Skip to content

Instantly share code, notes, and snippets.

@dio-ct
Created September 8, 2021 12:33
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 dio-ct/21e5ae35fec9d8fc35a5286850f0de6d to your computer and use it in GitHub Desktop.
Save dio-ct/21e5ae35fec9d8fc35a5286850f0de6d to your computer and use it in GitHub Desktop.
stop and start AWS instances with boto3
import os
import boto3
import argparse
from botocore.exceptions import ClientError
INSTANCE_ID = os.environ.get("S3_INSTANCE_ID", None)
print(INSTANCE_ID)
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--stop',
action='store_true',
required=False,
help="Stop an Instance")
group.add_argument('--start',
action='store_true',
required=False,
help="Start an Instance")
args = parser.parse_args()
ec2 = boto3.client('ec2')
if args.stop:
try:
response = ec2.stop_instances(InstanceIds=[INSTANCE_ID],
DryRun=False)
print('Success', response)
except ClientError as e:
print('Error', e)
if args.start:
try:
response = ec2.start_instances(InstanceIds=[INSTANCE_ID],
DryRun=False)
print('Success', response)
except ClientError as e:
print('Error', e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment