Skip to content

Instantly share code, notes, and snippets.

@SteelPangolin
Created January 30, 2015 21:23
Show Gist options
  • Save SteelPangolin/08880dc2c74b9c26cb5b to your computer and use it in GitHub Desktop.
Save SteelPangolin/08880dc2c74b9c26cb5b to your computer and use it in GitHub Desktop.
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)
@mlvnds
Copy link

mlvnds 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"

@SteelPangolin
Copy link
Author

Thanks for the refinement, @Melvin-mlp.

For those of you who did find this through Google, there's more detail in my blog article on how to find the name of an Elastic Beanstalk environment from inside one of its instances.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment