Find EC2 instances that not equal to X – AWS CLI

Question:

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".

Asked By: hightest

||

Answers:

Just remove the filter and iterate over all the instances and inside the code add an if condition on the platform key.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import boto3

ec2 = boto3.client("ec2", region_name="eu-central-1")
response = ec2.describe_instances()
instances = response["Reservations"]

for each_res in response["Reservations"]:
    for each_inst in each_res["Instances"]:
        platform = each_inst.get('Plaform')
        instance_id  = each_inst.get('InstanceId')
        if platform == 'Windows':
            response = ec2.create_tags(
                Resources=[instance_id],
                    Tags = [
                        {
                            'Key' : 'test',
                            'Value': 'test01'
                        }
                    ]
                )
        else:
            print(f'found non windows intance: {instance_id}')
            response = ec2.create_tags(
                Resources=[instance_id],
                    Tags = [
                        {
                            'Key' : 'nonwindow',
                            'Value': 'nonwindowvalue'
                        }
                    ]
                )

As per the API docs

The value is Windows for Windows instances; otherwise blank.

Code is working correctly I tested:

$ python3 describe_instances.py
found non windows intance: i-0ba1a62801c895

describe_instances

Response structure received from the describe_instnaces call

{
    'Reservations': [
        {
            'Groups': [
                {
                    'GroupName': 'string',
                    'GroupId': 'string'
                },
            ],
            'Instances': [
                {
                    'AmiLaunchIndex': 123,
                    'ImageId': 'string',
                    'InstanceId': 'string',
                     ....
                    'Platform': 'Windows',
                    'PrivateDnsName': 'string',
                    'PrivateIpAddress': 'string',
                    'ProductCodes': [
                    ....
Answered By: samtoddler

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