skip to Main Content

So, I have this code, and I will love to grab the public IP address of the new windows instance that will be created when I adjust the desired capacity.
The launch template assigns an automatic tag name when I adjust the desired_capacity. I want to be able to grab the public IP address of that tag name.

import boto3

session = boto3.session.Session()
client = session.client('autoscaling')


def set_desired_capacity(asg_name, desired_capacity):
    response = client.set_desired_capacity(
        AutoScalingGroupName=asg_name,
        DesiredCapacity=desired_capacity,
    )
    return response


def lambda_handler(event, context):
    asg_name = "test"
    desired_capacity = 1
    return set_desired_capacity(asg_name, desired_capacity)


if __name__ == '__main__':
    print(lambda_handler("", ""))

I took a look at the EC2 client documentation, and I wasn’t sure what to use. I just need help modifying my code

2

Answers


  1. If you know the tag that you are assigning in the autoscaling group, then you can just use a describe_instances method. The Boto3 docs have an example with filtering. Something like this should work, replacing TAG, VALUE, and TOPICARN with the appropriate values.

    import boto3
    
    ec2_client = boto3.client('ec2', 'us-west-2')
    sns_client = boto3.client('sns', 'us-west-2')
    
    response = ec2_client.describe_instances(
    Filters=[
        {
            'Name': 'tag:TAG',
            'Values': [
                'VALUE'
            ]
        }
    ]
    )
    
    for reservation in response["Reservations"]:
        for instance in reservation["Instances"]:
            ip = instance["PublicIpAddress"]
            sns_publish = sns_client.publish(
                TopicArn='TOPICARN',
                Message=ip,
            )
            print(sns_publish)
    
    
    Login or Signup to reply.
  2. Objective:

    • After an EC2 instance starts
    • Obtain the IP address
    • Send a message via Amazon SNS

    It can take some time for a Public IP address to be assigned to an Amazon EC2 instance. Rather than continually calling DescribeInstances(), it would be easier to Run commands on your Linux instance at launch – Amazon Elastic Compute Cloud via a User Data script.

    The script could:

    IP=$(curl 169.254.169.254/latest/meta-data/public-ipv4)
    
    • Send a message to an Amazon SNS topic with:
    aws sns publish --topic-arn xxx  --message $IP
    

    If you also want the message to include a name from a tag associated with the instance, the script will need to call aws ec2 describe-instances with its own Instance ID (which can be obtained via the Instance Metadata) and then extra the name from the tags returned.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search