Search code examples
amazon-web-servicesamazon-ec2terraformautoscaling

Can an EC2 instance find out what launch template OR autoscaling group it's been launched with?


I have an AMI that I'm using for 3 different autoscaling groups, each using a copy-pasted launch template with only "name" differing - I couldn't find a way to "inherit" that stuff. It's all configured through terraform.

I'd like to find out, upon instance bootup, what group or launch template it's been launched with, so I can start needed services accordingly. I'm not keen about maintaining 3 different AMIs for that purpose.

Is there a way? I couldn't find anything in the meta-data.

Thanks!


Solution

  • The EC2 autoscaling API has an action named DescribeAutoScalingInstances which seems to return the information you want.

    Given an EC2 instance ID, it returns an AutoScalingInstanceDetails object describing:

    • The autoscaling group that instance belongs to, if any.
    • The launch configuration or launch template used when starting it.
    • The availability zone it is running in.
    • Its lifecycle state and healthcheck status.
    • Its "scale in protection" flag.

    Your EC2 instance will first need to discover its own instance ID, which it can find using the EC2 metadata API called from its own private network interface.

    You can give your EC2 instance access to call the autoscaling API by creating an IAM role with access to at least that API action and then associating it with your instance using an "IAM instance profile", which then allows your instance to acquire temporary AWS API credentials using information from the EC2 metadata API.