How to start and stop an EC2 Instance using Lambda (AWS)
This article has not been completed yet. However, it may already contain helpful information and therefore it has been published at this stage.
Create an EC2 - Instance....
Create IAM Policy & IAM Role
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"ec2:Start*",
"ec2:Stop*"
],
"Resource": "*"
}
]
}
Enter a name. For example itinfrasollambdaec2
Create a Lambda function
import boto3
region = 'eu-central-1'
instances = ['i-0bf45f32ee3047d76']
ec2 = boto3.client('ec2', region_name=region)
def lambda_handler(event, context):
ec2.stop_instances(InstanceIds=instances)
print('stopped your instances: ' + str(instances))
import boto3
region = 'eu-central-1'
instances = ['i-0bf45f32ee3047d76']
ec2 = boto3.client('ec2', region_name=region)
def lambda_handler(event, context):
ec2.start_instances(InstanceIds=instances)
print('started your instances: ' + str(instances))
Sources:
https://it-infrastructure.solutions/spinning-up-your-first-ec2-instance-aws/
https://aws.amazon.com/de/premiumsupport/knowledge-center/start-stop-lambda-cloudwatch/