Simple Python Script to Start and Stop Amazon AWS Instances

Managing AWS instances from a Linux CLI with Python2.7. 

Installation

Assuming you already have Python 2.7 installed, you will also need a boto library to be able to work with AWS:

# apt-get update && apt-get install python-boto

For the script to work, you will also need to know the following:

  1. AWS access key and secret key.
  2. The region your instance is running in.
  3. The instance ID.

Usage

Script takes a single parameter passed on a CLI, either “start” or “stop”, depending on the action needed:

$ /usr/bin/python aws.py start
Starting the instance...
$ /usr/bin/python aws.py stop
Stopping the instance...

In case you enter something else:

$ /usr/bin/python aws.py sometext
Usage: python aws.py {start|stop}

Python Script

The script file is referenced as aws.py.

# /usr/bin/python2.7
# written by Tomas (www.lisenet.com) on 05/11/2012
# copyleft free software

import boto.ec2
import sys

# specify AWS keys
auth = {"aws_access_key_id": "<key_id>", "aws_secret_access_key": "<access_key>"}

def main():
    # read arguments from the command line and 
    # check whether at least two elements were entered
    if len(sys.argv) < 2:
	print "Usage: python aws.py {start|stop}\n"
	sys.exit(0)
    else:
	action = sys.argv[1] 

    if action == "start":
	startInstance()
    elif action == "stop":
    	stopInstance()
    else:
    	print "Usage: python aws.py {start|stop}\n"

def startInstance():
    print "Starting the instance..."

    # change "eu-west-1" region if different
    try:
        ec2 = boto.ec2.connect_to_region("eu-west-1", **auth)

    except Exception, e1:
        error1 = "Error1: %s" % str(e1)
        print(error1)
        sys.exit(0)

    # change instance ID appropriately  
    try:
         ec2.start_instances(instance_ids="i-12345678")

    except Exception, e2:
        error2 = "Error2: %s" % str(e2)
        print(error2)
        sys.exit(0)

def stopInstance():
    print "Stopping the instance..."

    try:
        ec2 = boto.ec2.connect_to_region("eu-west-1", **auth)

    except Exception, e1:
        error1 = "Error1: %s" % str(e1)
        print(error1)
        sys.exit(0)

    try:
         ec2.stop_instances(instance_ids="i-12345678")

    except Exception, e2:
        error2 = "Error2: %s" % str(e2)
        print(error2)
        sys.exit(0)

if __name__ == '__main__':
    main()

35 thoughts on “Simple Python Script to Start and Stop Amazon AWS Instances

  1. Thanks for this insight, but I do have a critical question, on which CLI do you run this script from, can I do this from my Local computer, I use Windows and have putty

  2. Thanks a lot. But could you answer me 2 questions below:
    1. I have many ec2 instances (about 10), is there anyway to start/stop a specify instance ? e.g aws.py start instance_1
    2. How can I check if an instance is running ? so if I try to start it, console will print something like “instance is already running”.

    • Hi, you can change the script to take a parameter for an instance name, and then start or stop that instance. As for instance state, check “get_all_instance_status” method. It returns class boto.ec2.instancestatus.InstanceStatus object. So you should be able to get system_status and instance_status from it.

    • thanks for that.

      I used your script to start an instance but the console shows me this: Error2: ‘NoneType’ object has no attribute ‘start_instance’. Could your please explain what it is and how to solve it ?

    • “NoneType” means that instead of an instance of whatever class or object you think you’re working with, you’ve actually got “None”.

      If you check the script, you will see that the Error2 comes from the e2 exception (that’s the whole point of it – to be able to track down errors easily). Can you post the line that contains start_instances from your script?

  3. I run into the same problem as Long Tran. In my case, I have already started an instance and am just trying the stopInstance( ) from your program. I have pretty much commented everything else in your program except the relevant lines so that I can stop the instance I know is running.

    Here is the error I am getting:

    topping the instance…
    Error2: ‘NoneType’ object has no attribute ‘stop_instances’

    (I have a feeling that problem lies on my system rather than your code because when I ran another program that will stop the same instance, I got the same error. I am running Python on my MacBook pro. I have been able to successfully do S3 integration though).

    Thanks

  4. I am running into the same problem as Long Tran when I am just using your program to stop an ec2 instance. Instance ID, region have been carefully changed.

  5. My problem is resolved now. Problem was at my end as I had thought. Instead of passing us-west-1, I was passing us-west-1a. So the ec2 variable was becoming NoneType
    ec2 = boto.ec2.connect_to_region(“eu-west-1”, **auth)

    Thanks for your putting this script.

    • So you were passing the availability zone rather than the region? I don’t want to sound harsh, but it might be worth reading the manual:

      boto.ec2.connect_to_region(region_name, **kw_params)
    • Yep, that worked ! You’re right. I noticed about it when using awscli at aws configure. My EC2 instance region name in EC2 dashboard is “ap-southeast-1a”, but the .configure file only accept “ap-southeast-1”.

  6. Hi ,

    I tried through this script and it worked well for windows too..

    for auth you have mentioned as

    auth = {“aws_access_key_id”:”******”,”aws_secret_access_key”:”MynewKeyPAir”}

    so from where did you get values for aws_access_key_id and aws_secret_access_key, i got for asw_secret_key but not the ID. i am using ec2.t2.micro instance.

  7. Hi Tomas,

    I have a python script in my local machine, which streams data from twitter to S3.
    Now my requirement is, i have to run the python script in ec2 and once the script is run successfully, i will have to close the instance. Also i will have the start the script from my local machine but the script should run in ec2

    Could you please help me in this regards?

    import boto.ec2
    import sys

    # specify AWS keys
    auth = {“aws_access_key_id”: “”, “aws_secret_access_key”: “”}

    startInstance()

    a=10
    b=20
    c=a+b
    print c

    stopInstance()

    will this code work?, given i define the functions mentioned above.

  8. Hi, i am facing some problem while starting the ec2 instance. I changed the region “ap-south-1a” to “ap-south-1” then also i am getting error like error1: ‘module’ object has no attribute “connect_to_region”. I am starting my instance through windows cli with python2.7 and boto3. can anyone help me out with this.

    • Try python-boto rather than python-boto3. It’s possible that syntax has changed between versions. Check boto3 documentation if that’s the version you must use.

  9. hi i used the script and it was working fine all these days. All of a sudden i see botocore exception( auth error) unable to validate aws credentials.

  10. Thanks Tomas for this – we just integrated it into our OS menu for our VMs – we can now add a disk and have it available to the OS in two simple steps.Great for Servicedesk guys

  11. When am trying run script through windows command prompt showing blow error
    Error2: EC2ResponseError: 401 Unauthorized

    AuthFailureAWS was not able to validate the provided access credentials5eaf75fe-43fb-4cb8-9ed4-ff37d8378d41

  12. I am having trouble connecting to us-east-2 but I have no trouble connecting to us-east-1?

    ec2 = boto.ec2.connect_to_region(“us-east-1”, **auth) — WORKS
    ec2 = boto.ec2.connect_to_region(“us-east-2”, **auth) — ec2 = None

    I have servers running in both N.Virginia as well as Ohio. What could be causing this?

  13. Hey, I want to run some bash scripts every time when I start my instance
    Can you help me out in that?

    • Sure thing, there are several ways that you can achieve this.

      When you launch an instance in Amazon EC2, you have the option of passing user data to the instance that can be used to run scripts after the instance starts.

      Depending on your OS, you can also create an sysvinit/systemd service that starts on system boot to run your script.

  14. Hi, new to amazon…is there any way to execute the script from local machine to start and stop Amazon instance?

  15. Hi Tomas,
    I have created the python script in similar passion, which is working fine by using python. This script should be used by my team also hence i have created exe file by using pyinstaller which is working fine in my local machine. But in other machines due to antivirus it is deleting my exe by suspecting as malware.

    is there any way to find why it is considering the exe file as Malware ?

    • You can try to upload your file to VirusTotal and see what gets reported. That might give you some insight into why the file is blocked.

Leave a Reply

Your email address will not be published. Required fields are marked *