Robert Benedetto
Robert Benedetto

Reputation: 1710

Get current Environment name

I have an AWS question: I have an application running on Beanstalk. I have two environments, XXX-LIVE and XXX-TEST.

I would like to know how I can get the Environment name using the SDK, since I want to point to my test database if the code is running on the XXX-TEST environment?

So far I have only found the .RetrieveEnvironmentInfo() method of the object AWSClientFactory.CreateAmazonElasticBeanstalkClient();

But this requires that you provide the Environment name/ID.

Can anyone help?

Upvotes: 1

Views: 2090

Answers (2)

PressingOnAlways
PressingOnAlways

Reputation: 12356

Here's how we do it for our application in ruby:

  def self.beanstalk_env
    begin
      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'
              return tag.value
            end
          end
        end
      end
    rescue

    end
    'No_Env'
  end

Your instance's IAM-policy will have to allow ec2:describe:

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

Upvotes: 4

kukido
kukido

Reputation: 10601

You can add custom "environment-name" parameter to both environments. Set the value to the name of the environment or just specify "test" or "production".

enter image description here

If the database access URL is the only difference between the two, then set URL as a parameter and you will end up with identical code with no branches.

More details on customization can be found here: Customizing and Configuring AWS Elastic Beanstalk Environments

Upvotes: 0

Related Questions