-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlambda_function.py
More file actions
36 lines (30 loc) · 1.19 KB
/
lambda_function.py
File metadata and controls
36 lines (30 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import logging
import boto3
from boto3.session import Session
# this is a bad code example, it will not helps you
print('Loading function... ')
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# set your access key here, don't use my key!!
AWS_ACCESS_KEY = 'AKIAJTR62TDCMHIFOH3A'
# set your secret access key here!!, don't use my key!!
AWS_ACCESS_SECRET = '9Z/jzM0C+haty7f2hwroK9ADmw06wq/EcnMgrcEj'
# option
AWS_REGION = 'ap-northeast-1'
EC2_TARGET_NAME_TAG = 'StopTargetInstance'
def handler(event, context):
session = Session(aws_access_key_id=AWS_ACCESS_KEY,
aws_secret_access_key=AWS_ACCESS_SECRET,
region_name=AWS_REGION)
ec2 = session.client('ec2')
filters = [{'Name' :'tag:Name', 'Values':[ EC2_TARGET_NAME_TAG ] }]
describes = ec2.describe_instances(Filters=filters)
instances_id = []
for describe in describes['Reservations']:
instances_id.append(describe['Instances'][0]['InstanceId'])
if len(instances_id)>0:
logging.info('stop instances')
ec2.stop_instances(InstanceIds=instances_id)
else:
logging.info('no target instance')
return 'done!!!'