2 years ago
#61592
Johannes
How to pass secrets/environment variables to Amplify Serverless Docker Container (Dockerfile)
I'm provisioning a serverless container (FastAPI) backend through Amplify (see https://docs.amplify.aws/cli/usage/containers/ ). I'm using the 'Deploy single container' workflow (https://docs.amplify.aws/cli/usage/containers/#deploy-a-single-container). Now I try to figure out how to pass secrets and environment variables to the running docker container. There is documentation for this about the docker-compose / multiple container case but the equivalent functionality seems to be missing in the single Dockerfile case ( https://docs.amplify.aws/cli/usage/containers/#environment-variables-and-secrets).
I'd like to pull some secrets from Secrets Manager and pass some env variables.
What I've done:
- Modify custom-policies.json to allow access to the specific secret
- Hardcode the secret name as an env variable into the Dockerfile
- Now I can use boto3 in the running (python) container to retrieve the secret by name.
This works but it's a hack. Are there alternatives? E.g. the docs have a much more elegant approach for the docker-compose case. I'd like to e.g. override the ECR functionality of using the 'secrets' and 'environment' parameter in the container definition.
I tried overriding the 'apiname-cloudformation-template.json'. It contains the container definition with an empty 'secrets' parameter. I've added the secrets there as per the ECS docs, but this file gets overwritten on running 'amplify push'.
custom-policies.json:
[
{
"Action": [
"secretsmanager:GetSecretValue"
],
"Resource": [
"arn:aws:secretsmanager:us-east-1:<id>:secret:<secret name>"
]
}
]
Dockerfile:
FROM public.ecr.aws/docker/library/python:3.9
RUN apt-get update && apt-get install -y git
WORKDIR /code
COPY ./requirements_docker.txt /code/requirements.txt
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
COPY ./app /code/app
ENV AWSSECRET=<secret name>
EXPOSE 80
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
Python snippet for retrieving secret and setting as env variable:
import boto3
secretsmanager_client = boto3.client('secretsmanager', region_name='us-east-1')
resp = secretsmanager_client.get_secret_value(SecretId=os.environ['AWSSECRET'])
secret_dict = eval(resp['SecretString'])
for key, value in secret_dict.items():
os.environ[key] = value
python
docker
aws-amplify
aws-secrets-manager
0 Answers
Your Answer