Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get an Amazon Elastic Beanstalk environment's name from inside one of its instances
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"ec2:Describe*"
],
"Effect": "Allow",
"Resource": "*"
}
]
}
#!/usr/bin/env python
import boto.utils
import boto.ec2
iid_doc = boto.utils.get_instance_identity()['document']
region = iid_doc['region']
instance_id = iid_doc['instanceId']
ec2 = boto.ec2.connect_to_region(region)
instance = ec2.get_only_instances(instance_ids=[instance_id])[0]
env = instance.tags['elasticbeanstalk:environment-name']
print(env)
@Melvin-mlp

This comment has been minimized.

Copy link

Melvin-mlp commented Mar 6, 2018

To help other people like me who came from google search, there is another way to perform this from your elasticbeanstalk instances without allowing all ec2:Describe actions

EC2-DescribeTags-IAM-policy.json

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "ec2:DescribeTags"
      ],
      "Effect": "Allow",
      "Resource": "*"
    }
  ]
}

Get environment name from bash script

get-eb-env-name.sh

#!/bin/bash
set -e

INSTANCE_ID=$(/opt/aws/bin/ec2-metadata -i | awk '{print $2}')
REGION=$(/opt/aws/bin/ec2-metadata -z | awk '{print substr($2, 0, length($2)-1)}')
TAG="elasticbeanstalk:environment-name"

aws ec2 describe-tags \
  --output text \
  --filters "Name=resource-id,Values=${INSTANCE_ID}" \
            "Name=key,Values=${TAG}" \
  --region "${REGION}" \
  --query "Tags[*].Value"

Below, the command line to get the environment name with one liner:

aws ec2 describe-tags \
  --output text \
  --filters "Name=resource-id,Values=$(/opt/aws/bin/ec2-metadata -i | awk '{print $2}')" \
            "Name=key,Values=elasticbeanstalk:environment-name" \
  --region "$(/opt/aws/bin/ec2-metadata -z | awk '{print substr($2, 0, length($2)-1)}')" \
  --query "Tags[*].Value"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment