Skip to content

Instantly share code, notes, and snippets.

@sudheerchamarthi
Last active November 23, 2020 18:08
Show Gist options
  • Save sudheerchamarthi/0d0710e4aafca8cdd1732f43da88960e to your computer and use it in GitHub Desktop.
Save sudheerchamarthi/0d0710e4aafca8cdd1732f43da88960e to your computer and use it in GitHub Desktop.
import boto3
# Change this - Add the Tag Key to look for in ASG
asgStopTagKey = "status"
# Change this - Add the Tag Value to look for in ASG
asgStopTagValue = "off"
asgDesiredCount = 0
asgMinValue = 0
# Change this - Add the Tag Key to look for in EC2
ec2StopTagKey = "status"
# Change this - Add the Tag Value to look for in EC2
ec2StopTagValue = "off"
nextToken=""
ec2_client = boto3.client('ec2', region_name='us-east-1')
asg_client = boto3.client('autoscaling', region_name='us-east-1')
asgInfo = asg_client.describe_auto_scaling_groups()
print("Updating ASG")
for asg in range(len(asgInfo['AutoScalingGroups'])):
asgName = asgInfo['AutoScalingGroups'][asg]['AutoScalingGroupName']
for tag in range(len(asgInfo['AutoScalingGroups'][asg]['Tags'])):
if asgInfo['AutoScalingGroups'][asg]['Tags'][tag]['Key'] == asgStopTagKey:
tagValue = asgInfo['AutoScalingGroups'][asg]['Tags'][tag]['Value']
if tagValue == asgStopTagValue:
# Update ASG Desired and Min Value
asg_client.update_auto_scaling_group(AutoScalingGroupName=asgName, MinSize=asgMinValue, DesiredCapacity=asgDesiredCount)
while True:
if nextToken=="NA":
print("exiting")
break
else:
try:
nextToken=asgInfo['NextToken']
asgInfo = asg_client.describe_auto_scaling_groups(NextToken=nextToken)
for asg in range(len(asgInfo['AutoScalingGroups'])):
asgName = asgInfo['AutoScalingGroups'][asg]['AutoScalingGroupName']
for tag in range(len(asgInfo['AutoScalingGroups'][asg]['Tags'])):
if asgInfo['AutoScalingGroups'][asg]['Tags'][tag]['Key'] == asgStopTagKey:
tagValue = asgInfo['AutoScalingGroups'][asg]['Tags'][tag]['Value']
if tagValue == asgStopTagValue:
# Update ASG Desired and Min Value
# asg_client.update_auto_scaling_group(AutoScalingGroupName=asgName, MinSize=asgMinValue, DesiredCapacity=asgDesiredCount)
print(asgName)
except:
nextToken="NA"
print("Updated ASG")
ec2Info = ec2_client.describe_instances(Filters=[{
# Change this - Replace stop with Tag Value to look for in EC2
'Name':'tag:status',
'Values':[ec2StopTagValue]},
{'Name':'instance-state-name',
'Values':['running']
}
])
print("Stopping EC2")
for instance in range(len(ec2Info['Reservations'])):
# Stop Instances
# ec2_client.stop_instances(InstanceIds=[ec2Info['Reservations'][instance]['Instances'][0]['InstanceId']])
print(ec2Info['Reservations'][instance]['Instances'][0]['InstanceId'])
print("Stopped EC2")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment