Search code examples
amazon-web-servicesenvironment-variablesamazon-cognitoaws-sam

How to use environment variables to put them in AWS SAM template


I have a AWS SAM template that has lines like this

Parameters:
    GoogleClientId:
        Description: 'Required. The Google client id'
        Type: 'String'
        NoEcho: true

    GoogleClientSecret:
        Description: 'Required. The Google client password'
        Type: 'String'
        NoEcho: true

Resources:
...
  GoogleProvider:
    Type: AWS::Cognito::UserPoolIdentityProvider
    Properties:
      AttributeMapping: {
        "name": "name",
        "family_name": "family_name",
        "email": "email",
        "username": "sub",
      }
      ProviderDetails: {
         "client_id" : !Ref GoogleClientId,
         "client_secret": !Ref GoogleClientSecret,
         "authorize_scopes": "openid profile email",
      }
      ProviderName: Google
      ProviderType: Google
      UserPoolId: !Ref ScreenshotUserPool
...

I don’t want to keep the Google secret in the clear, I have it in the .env file.

I found an option with parameters, but I don’t want to re-enter the parameters with each deployment, is there a way to automatically pull the variable from the environment? thanks to all


Solution

  • This depends on your current deployment process.

    For local development using the .env environment is your best bet though.

    For deployments you can use AWS Secrets Manager to retrieve the sensitive information (specifically using get-secret-value) and pass it in using the parameter-overrides flag with sam deploy.

    You can wrap this up in a bash script and have that be executed when you're ready for a deployment, the below is just an example pseudocode.

    # deploy.sh file
    
    # retrieve secret from AWS Secrets Manager
    # you can use jq to extract specifics if you're storing a JSON
    GOOGLE_CLIENT_SECRET=$(aws secretsmanager get-secret-value --secret-id MyGoogleClientSecret --output text)
    
    # build
    sam build
    
    # deploy
    sam deploy \
    --stack-name {STACK_NAME} \
    --parameter-overrides GoogleClientSecret=$GOOGLE_CLIENT_SECRET \
    --no-confirm-changeset
    

    Note --no-confirm-changeset will result in a deployment without the prompt to confirm, use cautious.