TIL: AWS SSM to environment variables
Today I learned (TIL) a way to make creating .env files easier
from the AWS Secrets service.
It's common to have to validate something in the application using data from the test or staging environment. In my case:
- I have to access the aws console.
- Go to the service page.
- Look for the secret.
- Click to get the data
- Convert the data from Json to a readable .env format.
- Put the converted data in a
.envfile.
It gets tedious when you are working on 2 or 3 projects.
The solution using aws-cli and
jq is enough to build the
.env file.
The command
aws secretsmanager get-secret-value --secret-id "SECRET_ID" \
--query SecretString --output text | \
jq -r 'to_entries | .[] | "\(.key)=\(.value|tostring)"' > .env
What does it do?
Basically the Secrets Manager response is this:
{
"VARIAVEL_DE_AMBIENTE": "VALOR",
"VARIAVEL_DE_AMBIENTE1": "VALOR1"
}
to_entries: Converts the data above to{"key": "VARIAVEL_DE_AMBIENTE", "value": "VALOR"}.[]: I use this filter to return [{}] and not just the object.\(.key)=\(.value|tostring): I access the key and value of the previous data, build a key=value output and convert every value to string.
In the end I get an output like this:
VARIAVEL_DE_AMBIENTE=VALOR
VARIAVEL_DE_AMBIENTE1=VALOR1
Extra
It's possible to build a shell function to make the command more dynamic, but I'll leave that to you =].