How to Start an EC2 Instance in Lambda and Stop the Instance After Executing the Command

Asked 2 years ago, Updated 2 years ago, 125 views

I would like to start the EC2 instance of Ubuntu that is stopped, run the script, email the results, and then stop again.
I wrote and ran Lambda functions like this:

import boto3

instanceId='i-xxxxxxxx'
instance=boto3.resource('ec2') .instance(instanceId)
statusDict = {'pending': 0,
              'running'—16,
              'shutting-down':32,
              'terminated':48,
              'stopping': 64,
              'stopped': 80 
             }

ec2 = boto3.client('ec2')
ssm = boto3.client('ssm')

deflambda_handler(event, context):
    try:
        state = instance.state
        stateCode = state ['Code']
        if stateCode==statusDict ['running']:
            print('Instance is already running.')
        else:
            response=instance.start()
            print(response)
            instance.wait_until_running()
            print('Successed to start instance')

        print(ssm.describe_instance_information())
        waiter=ec2.get_waiter('instance_status_ok')
        waiter.wait (InstanceIds=[instanceId])
        print(ssm.describe_instance_information())

        US>ssm.send_command(
            InstanceIds = [instanceId],
            DocumentName="AWS-RunShellScript",
            Parameters = {
                "commands": [
                    "python 3. / example.py",
                    "cat log.txt | sendmail [email protected]", 
                    "awsec2stop-instances--instance-ids i-xxxxxxxx",
                ],
                "executionTimeout": "3600",
                "workingDirectory": ["/home/ubuntu/example/" ]
            },
        )
    except Exception as:
        print(e)
        raise

This will run until the mail is sent, but the instance will not stop.
I have verified that aws is installed on the server and that logging in to the server with ssh and entering the same command will stop properly.

How do I stop an instance after running a script?

aws aws-lambda

2022-09-30 20:19

1 Answers

I don't know the cause, but...

Why don't you set the command to shutdown?
Or try to terminate from ssm separately after executing the command in ssm.


2022-09-30 20:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.