Jeff Gruenbaum
Jeff Gruenbaum

Reputation: 403

How to use gnupg python library within Docker container for AWS Lambda Function

I am trying to run a python lambda function that is being deployed as a docker container. The purpose of the function is to connect to an ftp server, retrieve encrypted files, and then decrypt them. The part that is causing issues is the decryption. I am using gpg for the decryption with the use of a private key.

I was able to setup gpg and my python code with my aws lambda docker container as following:

FROM amazon/aws-lambda-python:3.9
RUN yum update
RUN yum install -y gnupg
RUN yum -y install gcc g++ sudo
COPY requirements.txt  .
RUN  pip3 install -r requirements.txt --target "${LAMBDA_TASK_ROOT}"

COPY . ${LAMBDA_TASK_ROOT}

CMD [ "app.handler" ] 

But after getting gnupg installed inside the container. I was not able to successfully import keys and decrypt files. I kept receiving errors, such as:

gpg: Fatal: can't create directory /home/sbx_user1051/.gnupg: No such file or directory

and this error:

gpg returned a non-zero error code: 2

I am using python3.9 with the library python-gnupg, which is built off the gnupg binary. The errors mentioned above took place when I tried the following:

import gnupg
my_gpg = gnupg.GPG(gpgbinary="/usr/bin/gpg")
my_gpg.import_keys_file("/var/task/keys/priv_key.asc", passphrase=os.getenv("PASSPHRASE"))

How can I avoid these errors and successfully import the priv_key to my gpg keyring?

Upvotes: 1

Views: 1288

Answers (1)

Jeff Gruenbaum
Jeff Gruenbaum

Reputation: 403

After a lot of headbanging, I was able to find a simple solution to this problem.

While grabbing the gpg binary in python, you can set its homedir. I believe the gpg binary did not have proper permissions to create/read files, which caused the errors, so I set the homedir to the /tmp directory which has full read/write permissions in lambda containers. So now my code looks like this and it runs without any issues.

import gnupg
my_gpg = gnupg.GPG(gpgbinary="/usr/bin/gpg", gnupghome="/tmp")
my_gpg.import_keys_file("/var/task/keys/priv_key.asc", passphrase=os.getenv("PASSPHRASE"))

Upvotes: 1

Related Questions