
dc-common-lambda-auto-start


environment_autotrue
webhook_url to receive notifications to Slack.import boto3
import os
import json
import logging
import urllib3
logger = logging.getLogger()
logger.setLevel(logging.INFO)
ec2_resource = boto3.resource('ec2')
http = urllib3.PoolManager()
webhook_url = "https://hooks.slack.com/services/XXXXX/XXXXX/XXXXX" # Replace with your Webhook URL
def lambda_handler(event, context):
environment_auto = os.environ.get('environment_auto')
if not environment_auto:
logger.info('Target is empty')
return {
"statusCode": 400,
"body": "Environment variable 'environment_auto' is not set"
}
instances = ec2_resource.instances.filter(
Filters=[{'Name': 'tag:environment_auto', 'Values': [environment_auto]}]
)
instance_list = list(instances)
if not instance_list:
return {
"statusCode": 500,
"body": "Target Instance is None"
}
action_start = instances.start()
send_slack(action_start)
return {
"statusCode": 200,
"body": "EC2 Starting"
}
def send_slack(action_start):
list_instance_id = []
if (
len(action_start) > 0
and "StartingInstances" in action_start[0]
and len(action_start[0]["StartingInstances"]) > 0
):
for instance in action_start[0]["StartingInstances"]:
list_instance_id.append(instance["InstanceId"])
msg = f"Starting Instances ID:\n {list_instance_id}"
data = {"text": msg}
http.request(
"POST",
webhook_url,
body=json.dumps(data).encode("utf-8"),
headers={"Content-Type": "application/json"}
)
else:
logger.info('Not found Instances Start')


dc-common-lambda-auto-startdc-common-lambda-auto-start8 and select hours for the unit

dc-common-lambda-auto-start function

