Abdul Salam
Abdul Salam

Reputation: 552

AWS Lambda + python: ec2.start_instances(InstancesIds= ?? )

I have created the below python script in AWS Lambda, to list all the stopped instances, which works well. now, I wants to extend the functionality by starting the instances which were stopped.

Script:

region ='us-east-1'
ec2 = boto3.resource('ec2',region)
def lambda_handler(event, context):
    instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}])
    for instance in instances:
        print('Ec2 Instances which are stopped: ', 'Instance ID: ', instance.id, 'Instance state: ', instance.state, 'Instance type: ',instance.instance_type)

Now am appending the following code to start the instances:

ec2.start_instances(InstanceIds=instance.id)

I am getting error[ec2.ServiceResource' object has no attribute 'start_instances], because (InstanceIds=' ') expects list here, but my instance is of type <class 'boto3.resources.factory.ec2.Instance'> How do i convert, so that I can input list to start_instances method.

Thanks in Advance!!

Please find below, my updated script after getting answer, now this script will start the stopped instances automatically.

Updated script

region ='us-east-1'
ec2 = boto3.resource('ec2',region)
client = boto3.client('ec2',region)
def lambda_handler(event, context):
    instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}])
    for instance in instances:
        print('Ec2 Instances which are stopped: ', 'Instance ID: ', instance.id, 'Instance state: ', instance.state, 'Instance type: ',instance.instance_type)
        instance_ids = [instance.id for instance in instances]
        response = client.start_instances(InstanceIds=[instance.id])
        print('Lambda have started these instances', instance.id)  

Caution Please exercise care if you are copy pasting this script as this will turn-on instances which may cost you. (This script is working, TESTED!)

Upvotes: 0

Views: 1117

Answers (2)

Sudharsan Sivasankaran
Sudharsan Sivasankaran

Reputation: 5897

ec2.instances is the higher level resource and start_instance is low level client, to use the client function, you need create the client with boto3.client('ec2')

client = boto3.client('ec2')
response = client.start_instances(
    InstanceIds=[
        'string',
    ],
)

Upvotes: 1

helloV
helloV

Reputation: 52433

If you want to start each instance in the loop:

ec2.start_instances(InstanceIds=[instance.id])

If you want to start all instances outside the loop: Use list comprehension to generate a list of instance ids and pass it to start_instances

instance_ids = [instance.id for instance in instances]
ec2.start_instances(InstanceIds=instance_ids)

Upvotes: 1

Related Questions