Last active
September 2, 2019 17:31
-
-
Save alertedsnake/4b85ea44481f518cf157 to your computer and use it in GitHub Desktop.
Get a list of instances in an AWS autoscaling group, with boto3. I set MaxRecords=2 to experiment with the pagination, it does seem to return the whole list when not set, but.....
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
def as_get_instances(client, asgroup, NextToken = None): | |
# this is downright ridiculous because boto3 sucks | |
irsp = None | |
if NextToken: | |
irsp = client.describe_auto_scaling_instances(MaxRecords=2, NextToken=NextToken) | |
else: | |
irsp = client.describe_auto_scaling_instances(MaxRecords=2) | |
for i in irsp['AutoScalingInstances']: | |
if i['AutoScalingGroupName'] == asgroup: | |
yield i['InstanceId'] | |
if 'NextToken' in irsp: | |
for i in as_get_instances(client, asgroup, NextToken = irsp['NextToken']): | |
yield i | |
if __name__ == '__main__': | |
client = boto3.client('autoscaling', region_name='us-east-1') | |
print(list(as_get_instances(client, 'content_server'))) |
You should be able to make this a tiny bit cleaner via get_paginator
A very basic approach (you can max PageSize
to 50 in production):
import boto3
def asg_get_instances(asgroup):
awsclient = boto3.client('autoscaling')
asg_paginator = awsclient.get_paginator("describe_auto_scaling_instances")
asg_page_iterator = asg_paginator.paginate( PaginationConfig={'PageSize':1, 'StartingToken': None } )
asg_instances = []
for asg_page in asg_page_iterator:
all_asg_instances += asg_page['AutoScalingInstances']
res = []
for ec2 in all_asg_instances:
if ec2['AutoScalingGroupName'] == asgroup:
res += ec2
return res
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You should be able to make this a tiny bit cleaner via get_paginator