import boto3
# create an EC2 client object
ec2 = boto3.client('ec2')
# create an empty list to store the instance IDs
instance_ids = []
# get information about all EC2 instances
response = ec2.describe_instances()
# loop through the instances and check if they have a "Name" tag
for reservation in response['Reservations']:
for instance in reservation['Instances']:
for tag in instance['Tags']:
if tag['Key'] == 'Name':
instance_ids.append(instance['InstanceId'])
# print the instance IDs that have a "Name" tag
print(instance_ids)
ec2.start_instances(instance_ids)
The lambda function
import json
import boto3
from botocore.config import Config
def lambda_handler(event, context):
my_config = Config(
region_name = 'us-west-2')
ec2 = boto3.client('ec2', config=my_config)
# create an empty list to store the instance IDs
instance_ids = []
# get information about all EC2 instances
response = ec2.describe_instances()
# loop through the instances and check if they have a "Name" tag
for reservation in response['Reservations']:
for instance in reservation['Instances']:
for tag in instance['Tags']:
if tag['Key'] == 'Name':
instance_ids.append(instance['InstanceId'])
ec2.start_instances(instance['InstanceId'])
#ec2.stop_instances(instance['InstanceId'])
#ec2.terminate_instances(instance['InstanceId'])
# print the instance IDs that have a "Name" tag
print(instance_ids)
return {
'statusCode': 200,
'body': json.dumps(instance_ids)
}