Skip to content

Instantly share code, notes, and snippets.

@EmmanuelOuzan
Last active May 26, 2021 14:45
Show Gist options
  • Save EmmanuelOuzan/8d259ecfe3dc00d01468907a9e51ec78 to your computer and use it in GitHub Desktop.
Save EmmanuelOuzan/8d259ecfe3dc00d01468907a9e51ec78 to your computer and use it in GitHub Desktop.
Lambada Create EC2 instance function code
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Sid": "VisualEditor1",
"Effect": "Allow",
"Action": [
"ec2:*"
],
"Resource": "*"
},
{
"Sid": "VisualEditor2",
"Effect": "Allow",
"Action": "logs:CreateLogGroup",
"Resource": "arn:aws:logs:*:*:*"
}
]
}
import os
import boto3
AMI = os.environ['AMI']
INSTANCE_TYPE = os.environ['INSTANCE_TYPE']
KEY_NAME = os.environ['KEY_NAME']
SUBNET_ID = os.environ['SUBNET_ID']
REGION = os.environ['REGION']
ec2 = boto3.client('ec2', region_name=REGION)
def lambda_handler(event, context):
instance = ec2.run_instances(
ImageId=AMI,
InstanceType=INSTANCE_TYPE,
KeyName=KEY_NAME,
SubnetId=SUBNET_ID,
MaxCount=1,
MinCount=1,
InstanceInitiatedShutdownBehavior='terminate'
)
instance_id = instance['Instances'][0]['InstanceId']
print (instance_id)
return instance_id
import boto3
import time
region = 'us-east-1'
instances = ['i-05de1a23cc80e5eb9']
def lambda_handler(event, context):
ec2 = boto3.client('ec2', region_name=region)
ec2.terminate_instances(InstanceIds=instances)
print ('Terminate your instances: ' + str(instances))
return "Build server Terminate..."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment