0

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))
4
  • 1
    FYI, I created a Simple EC2 Stopinator in Lambda - DEV Community that can stop/terminate instances based on tag. Feel free to use the code. Commented Feb 3, 2021 at 22:06
  • I tried but it does not seem to work could you post it down below :). I tried to create a JSON policy that would specify only to allow the stopping or starting based on certain tags but I need to filter out tags more specifically for tags I dont want etc.. Commented Feb 4, 2021 at 15:18
  • import boto3 region = 'us-east-1' ec2 = boto3.client('ec2') instances = ['i-018b3ee8dd8b9fes5'] def lambda_handler(event,context): ec2.stop_instances(InstanceIds=instances) Commented Feb 4, 2021 at 15:19
  • Thats what I have and it works. I have tried many different variations of filters, sorting by keys, etc.. and nothing seems to work. I am still sort of new so trying to learn but am getting upset when code that would normally work will not compile :( Commented Feb 4, 2021 at 15:20

1 Answer 1

1

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
  }
}
Sign up to request clarification or add additional context in comments.

13 Comments

is that python 3.7 or 3.6 im using 3.6 and got some errors currently debugging and tidying up. Also, shouldn't the tag 'Name' field be Key??
ec2.stop_instances*
@robby I just typed the code here, to give nudge you in the correct direction. When you prepare the filter you provide the tags in the above format. Like filters = [{'Name':'tag:environment', 'Values':[Env]}, {'Name':'tag:role', 'Values':[Role]} ]
actually it says im not able to use filter parameter in ec2.stop_instances... :( thanks for the help! if you can think of anything else please let me know!
@robby stop_instances doesnt support custom filters. In my code above I am pasing Instances
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.