Launching EC2 Instance - Using Python inside lambda function.
This POST discuss about launching EC2 instance in AWS using python code in lambda.
all the code written in Italic
Written using "anaconda and Jupyter Notebook"
Steps for Writing python code for launching AWS instance.
import json
import boto3
def lambda_handler(event, context):
myec2 = boto3.resource(
service_name = "ec2",
aws_access_key_id = "",
aws_secret_access_key = "",
region_name = "ap-south-1",
verify = False
)
myos = myec2.create_instances(
ImageId= "ami-0cc9838aa7ab1dce7",
InstanceType= "t2.micro",
MaxCount= 1,
MinCount= 1
)
print(myos[0].id)
# TODO implement
return {
'statusCode': 200,
'body': json.dumps('one ec2 created in ap-south-1!')
}
After this create API Gateway - note the region
create Api => REST API => Build => new api => "api name" (EC2)=> Create api.
Resource / "launch" and method "Get" => integration = Lambda and chose the lambda function.
Create SNS, create a topic and configure the subscription to that topic. eg- like mail ..
import boto3
mysns = boto3.client("sns")
mysns.publish(
TopicArn='arn:aws:sns:us-east-1:339713094090:Testing'
Message='I m body ec2 instance launched'
Subject="hi ec2 launched'
)
Comments
Post a Comment