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:

  1. I have to access the aws console.
  2. Go to the service page.
  3. Look for the secret.
  4. Click to get the data
  5. Convert the data from Json to a readable .env format.
  6. Put the converted data in a .env file.

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"
}

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 =].