Launch, List And Terminate AWS EC2 instances using python boto3 script

Launch, List And Terminate AWS EC2 instances using python boto3 script

Table Of Content

  • Prerequisite
  • Launch AWS EC2 Instances using python script
  • List AWS EC2 Instances using python script
  • Terminate AWS EC2 Instances using python script

Prerequisite

An AWS Account An IAM User with:

  • AWS Management Console access to verify your EC2 instances launched,listed and terminated.
  • The IAM permissions required to perform IAM, EC2, and CloudWatch activities. IAM policy creation and AWS Application Programming Interface (API) permissions are outside this article’s scope. Always adhere to the principle of least privilege when authorizing accounts to perform actions. Administrative access to an EC2 Instance.
  • Install awscli using aws official documentation here
  • Install python and boto3
  • Configure aws cli by using official documentation here

Boto3

Boto3 is the name of the Python SDK for AWS. It allows you to directly create, update, and delete AWS resources from your Python scripts.

Launch AWS EC2 Instance using python script

  1. Python code in one module gains access to the code in another module by the process of importing it. The import statement combines two operations it searches for the named module, then it binds the results of that search to a name in the local scope.
    import boto3
    
  2. We will invoke the client for EC2
    client = boto3.client('ec2')
    
  3. To launch EC2 instances we have to use method "run_instances()". This method helps us launch AWS EC2 instances based on our requirement.
    response =client.run_instances(<arguments>)
    
  4. Goto link where you will find all arguments list. Based on your requirement you can put this arguments to launch your EC2 instances. This document also mentions datatype of the parameter.
    Note:- Arguments which are with "REQUIRED" tags mentioned in documentation is mandatory, if you don't specify those arguments code block to launch EC2 will not execute successfully.
    Example:- "MinCount", "MaxCount".
    Below code will launch EC2 instance based on your provided input.
    resp=client.run_instances(ImageId='ami-0742b4e673072066f',
                           InstanceType='t2.micro',
                           MinCount=3,
                           MaxCount=3,
                           KeyName='<Your key name>')
    
  5. Once above method will run it will launch EC2 and launched EC2 information will be captured in variable "resp". It will return infomation in dictonary, so "resp" would be a dictonary.
  6. Now we will traverse the dict using for loop to print list of instances launched by "run_instances" method.
for i in resp['Instances']:
    print("Instance ID Created is :{} Instance Type Created is : {}" .format(i['InstanceId'],i['InstanceType']))

To view entire github code please click here

List AWS EC2 Instances using python script

  1. Python code in one module gains access to the code in another module by the process of importing it. The import statement combines two operations it searches for the named module, then it binds the results of that search to a name in the local scope.
    import boto3
    
  2. We will invoke the client for EC2
    client = boto3.client('ec2')
    
  3. To describe EC2 instances we have to use method "describe_instances()". This method helps us describe AWS EC2 instances already launched for your account.
    Goto link where you will find all parameters and filter list. Based on your requirement you can use it to describe your EC2 instances. This document also mentions datatype of the parameter.
    resp =client.describe_instances()
    
  4. Once above method will run it will describe EC2 launched information in your account which will be captured in variable "resp". It will return infomation in dictonary, so resp would be a dictonary.
  5. Now we will traverse the dict using for loop to print list of instances already launched
    for reservation in resp['Reservations']:
    for instance in reservation['Instances']:
        print("Running Instance Image ID: {} Running instance Instance Type: {} Running Instance Keyname {}"
              .format(instance['InstanceId'],instance['InstanceType'],instance['KeyName']))
    
    To view entire github code please click here

Terminate AWS EC2 Instances using python script

  1. Python code in one module gains access to the code in another module by the process of importing it. The import statement combines two operations; it searches for the named module, then it binds the results of that search to a name in the local scope.
    import boto3
    
  2. We will invoke the client for EC2
    client = boto3.client('ec2')
    
  3. To describe EC2 instances we have to use method "describe_instances()". This method helps us describe AWS EC2 instances already launched for your account.
    Goto link where you will find all parameters and filter list. Based on your requirement you can use it to describe your EC2 instances. This document also mentions datatype of the parameter.
    resp =client.describe_instances()
    
  4. Create an empty list in which we will save the list of instances to be terminated.
    newlist=[]
    
  5. Now we will traverse the dict using for loop to save the instance ids which needs to be terminated.
    for reservation in resp['Reservations']:
     for instance in reservation['Instances']:
             newlist.append(instance['InstanceId'])
    
  6. Now we will use method "terminate_instances()" to terminate our list "newlist" which we will pass as an argument to this method and will print the output.
    print(client.terminate_instances(InstanceIds=(newlist)))
    
    To view entire github code please click here

Conclusion

Boto3 provided inbuild methods for AWS resources using which many task can be automated by writing a python script.

Stay tuned for my next blog.....

So, did you find my content helpful? If you did or like my other content, feel free to buy me a coffee. Thanks.

Did you find this article valuable?

Support Dheeraj Choudhary's Blog by becoming a sponsor. Any amount is appreciated!