AWS Elastic Beanstalk - switching environment variables between environments

Viewed 1478

I am using Elastic Beanstalk's aws:elasticbeanstalk:application:environment namespace to configure my environment with env vars. How can I set different values for different environments (e.g. development versus production)?

Development:

option_settings:
  aws:elasticbeanstalk:application:environment:
    REDIS_HOST: localhost

Production:

option_settings:
  aws:elasticbeanstalk:application:environment:
    REDIS_HOST: prod.redis.server.com
2 Answers

The AWS CLI has a convenient way of doing this for you as the update-environment command allows you to set env vars from a specially formatted json file. Create a separate json file for each environment you will be deploying to.

Example json file named deploy-dev.json:

[
  {
    "Namespace": "aws:elasticbeanstalk:application:environment",
    "OptionName": "NODE_ENV",
    "Value": "dev"
  },
  {
    "Namespace": "aws:elasticbeanstalk:application:environment",
    "OptionName": "LOG_LEVEL",
    "Value": "silly"
  }
]

Deploy app and then update env vars:

aws elasticbeanstalk create-application-version --application-name "$EB_APP_NAME" --version-label "$EB_VERSION"
aws elasticbeanstalk update-environment --environment-name "$EB_ENV_NAME" --version-label "$EB_VERSION" --option-settings file://.ebextensions/deploy-dev.json

How it's changed depends on your deployment method.

One option you can use is to set a bogus value in your .config file:

option_settings:
  aws:elasticbeanstalk:application:environment:
    REDIS_HOST: change me

Then, after deployment, modify the variable either using the AWS Management Console or using the EB CLI:

eb setenv REDIS_HOST=prod.redis.server.com

If you are using CloudFormation to deploy your EB application, you can feed the value as part of the OptionSettings field in your CloudFormation template:

    "EBConfigurationTemplate" : {
        "Type" : "AWS::ElasticBeanstalk::ConfigurationTemplate",
        "Properties" : {
            "ApplicationName" : {
                "Ref" : "EBApplication"
            },
            "Description"     : "Configuration Template",
            "OptionSettings"  : [
                {
                    "Namespace" : "aws:elasticbeanstalk:application:environment",
                    "OptionName" : "REDIS_HOST",
                    "Value"      : {
                        "Ref" : "RedisHostInputParameter"
                    }
                },
            ]

There are probably other methods too, but they will depend on the method of deployment.

Related