av0000
av0000

Reputation: 1967

Accessing process.env.secrets in Amplify Build Commands

I'm following these docs on Environment Secrets and am trying to access my secret in a build command to provide an api key for my Next.js app.

The docs say:

Accessing an environment secret during a build is similar to accessing environment variables, except that environment secrets are stored in process.env.secrets as a JSON string.

My parameter store has a secret at /amplify/{my-app-id-here}/dev/API_KEY

In local, when I can just use .env.local everything works fine, but when I try my "live" site I get:

{"error":{"message":"API key not configured"}}

Relevant Build Commands:

  phases:
    preBuild:
      commands:
        - npm ci
        - echo $SECRETS | grep -o '"API_KEY":"[^"]*' | sed 's/"API_KEY":"//g' > .env.local
    

I have tried $SECRETS, $PROCESS_ENV_SECRETS, ${process.env.secrets}, etc. but I keep getting the error. I think I am not properly accessing process.env.secrets but I am not sure.

I even tried just returning "process.env" and did not see the key there.

Upvotes: 5

Views: 1416

Answers (2)

Ritesh Nemade
Ritesh Nemade

Reputation: 11

I managed to access the variables declared in build settings as shown below.

To print all environment variables in build settings

printenv

If you want to print only secrets added in build settings

echo "Secrets:$secrets"

Accessing specific secret variable

variable_name=$(echo $secrets | grep -o '"<parameter_name>":"[^"]*' | grep -o '[^"]*$')

Also after accessing the variable you can use it as follows

$<variable_name>

Hope it helps!!!

Upvotes: 1

Webermku
Webermku

Reputation: 11

I had a similar issue doing this with a Vite project.

I managed to do it with the following AWS Amplify build settings (note, I use a backend for the app called "staging"):

build:
      commands:
        - export VITE_APP_SUPABASE_URL=$(aws ssm get-parameter --name "/amplify/[MY_PROJECT_ID]/staging/VITE_APP_SUPABASE_URL" --with-decryption --query "Parameter.Value" --output text)
        - export VITE_APP_SUPABASE_ANON_KEY=$(aws ssm get-parameter --name "/amplify/[MY_PROJECT_ID]/staging/VITE_APP_SUPABASE_ANON_KEY" --with-decryption --query "Parameter.Value" --output text)
        - yarn run build
        - npm run build

In this case there is a Vite specific thing that the .env variables have to start with "VITE_" in the standard configuration so I created new secretstring variables in the Parameter Store. Finally, the --with-decryption syntax shown above is needed to get the decrypted string.

Upvotes: 1

Related Questions