Skip to content

Instantly share code, notes, and snippets.

@pharsi
Created February 28, 2024 00:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pharsi/2392ca8fb0b939182953dc44c1f87be5 to your computer and use it in GitHub Desktop.
Save pharsi/2392ca8fb0b939182953dc44c1f87be5 to your computer and use it in GitHub Desktop.
import sys
import json
import boto3
from botocore.config import Config
# ec2 = boto3.client('ec2')
my_config = Config(
region_name='us-east-1',
signature_version='v4',
retries={
'max_attempts': 10,
'mode': 'standard'
},
)
with open("/creds") as file:
[accessKeyId, secretAccessKey] = file.readlines()
accessKeyId = accessKeyId.strip()
secretAccessKey = secretAccessKey.strip()
ec2_client = boto3.client('ec2', config=my_config, aws_access_key_id=accessKeyId, aws_secret_access_key=secretAccessKey)
for x in sys.argv[1:]:
response = ec2_client.describe_instances(
Filters=[
{
'Name': 'tag:Name',
'Values': [
x,
]
},
],
)
# print(sys.argv)
# print(json.dumps(response, indent=4, default=str))
state = response["Reservations"][0]["Instances"][0]["State"]["Name"]
if state == "running":
instance_id = response["Reservations"][0]["Instances"][0]["InstanceId"]
print("Stopping instance {} with id {}".format(x, instance_id))
stop_response = ec2_client.stop_instances(
InstanceIds=[
instance_id,
],
Force=True
)
print(stop_response)
waiter = ec2_client.get_waiter('instance_stopped')
waiter.wait(InstanceIds=[instance_id])
print("Instance {} is stopped".format(x))
ec2_client.terminate_instances(InstanceIds=[instance_id])
waiter = ec2_client.get_waiter('instance_terminated')
waiter.wait(InstanceIds=[instance_id])
print(f"Instance {instance_id} has been terminated.")
# update the code to start the instance if it is stopped
# json_response = json.loads(response)
# print(response)
# response = ec2_client.describe_instances(
# Filters=[
# {
# 'Name': 'string',
# 'Values': [
# 'string',
# ]
# },
# ],
# InstanceIds=[
# 'string',
# ],
# DryRun=True|False,
# MaxResults=123,
# NextToken='string'
# )
# print(sys.argv)
# response = ec2_client.describe_instances(
# Filters=[
# {
# 'Name': 'string',
# 'Values': [
# 'string',
# ]
# },
# ],
# InstanceIds=[
# 'string',
# ],
# DryRun=True|False,
# MaxResults=123,
# NextToken='string'
# )
# if (sys.argv[1] in 'Start' or sys.argv[1] in 'Stop'):
# if sys.argv[1] == 'Start':
# # Start ec2
# print("Starting ec2")
# else:
# # Stop ec2
# print("Stopping ec2")
# else:
# print("invalid choice")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment