DEV Community

Cover image for Boto3 - Managing EC2 Instances
Srinivasulu Paranduru for AWS Community Builders

Posted on • Updated on

Boto3 - Managing EC2 Instances

Managing EC2 Instances

An EC2 instance is a virtual server in Amazon Ec2(Elastic cloud compute) for running applications in AWS Infrastructure

Make sure one or more AWS EC2 Instances are in running/stopped mode

Describe Instances

Describe one or more Ec2 Instances using describe_instances

import boto3

ec2 = boto3.client('ec2')
response = ec2.describe_instances()
print(response)

Enter fullscreen mode Exit fullscreen mode

Response:


{'Reservations': [{'Groups': [], 'Instances': [{'AmiLaunchIndex': 0, 'ImageId': 'ami-02cad064a29d4550c', 'InstanceId': 'i-047aa10b5116848d3', 'InstanceType': 't2.micro', 'KeyName': 'srini-october', 'LaunchTime': datetime.datetime(2023, 12, 27, 20, 9, 35, tzinfo=tzutc()), 'Monitoring': {'State': 'disabled'}, 'Placement': {'AvailabilityZone': 'eu-west-1a', 'GroupName': '', 'Tenancy': 'default'}, 'PrivateDnsName': 'ip-172-31-29-170.eu-west-1.compute.internal', 'PrivateIpAddress': '172.31.29.170', 'ProductCodes': [], 'PublicDnsName': 'ec2-54-74-208-66.eu-west-1.compute.amazonaws.com', 'PublicIpAddress': '54.74.208.66', 'State': {'Code': 16, 'Name': 'running'}, 'StateTransitionReason': '', 'SubnetId': 'subnet-6a290f55', 'VpcId': 'vpc-1caa4f45', 'Architecture': 'x86_64', 'BlockDeviceMappings': [{'DeviceName': '/dev/xvda', 'Ebs': {'AttachTime': datetime.datetime(2023, 12, 27, 20, 9, 36, tzinfo=tzutc()), 'DeleteOnTermination': True, 'Status': 'attached', 'VolumeId': 'vol-0f39d3d1d1b5bf7d3'}}], 'ClientToken': '5ca9497b-36ed-498c-8f69-b5ebfdac13d1', 'EbsOptimized': False, 'EnaSupport': True, 'Hypervisor': 'xen', 'NetworkInterfaces': [{'Association': {'IpOwnerId': 'amazon', 'PublicDnsName': 'ec2-54-74-208-66.eu-west-1.compute.amazonaws.com', 'PublicIp': '54.74.208.66'}, 'Attachment': {'AttachTime': datetime.datetime(2023, 12, 27, 20, 9, 35, tzinfo=tzutc()), 'AttachmentId': 'eni-attach-018dc6b5c402db53f', 'DeleteOnTermination': True, 'DeviceIndex': 0, 'Status': 'attached', 'NetworkCardIndex': 0}, 'Description': '', 'Groups': [{'GroupName': 'launch-wizard-24', 'GroupId': 'sg-0e3fd0ccb2e17ca8d'}], 'Ipv6Addresses': [], 'MacAddress': '06:c4:cc:e6:58:9b', 'NetworkInterfaceId': 'eni-060f3c36cab1c1e32', 'OwnerId': '481745247371', 'PrivateDnsName': 'ip-172-31-29-170.eu-west-1.compute.internal', 'PrivateIpAddress': '172.31.29.170', 'PrivateIpAddresses': [{'Association': {'IpOwnerId': 'amazon', 'PublicDnsName': 'ec2-54-74-208-66.eu-west-1.compute.amazonaws.com', 'PublicIp': '54.74.208.66'}, 'Primary': True, 'PrivateDnsName': 'ip-172-31-29-170.eu-west-1.compute.internal', 'PrivateIpAddress': '172.31.29.170'}], 'SourceDestCheck': True, 'Status': 'in-use', 'SubnetId': 'subnet-6a290f22', 'VpcId': 'vpc-3caa4f45', 'InterfaceType': 'interface'}], 'RootDeviceName': '/dev/xvda', 'RootDeviceType': 'ebs', 'SecurityGroups': [{'GroupName': 'launch-wizard-24', 'GroupId': 'sg-0e3fd0ccb2e17ca8d'}], 'SourceDestCheck': True, 'Tags': [{'Key': 'Name', 'Value': 'srini-ec2'}], 'VirtualizationType': 'hvm', 'CpuOptions': {'CoreCount': 1, 'ThreadsPerCore': 1}, 'CapacityReservationSpecification': {'CapacityReservationPreference': 'open'}, 'HibernationOptions': {'Configured': False}, 'MetadataOptions': {'State': 'applied', 'HttpTokens': 'required', 'HttpPutResponseHopLimit': 2, 'HttpEndpoint': 'enabled', 'HttpProtocolIpv6': 'disabled', 'InstanceMetadataTags': 'disabled'}, 'EnclaveOptions': {'Enabled': False}, 'BootMode': 'uefi-preferred', 'PlatformDetails': 'Linux/UNIX', 'UsageOperation': 'RunInstances', 'UsageOperationUpdateTime': datetime.datetime(2023, 12, 27, 20, 9, 35, tzinfo=tzutc()), 'PrivateDnsNameOptions': {'HostnameType': 'ip-name', 'EnableResourceNameDnsARecord': True, 'EnableResourceNameDnsAAAARecord': False}, 'MaintenanceOptions': {'AutoRecovery': 'default'}, 'CurrentInstanceBootMode': 'legacy-bios'}], 'OwnerId': '481745247371', 'ReservationId': 'r-0f04635ac0d590724'}], 'ResponseMetadata': {'RequestId': 'a600e28f-4719-4313-b377-66aeda654832', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': 'a600e28f-4719-4313-b377-66aeda654832', 'cache-control': 'no-cache, no-store', 'strict-transport-security': 'max-age=31536000; includeSubDomains', 'vary': 'accept-encoding', 'content-type': 'text/xml;charset=UTF-8', 'transfer-encoding': 'chunked', 'date': 'Wed, 27 Dec 2023 20:10:06 GMT', 'server': 'AmazonEC2'}, 'RetryAttempts': 0}}

Enter fullscreen mode Exit fullscreen mode

Monitor and Unmonitor Instances
Enable or disable detailed monitoring for a EC2 instance. By default, basic monitoring is enabled for EC2 instance

  • Enable detailed monitoring for a running instance using monitor_instances
  • Disable detailed monitoring for a running instance using unmonitor_instances
#file name : ec2_monitor.py

import sys
import boto3

ec2 = boto3.client('ec2')
if sys.argv[1] == 'ON':
    response = ec2.monitor_instances(InstanceIds=['i-047aa10b5116848d3'])
else:
    response = ec2.unmonitor_instances(InstanceIds=['i-047aa10b5116848d3'])
print(response)

Enter fullscreen mode Exit fullscreen mode

`Run the python file : python3 ec2_monitor.py 'ON'

Note :Currently i have used i-047aa10b5116848d3 ec2 instance id of the sample instance which i have provisioned for my testing, but you need to change the one as per the ec2 instances running.

**Response:**
{'InstanceMonitorings': [{'InstanceId': 'i-047aa10b5116848d3', 'Monitoring': {'State': 'disabling'}}], 'ResponseMetadata': {'RequestId': '586598ee-2755-4964-baa6-27c1d87f26c6', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '586598ee-2755-4964-baa6-27c1d87f26c6', 'cache-control': 'no-cache, no-store', 'strict-transport-security': 'max-age=31536000; includeSubDomains', 'content-type': 'text/xml;charset=UTF-8', 'content-length': '430', 'date': 'Wed, 27 Dec 2023 20:23:53 GMT', 'server': 'AmazonEC2'}, 'RetryAttempts': 0}}
`

Start and Stop EC2 Instances

Start Ec2 Instances

import sys
import boto3
import json 
from botocore.exceptions import ClientError


def lambda_handler(event, context):
    # Do a dryrun first to verify permissions
    ec2 = boto3.client('ec2')
    try:
        ec2.start_instances(InstanceIds=['i-09814c21b0108116c'], DryRun=True)
    except ClientError as e:
        if 'DryRunOperation' not in str(e):
           raise
    # Dry run succeeded, run start_instances without dryrun
    try:
        response = ec2.start_instances(InstanceIds=['i-09814c21b0108116c'], DryRun=False)
        print(response)
    except ClientError as e:
            print(e)
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda sr!')
    }



Enter fullscreen mode Exit fullscreen mode

Stop EC2 Instances

import sys
import boto3
from botocore.exceptions import ClientError

ec2 = boto3.client('ec2')

# Do a dryrun first to verify permissions
try:
    ec2.stop_instances(InstanceIds=[instance_id], DryRun=True)
except ClientError as e:
    if 'DryRunOperation' not in str(e):
       raise
# Dry run succeeded, run stop_instances without dryrun
try:
    response = ec2.stop_instances(InstanceIds=[instance_id], DryRun=False)
    print(response)
except ClientError as e:
        print(e)

Enter fullscreen mode Exit fullscreen mode

Conclusion : Discussed about Managing Ec2 Instances using Boto3

Any suggestions/improvements for my blogs and if you like my blogs please share with your connections.Follow me in linked in https://www.linkedin.com/in/srinivasuluparanduru/

Top comments (0)