PressingOnAlways
PressingOnAlways

Reputation: 12366

Detecting Elastic Beanstalk Environment?

I am trying to tag error messages by elastic beanstalk environment. Is there a way to programmatically determine what environment I am in from an EC2 instance inside the elastic beanstalk?

I am using ruby on rails so a ruby way would be nice, but I can port from any language.

Upvotes: 3

Views: 665

Answers (2)

smentek
smentek

Reputation: 2884

Whatever you are doing you should be focus on application environment name and not on its sourroundings elastic beanstalk environment name. So use elastic beanstalk environment variables, set sth like APP_ENV, and read it programmatically in whatever lagnuage you are using inside your app.

It is kind of the same principle like with Object Oriented Programming where you encapsulate your stuff to be independent from ther rest of the code. Internals of EB may change with next release, elastic beanstalk environment variables will be still there...

Upvotes: 1

ZeroInputCtrl
ZeroInputCtrl

Reputation: 169

I have a rails project and this is what we are currently doing inside in order to determine which environment our ec2 instance is a part of.

Below the code is doing more than one check, the file check makes sure that you are running this code on an ec2 instance. The second set of url calls are grabbing the ec2 instance id along with which aws region is being used. Then finally it uses the previous two pieces of data to find the environment-name using the aws-sdk. It's a little ugly but it gets the job done.

require 'net/http'
require 'aws-sdk'

uuid = File.readlines('/sys/hypervisor/uuid', 'r')
if uuid
    str = uuid.first.slice(0,3)
    if str == 'ec2'
        metadata_endpoint = 'http://169.254.169.254/latest/meta-data/'
        dynamic_endpoint = 'http://169.254.169.254/latest/dynamic/'
        instance_id = Net::HTTP.get( URI.parse( metadata_endpoint + 'instance-id' ) )
        document = Net::HTTP.get( URI.parse( dynamic_endpoint + 'instance-identity/document') )
        parsed_document = JSON.parse(document)
        region = parsed_document['region']
        ec2 = AWS::EC2::Client.new(region: region)
        ec2.describe_instances({instance_ids:[instance_id]}).reservation_set[0].instances_set[0].tag_set.each do |tag|
            if tag.key == 'elasticbeanstalk:environment-name'
                @env_name = tag.value
            end
        end
    end
end

Upvotes: 1

Related Questions