Last active
May 14, 2018 01:31
-
-
Save GeneralTesler/0ad29e2c0af44af04b955da5d841a076 to your computer and use it in GitHub Desktop.
Python lambda to launch EC2 + policy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"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/*" | |
] | |
} | |
] | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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