Skip to content

Instantly share code, notes, and snippets.

@GeneralTesler
Last active May 14, 2018 01:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GeneralTesler/0ad29e2c0af44af04b955da5d841a076 to your computer and use it in GitHub Desktop.
Save GeneralTesler/0ad29e2c0af44af04b955da5d841a076 to your computer and use it in GitHub Desktop.
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