CDP-cdp
CDP-cdp

Reputation: 75

Boto3 EC2 instance filter with tag

I would like to use a variable collected as part of python script in the place of KEY in tag:key. I find no luck. Below is my code. But the value part works.

tag_key_f = input("Enter Tag Name to find: ")
tag_val_f = input("Enter Tag Value to find: ")
instances = ec2.describe_instances(Filters=[{'Name': 'tag:tag_key_f', 'Values': [tag_val_f]}])

Upvotes: 2

Views: 5838

Answers (2)

arun n a
arun n a

Reputation: 906

import boto3

tag_key_name = "JobNumber" # replace it with your tag key name
values = ["Job123"]

client = boto3.client('ec2', aws_access_key_id=Config.AWS_ACCESS_KEY_ID, 

aws_secret_access_key=Config.AWS_SECRET_ACCESS_KEY)
instances = client.describe_instances(Filters=[{'Name': f'tag:{tag_key_name}', 'Values': values}])

This query worked for me to fetch the ec2 machines with a specific tag filter.

Upvotes: 0

CDP-cdp
CDP-cdp

Reputation: 75

This was fixed just by adding a separator.

tag_key_f = input("Enter Tag Name to find: ")
tag_val_f = input("Enter Tag Value to find: ")
instances = ec2.describe_instances(Filters=[{'Name': 'tag:'+tag_key_f, 'Values': [tag_val_f]}])

Upvotes: 4

Related Questions