Quantcast
Channel: Active questions tagged amazon-ec2 - Stack Overflow
Viewing all articles
Browse latest Browse all 29539

Create and Filter EC2 with Tags

$
0
0

Trying to create a Lambda function in AWS using Python 3.6, which creates an EC2 instance that gets terminated after a specific period of time. Since I am still very green with this, I chose to use 'Tags' to be used as a filter when terminating the instances.

However, I am having trouble figuring out a way to add the tag to the instance as its being generated.

My code for creating the EC2 is as follows

import os
import boto3

AMI = os.environ['AMI']
INSTANCE_TYPE = os.environ['INSTANCE_TYPE']
KEY_NAME = os.environ['KEY_NAME']
SUBNET_ID = os.environ['SUBNET_ID']

ec2 = boto3.resource('ec2')


def lambda_handler(event, context):

    instance = ec2.create_instances(
        ImageId=AMI,
        InstanceType=INSTANCE_TYPE,
        KeyName=KEY_NAME,
        SubnetId=SUBNET_ID,
        MaxCount=1,
        MinCount=1
    )

    print("New instance created...")

The environment variables are filled out manually

I also have a termination function, where it is supposed to filter out the EC2's created by the python script above with a Tag and terminate them

import os
import boto3

def lambda_handler(event, context):
    ec2 = boto3.resource('ec2')
    instances = ec2.instance.filter(Filters=[{"Name" :"tag:webserver", "Values":[delete] }])
    deleteInstances = [instance.id for instance in instances]
    for i in deleteInstances:
        terminateInstances = ec2.instances.terminate(i)
        print(terminateInstances)

    print("Terminating instances...")

Having no luck on finding methods to do this simply.


Viewing all articles
Browse latest Browse all 29539

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>