AWS ec2 start using lambda
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 | |
import json | |
import os | |
import logging | |
region = '' | |
region = os.environ['region']; | |
if not region : | |
logger.error('Missing region'); | |
raise | |
ec2 = boto3.client('ec2', region_name=region) | |
logger = logging.getLogger() | |
logger.setLevel(logging.INFO) | |
def lambda_handler(event, context): | |
logger.info("Event Object"); | |
logger.info(json.dumps(event)); | |
instance_id = event['detail']['instance-id']; | |
logger.info("Instance Id : %s", instance_id); | |
region = os.environ['region']; | |
if not region : | |
logger.error('Missing region'); | |
raise | |
## check for ec2 resource state | |
ec2 = boto3.client('ec2', region); | |
response = ec2.describe_instance_status(InstanceIds=[instance_id]); | |
logger.info("Instance Detail"); | |
print(logger.info(json. dumps(response))); | |
try : | |
instance_state = response['InstanceStatuses'][0]['InstanceState']['Name']; | |
logger.info("Instance State : %s", instance_state); | |
except IndexError: | |
logger.info("Starting Instance "); | |
## start instance | |
responses = ec2.start_instances( | |
InstanceIds=[instance_id] | |
); | |
return 1; | |
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
example test event :- | |
{"detail": {"instance-id": "i-031bb39695ed7172j"}} | |
environment variable : | |
region : |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment