0
votes

I am trying to get value of Tag key AutoScalingGroupName of instance. Python boto3 script fails with syntax error.

Here is my sample script.

#!/bin/python3.4
import requests
import boto3
import botocore.session
import urllib.request

ec2 = boto3.client('ec2', region_name='us-west-1', aws_access_key_id='****************', aws_secret_access_key='****************************')
liid = urllib.request.urlopen('http://169.254.169.254/latest/meta-data/instance-id').read().decode()
autoinstinfo = ec2.describe_instances(InstanceIds=[liid], Filters=[{'Name':'tag:AutoScalingGroupName', 'Values':['%s']} % ['AutoScalingGroupName']).get( 'Reservations', [] )
print(autoinstinfo)

Fails with this error message.

python3.4 ./test.py

File "./test.py", line 9 autoinstinfo = ec2.describe_instances(InstanceIds=[liid], Filters=[{'Name':'tag:AutoScalingGroupName', 'Values':['%s']} % (AutoScalingGroupName)).get( 'Reservations', [] ) ^ SyntaxError: invalid syntax

2

2 Answers

1
votes

Why do you want to use string format when you know the tag name? Why can't the following work?

ec2.describe_tags(Filters=[{'Name':'resource-id', 'Values':[liid]}, {'Name':'key', 'Values':['AutoScalingGroupName']}])['Tags'][0]['Value']
1
votes
`import boto3

ec2 = boto3.resource('ec2')
client = boto3.client('ec2')

response = client.describe_instances()

for r in response['Reservations']:
    for instance in r['Instances']:
        Tags = instance['Tags'][0]['Key']
        print(Tags)`

Above script will give you tags-key of all instances in your aws account.