Home > Software engineering >  AWS Lambda function that automatically starts a stopped instance
AWS Lambda function that automatically starts a stopped instance

Time:08-24

I am having some trouble writing this function that will automatically start a stopped instance. Relatively new to this and just playing around.

I am able to start only a single instance by hardcoding the instance ID.

I am trying to filter for any instance with a state that is stopped.

This is my code:

import json
import boto3

region = 'us-east-1'

ec2 = boto3.resource('ec2')
instances = ec2.instances.filter(
Filters=[{'Name': 'instance-state-name', 'Values':['stopped']}])

def lambda_handler(event, context):
    ec2 = boto3.client('ec2', region_name=region)
    ec2.start_instances(InstanceIds=instances)

This Lambda function is trigged by an event.

I am getting an "invalid type for parameter InstanceIds" error. Must be list or tuple. Tried to loop through it but no link. Wondering if there is a simpler way to do this or if you have a suggestion?

CodePudding user response:

You should iterate instances collection to get IDs (instance.id):

all_instance_ids=[]
for instance in instances:
  all_instance_ids.append(instance.id)
  • Related