Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python lambda to launch EC2 + policy
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": "ec2:RunInstances",
"Resource": [
"arn:aws:ec2:*:*:subnet/*",
"arn:aws:ec2:us-east-1::image/*",
"arn:aws:ec2:*:*:instance/*",
"arn:aws:ec2:*:*:volume/*",
"arn:aws:ec2:us-east-1:*:key-pair/*",
"arn:aws:ec2:*:*:security-group/*",
"arn:aws:ec2:*:*:network-interface/*"
]
}
]
}
import boto3, json
def lambda_launch_ec2(event, context):
'''expects json body like:
{"amiid":"string","sgid":"string","type":"string","key":"string"}
'''
body = json.loads(event['body'])
region = 'us-east-1'
amiid = body['amiid'] #AMI ID
sgid = body['sgid'] #Security Group ID
type = body['type'] #Instance type (ex: t2.micro)
key = body['key'] #SSH key name
EC2 = boto3.client('ec2', region_name=region)
new_instance = EC2.run_instances(
ImageId=amiid,
InstanceType=type,
MinCount=1,
MaxCount=1,
KeyName=key,
NetworkInterfaces=[
{
'AssociatePublicIpAddress':True,
'DeviceIndex':0,
'Groups':[
sgid
]
}
]
)
iid = (str(new_instance['Instances'][0]['InstanceId']))
'''api gateway lambda proxy response'''
return {"isBase64Encoded":False,"statusCode":200,"headers":{"X-Lambda-Function":"launch-ec2"},"body":json.dumps({"InstanceId":iid})}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment