Following AWS Lambda is working as expected [i.e. ec2 instance stop and start] for ec2 instances, which are not part of any auto-scaling group, but it is not working for ec2 instances which are part of auto-scaling group.
For ec2 instances, which are part of auto-scaling group, ec2 instances are re-launched & running again.
AWS Lambda code is as follows;
import boto3
ec2 = boto3.client('ec2')
def lambda_handler(event, context):
action_handler(event['action'])
def get_ec2_instances():
ec2_int = ec2.describe_instances(
Filters=[{
'Name': 'ops',
'Values': [
'cost-save'
]
}]
)
return ec2_int
def action_handler(action):
ec2_instances = get_ec2_instances()
for reservation in ec2_instances['Reservations']:
for ec2_instance in reservation['Instances']:
if action == "stop":
stop_ec2(ec2_instance)
elif action == "start":
start_ec2(ec2_instance)
def stop_ec2(ec2_int):
if ec2_int['State']['Name'] == 'running':
ec2.stop_instances(InstanceIds=[ec2_int['InstanceId']])
def start_ec2(ec2_int):
if ec2_int['State']['Name'] == 'stopped':
ec2.start_instances(InstanceIds=[ec2_int['InstanceId']])
Could you please assist to resolve this issue? I would like to make sure that ec2 instances which are part of auto-scaling must also stop and start as well.