'how to get the instance ids in a autoscaling group using AWS Lambda function Python

I'm new to coding I want to get the instance ids of an autoscaling group using AWS lambda function



Solution 1:[1]

You can use this boto3 client method for getting instance ids in an auto-scaling group.

import boto3
client = boto3.client('autoscaling')


def lambda_handler(event, context):
    response = client.describe_auto_scaling_groups(
        AutoScalingGroupNames=[
            'string',
        ],
        MaxRecords=50
    )
    instances = response['AutoScalingGroups'][0]['Instances']
    for i in range(len(instances)):
      print(instances[i]['InstanceId'])

If you have more than 1 auto-scaling-group then you have to keep this line in a loop:

response['AutoScalingGroups'][0]['Instances']

replacing '0' with the loop variable.

If you want something more from the response:

Here is the complete response returned by this method.

{
    'AutoScalingGroups': [
        {
            'AutoScalingGroupName': 'string',
            'AutoScalingGroupARN': 'string',
            'LaunchConfigurationName': 'string',
            'LaunchTemplate': {
                'LaunchTemplateId': 'string',
                'LaunchTemplateName': 'string',
                'Version': 'string'
            },
            'MixedInstancesPolicy': {
                'LaunchTemplate': {
                    'LaunchTemplateSpecification': {
                        'LaunchTemplateId': 'string',
                        'LaunchTemplateName': 'string',
                        'Version': 'string'
                    },
                    'Overrides': [
                        {
                            'InstanceType': 'string',
                            'WeightedCapacity': 'string',
                            'LaunchTemplateSpecification': {
                                'LaunchTemplateId': 'string',
                                'LaunchTemplateName': 'string',
                                'Version': 'string'
                            }
                        },
                    ]
                },
                'InstancesDistribution': {
                    'OnDemandAllocationStrategy': 'string',
                    'OnDemandBaseCapacity': 123,
                    'OnDemandPercentageAboveBaseCapacity': 123,
                    'SpotAllocationStrategy': 'string',
                    'SpotInstancePools': 123,
                    'SpotMaxPrice': 'string'
                }
            },
            'MinSize': 123,
            'MaxSize': 123,
            'DesiredCapacity': 123,
            'DefaultCooldown': 123,
            'AvailabilityZones': [
                'string',
            ],
            'LoadBalancerNames': [
                'string',
            ],
            'TargetGroupARNs': [
                'string',
            ],
            'HealthCheckType': 'string',
            'HealthCheckGracePeriod': 123,
            'Instances': [
                {
                    'InstanceId': 'string',
                    'InstanceType': 'string',
                    'AvailabilityZone': 'string',
                    'LifecycleState': 'Pending'|'Pending:Wait'|'Pending:Proceed'|'Quarantined'|'InService'|'Terminating'|'Terminating:Wait'|'Terminating:Proceed'|'Terminated'|'Detaching'|'Detached'|'EnteringStandby'|'Standby'|'Warmed:Pending'|'Warmed:Pending:Wait'|'Warmed:Pending:Proceed'|'Warmed:Terminating'|'Warmed:Terminating:Wait'|'Warmed:Terminating:Proceed'|'Warmed:Terminated'|'Warmed:Stopped'|'Warmed:Running',
                    'HealthStatus': 'string',
                    'LaunchConfigurationName': 'string',
                    'LaunchTemplate': {
                        'LaunchTemplateId': 'string',
                        'LaunchTemplateName': 'string',
                        'Version': 'string'
                    },
                    'ProtectedFromScaleIn': True|False,
                    'WeightedCapacity': 'string'
                },
            ],
            'CreatedTime': datetime(2015, 1, 1),
            'SuspendedProcesses': [
                {
                    'ProcessName': 'string',
                    'SuspensionReason': 'string'
                },
            ],
            'PlacementGroup': 'string',
            'VPCZoneIdentifier': 'string',
            'EnabledMetrics': [
                {
                    'Metric': 'string',
                    'Granularity': 'string'
                },
            ],
            'Status': 'string',
            'Tags': [
                {
                    'ResourceId': 'string',
                    'ResourceType': 'string',
                    'Key': 'string',
                    'Value': 'string',
                    'PropagateAtLaunch': True|False
                },
            ],
            'TerminationPolicies': [
                'string',
            ],
            'NewInstancesProtectedFromScaleIn': True|False,
            'ServiceLinkedRoleARN': 'string',
            'MaxInstanceLifetime': 123,
            'CapacityRebalance': True|False,
            'WarmPoolConfiguration': {
                'MaxGroupPreparedCapacity': 123,
                'MinSize': 123,
                'PoolState': 'Stopped'|'Running',
                'Status': 'PendingDelete'
            },
            'WarmPoolSize': 123
        },
    ],
    'NextToken': 'string'
}

To know more, please refer to this documentation : https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/autoscaling.html#AutoScaling.Client.describe_auto_scaling_groups

Solution 2:[2]

You can try using the boto3 library and get the information using the API as mentioned here: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/autoscaling.html#AutoScaling.Client.describe_auto_scaling_instances

Something like this could work

import boto3
import json

client = boto3.client('autoscaling')


def lambda_handler(event, context):
 get_response = client.describe_auto_scaling_instances(
                 InstanceIds= '*Your Autoscaling Instance Id*'
                 )

 instance_id = get_response['AutoScalingInstances'][0]['InstanceId']
  

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 KnowledgeGainer
Solution 2 Naman