robby
robby

Reputation: 1

Lambda function Python 3.6 to shut off EC2 instance with specific tags

Here is what I have so far. I just need help creating if statement/for loop for comparing tags. My tags are: Key: 'Name', Value: 'TestServer'. Thanks!

import boto3

ec2 = boto3.resource('ec2')
#tag = ec2.Tag('i-018b3ee8dd8b9fed3','Name','TestServer1')

region = 'us-east-1'
instances = ['i-018b3ee8dd8b9fes4']
ec2 = boto3.client('ec2')

def lambda_handler(event, context):
    
    ec2.stop_instances(InstanceIds=instances )
    print('stopped your instances: ' + str(instances) +str(tag))

Upvotes: 0

Views: 1146

Answers (1)

samtoddler
samtoddler

Reputation: 9665

Prepare a filter based on your tags requirement and run the query, eventually iterate through the resource.

import boto3
# Connect to EC2
ec2 = boto3.client('ec2', region_name='us-east-1')
 

def lambda_handler(event,context):
    custom_filter = [{
        'Name':'tag:Name', 
        'Values': ['TestServer']}]
    instances_to_stop = []
    running_instances = ec2.describe_instances(Filters=custom_filter)
    for reservation in running_instances.get('Reservations'):
        for instance in reservation.get('Instances'):
            instances_to_stop.append(instance.get('InstanceId'))
    print(f'Stopping following instance Ids : {instances_to_stop}')
    response = ec2.stop_instances(InstanceIds=instances_to_stop)
    print(response)

Response:

{
  "StoppingInstances": [
    {
      "CurrentState": {
        "Code": 64,
        "Name": "stopping"
      },
      "InstanceId": "i-011ac4a33afdsadasd",
      "PreviousState": {
        "Code": 16,
        "Name": "running"
      }
    }
  ],
  "ResponseMetadata": {
    "RequestId": "35a3ab",
      "date": "Thu, 04 Feb 2021 16:35:38 GMT",
      "server": "AmazonEC2"
    },
    "RetryAttempts": 0
  }
}

Upvotes: 1

Related Questions