Search code examples
amazon-web-servicesamazon-ec2environment-variablesamazon-elastic-beanstalk

How do I pass a system-defined Elastic Beanstalk environment variable (HOSTNAME) to an EC2 Docker container?


I have an Elastic Beanstalk application, managing some EC2 instances.

I would like to pass the environment variable HOSTNAME from the EC2 instance to the Docker container running on it. I can remote into the instance and echo $HOSTNAME, but I'm not sure how to pass the value to my app's Docker contianer.

The AWS docs describe how it passes environment variables, defined in the UI, when using Docker Compose, but it doesn't describe how it works for a non-Compose setup.

How can I pass HOSTNAME to the container running on EC

Platform: Docker running on 64bit Amazon Linux 2/3.6.5


Solution

  • (Tested on Docker running on 64bit Amazon Linux 2/3.6.5)

    Having a poke around in the logs for an EC2 instance, looking in eb-engine.log, you should find a line like this:

    2023/12/17 14:05:13.328497 [INFO] Running command /bin/sh -c docker run -d --env-file /opt/elasticbeanstalk/deployment/env.list   3a15af993d32
    

    Looks like Elastic Beanstalk will store environment variables in a file at /opt/elasticbeanstalk/deployment/env.list. We just need to modify this file before the container starts.


    You will need to make use of two platform hooks. One will run on any application deployment. The other will run on any config deployment.

    • In your codebase, create the directories .platform/hooks/predeploy and .platform/confighooks/predeploy.

    • Add a bash script file to each directory. I called mine 01-env-var-passthrough.sh. Paste this code into it:

      #!/usr/bin/env bash
      set -o errexit -o nounset -o pipefail -o verbose
      
      # Append a new line to the EC2 instance's environment variables
      envfile="/opt/elasticbeanstalk/deployment/env.list"
      
      echo "" >> $envfile
      echo "HOSTNAME=$HOSTNAME" >> $envfile
      
    • Ensure the .platform/ directory is included in your bundled application zip.