Pages

Thursday, February 22, 2024

 {

    "Version": "2024-02-17",

    "Statement": [

        {

            "Sid": "AllowLogCreation",

            "Effect": "Allow",

            "Action": [

                "logs:PutLogEvents",

                "logs:CreateLogStream",

                "logs:CreateLogGroup"

            ],

            "Resource": [

                "arn:aws:logs:*:*:*"

            ]

        },

        {

            "Sid": "AllowStartEc2",

            "Effect": "Allow",

            "Action": [

                "ec2:Stop*",

                "ec2:DescribeInstances"

            ],

            "Resource": [

                "*"

            ]

        }

    ]

  }

Wednesday, February 21, 2024

https://stackoverflow.com/questions/40040985/how-to-find-instances-that-dont-have-a-tag-using-boto3

 import boto3



client=boto3.client('ec2')



def lambda_handler(event, context):

    instances = [i for i in boto3.resource('ec2', region_name='ap-south-1').instances.all()]


    # Print instance_id of instances that do not have a Tag of Key='Foo'

    for i in instances:

        if i.tags is not None and 'resource' not in [t['Key'] for t in i.tags]:

            print (i.instance_id)

            ids=[]

            ids.append(i.instance_id)

            print (ids)

            client.stop_instances(InstanceIds=ids)

       #     client.stop_instances(i.instance_id)

 

    #ec2= boto3.resource('ec2', region_name = 'ap-south-1')

    #for each in ec2.instances.all():

     #   print (each.id)