Search code examples
pythonpython-2.7amazon-web-servicesboto3autoscaling

List out auto scaling group names with a specific application tag using boto3


I was trying to fetch auto scaling groups with Application tag value as 'CCC'.

The list is as below,

gweb
prd-dcc-eap-w2
gweb
prd-dcc-emc
gweb
prd-dcc-ems
CCC
dev-ccc-wer
CCC
dev-ccc-gbg
CCC
dev-ccc-wer

The script I coded below gives output which includes one ASG without CCC tag.

#!/usr/bin/python
import boto3

client = boto3.client('autoscaling',region_name='us-west-2')

response = client.describe_auto_scaling_groups()

ccc_asg = []

all_asg = response['AutoScalingGroups']
for i in range(len(all_asg)):
    all_tags = all_asg[i]['Tags']
    for j in range(len(all_tags)):
        if all_tags[j]['Key'] == 'Name':
                asg_name = all_tags[j]['Value']
        #        print asg_name
        if all_tags[j]['Key'] == 'Application':
                app = all_tags[j]['Value']
        #        print app
        if all_tags[j]['Value'] == 'CCC':
                ccc_asg.append(asg_name)

print ccc_asg

The output which I am getting is as below,

['prd-dcc-ein-w2', 'dev-ccc-hap', 'dev-ccc-wfd', 'dev-ccc-sdf']

Where as 'prd-dcc-ein-w2' is an asg with a different tag 'gweb'. And the last one (dev-ccc-msp-agt-asg) in the CCC ASG list is missing. I need output as below,

dev-ccc-hap-sdf
dev-ccc-hap-gfh
dev-ccc-hap-tyu
dev-ccc-mso-hjk

Am I missing something ?.


Solution

  • I got it working with below script.

    #!/usr/bin/python
    import boto3
    
    client = boto3.client('autoscaling',region_name='us-west-2')
    
    response = client.describe_auto_scaling_groups()
    
    ccp_asg = []
    
    all_asg = response['AutoScalingGroups']
    for i in range(len(all_asg)):
        all_tags = all_asg[i]['Tags']
        app = False
        asg_name = ''
        for j in range(len(all_tags)):
            if 'Application' in all_tags[j]['Key'] and all_tags[j]['Value'] in ('CCP'):
                    app = True
            if app:
                    if 'Name' in all_tags[j]['Key']:
                            asg_name = all_tags[j]['Value']
                            ccp_asg.append(asg_name)
    print ccp_asg
    

    Feel free to ask if you have any doubts.