Search code examples
amazon-web-servicesamazon-ec2aws-cliamazon-efs

What is the best way to get the private IP addresses of other ec2's in an autoscaling group while on one of the ec2 instances?


I need to update a config file in a shared EFS drive with all of the private IP addresses of the current autoscaling group.

The approach I'm thinking is to run a user data script that queries the ASG for the private IP addresses then echo that into the config file. To do that the ec2 needs to have AWS CLI credentials and appropriate read-only access. Ideally, I don't want to store any credentials on this ec2.

Is there another way? Possibly VPC Endpoint or something?

Thanks!


Solution

  • You are asking two questions.

    How do I provide credentials securely to an EC2 instance?

    You use IAM Roles and assign the role to your EC2 instances. Then use the instance credentials in your code. The CLI examples below will automatically pick up these credentials.

    Using an IAM Role to Grant Permissions to Applications Running on Amazon EC2 Instances

    How do I get the private IP address of EC2 instances in an Auto Scaling Group (ASG)?

    1. You need to get a list of instances attached to your ASG.
    2. For each instance in your ASG call the describe API and extract the private IP address.

    Example commands:

    aws autoscaling describe-auto-scaling-groups --auto-scaling-group-name my-auto-scaling-group
    
    aws ec2 describe-instances --instance-ids i-1234567890abcdef0
    

    You can filter the command output. For example add the following to the second command to just display the private IP address:

    --query 'Reservations[*].Instances[*].PrivateIpAddress'
    

    Recommendation: I would use the Python SDK and write a simple program that provides these features and updates your config file.