Issue
I'm looking to find instances that is not equal to platform "Windows" and tag them with specific tags.
For now i have this script that is tagging the instances that are equal to platform "Windows":
import boto3
ec2 = boto3.client('ec2')
response = ec2.describe_instances(Filters=[{'Name' : 'platform', 'Values' : ['windows']}])
instances = response['Reservations']
for each_res in response['Reservations']:
for each_inst in each_res['Instances']:
for instance in instances:
response = ec2.create_tags(
Resources=[each_inst['InstanceId']],
Tags = [
{
'Key' : 'test',
'Value': 'test01'
}
]
)
I need help to add a block to this script that will add another tag only to EC2 instance that is NOT equal to platform "Windows".
Solution
Try this. Working for me. Also, Running create_tags inside the for loop, you are executing one API for each resource. Whereas create_tags supports multiple resource as input. Reference : https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.create_tags
import boto3
#Initialize an empty list to store non windows instance IDs.
list_nonwindows = []
ec2 = boto3.client("ec2", region_name="us-east-1")
response = ec2.describe_instances()
instances = response["Reservations"]
for each_res in response["Reservations"]:
for each_inst in each_res["Instances"]:
if each_inst.get('Platform') == None:
instance_s = each_inst.get('InstanceId')
list_nonwindows.append(instance_s)
response = ec2.create_tags(
Resources=list_nonwindows,
Tags = [
{
'Key' : 'test',
'Value': 'test01'
}
]
)
Answered By - Justin Thomas Answer Checked By - Mildred Charles (WPSolving Admin)