1

I need to write a python script using boto3 which does the following,

  • set aws access & secret key for my session
  • then create an ec2 instance (using ami image)
  • execute a command in newly created ec2 instance
  • I guess question is on how to do it using python boto3, not using CLI! – MikA Sep 25 '15 at 13:22
  • No idea what csdshell is, but ideas for how to exec commands via SSH: http://stackoverflow.com/questions/946946/how-to-execute-a-process-remotely-using-python. – jarmod Sep 25 '15 at 14:56

1 Answers1

5

Its not really difficult, what you are asking is mostly covered on boto3 docs.

For creating a new t2.micro on us-east-1a running ubuntu 14.04. You should be able to do it like this :

# latest ubuntu ami
ami_id = 'ami-5189a661'

# define userdata to be run at instance launch
userdata = """#cloud-config

runcmd:
 - touch /home/ubuntu/heythere.txt
"""

conn_args = {
    'aws_access_key_id': 'YOURKEY',
    'aws_secret_access_key': 'YOUSECACCESSKEY',
    'region_name': 'us-east-1'
}

ec2_res = boto3.resource('ec2', **conn_args)

new_instance = ec2_res.create_instances(
    ImageId=ami_id,
    MinCount=1,
    MaxCount=1,
    UserData=userdata,
    InstanceType='t2.micro'
    )

print new_instance.id
kichik
  • 33,220
  • 7
  • 94
  • 114
Argais
  • 233
  • 4
  • 7