Get AWS EC2 tags to environment parameters for apache2

Objective:

  • AWS instances are assigned tags per instance.
  • Need tags to be environment parameters for Apache2; thus, web application can retrieve environment parameter.

 

Step 1: Configure tags in AWS EC2 instance

 

aws_ec2_tag

Step 2: Setup IAM user and get access key id and secret access key

 

Step 3: Access to SSH and append following shell scripts

$ sudo apt-get install -y jq curl awscli
$ sudo nano /etc/apache2/envvars

Append following script to /etc/apache2/envvars

  • Note that you need to replace AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_DEFAULT_REGION
  • Note that you need  to update allowed_tag variable if you want to add different tag name rather than ENVIRONMENT
######
# Customized By CL
# Original Author: Marcello de Sales (marcello.desales@gmail.com)
# Reference: https://github.com/12moons/ec2-tags-env/blob/master/import-tags.sh
### Requirements:
# 1. Install jq library (sudo apt-get install -y jq)
# 2. Configure IAM for permission AmazonEC2ReadOnlyAccess
### Installation:
# 1. Add tags to an EC2 host or Image Profile
# 2. Append following scripts to /etc/apache2/envvars
# 3. Restart apache2
# 4. Access to web application to get environment parameters
####

export AWS_ACCESS_KEY_ID=XXXXXXXXXX
export AWS_SECRET_ACCESS_KEY=XXXXXXXXXX
export AWS_DEFAULT_REGION=ap-southeast-2

# get instance tags
instance_id=$(/usr/bin/curl --silent http://169.254.169.254/latest/meta-data/instance-id)
instance_tags=$(aws ec2 describe-tags --filters "Name=resource-id,Values=$instance_id")

ami_id=$(/usr/bin/curl --silent http://169.254.169.254/latest/meta-data/ami-id)
ami_tags=$(aws ec2 describe-tags --filters "Name=resource-id,Values=$ami_id")

tags_to_env () {
    tags=$1

    for key in $(echo $tags | /usr/bin/jq -r ".[][].Key"); do
        value=$(echo $tags | /usr/bin/jq -r ".[][] | select(.Key==\"$key\") | .Value")
        key=$(echo $key | /usr/bin/tr '-' '_' | /usr/bin/tr '[:lower:]' '[:upper:]')

        allowed_tag=$(echo "ENVIRONMENT")
        if [ "${allowed_tag}" = "${key}" ] ; then
                export $key="$value"
        fi
    done
}

tags_to_env "$ami_tags"
tags_to_env "$instance_tags"

 

Step 4: Restart Apache2

$ sudo /etc/init.d/apache2 restart

 

Step 5: Check environment parameters

<?php
    $environment = getenv('ENVIRONMENT');
    echo "environment => ".$environment.PHP_EOL;