Services >> Cloud >> AWS >> SDK >> Python >> boto3 >> How to manage EC2

 

List instances

#!/bin/python
import boto3
ec2 = boto3.resource('ec2')
for instance in ec2.instances.all():
   print instance.id, instance.state

 

Create Instance

#!/bin/python
import boto3
ec2 = boto3.resource('ec2')
instance = ec2.create_instances(
    ImageId='ami-fdb8229e',
    MinCount=1,
    MaxCount=1,
    InstanceType='t2.micro',
    KeyName='yourkeyname',
    UserData='#!/bin/bash;yum install -y httpd24;echo bootstrapped > /var/tmp/bootstrap.log',
    TagSpecifications=[
        {
            'ResourceType': 'instance',
            'Tags': [
                {
                    'Key': 'Name',
                    'Value': 'Web server 5'
                },
            ]
        },
    ]
    )
print instance[0].id

 

References:

https://docs.aws.amazon.com/code-samples/latest/catalog/code-catalog-python.html