简体   繁体   English

Python Boto3:设置会话,创建 EC2 实例并使用 csdshell 运行命令

[英]Python Boto3: set session, create an EC2 instance and run command using csdshell

I need to write a python script using boto3 which does the following,我需要使用 boto3 编写一个 python 脚本,它执行以下操作,

  • set aws access & secret key for my session为我的会话设置 aws 访问和密钥
  • then create an ec2 instance (using ami image)然后创建一个 ec2 实例(使用 ami 图像)
  • execute a command in newly created ec2 instance在新创建的 ec2 实例中执行命令

Its not really difficult, what you are asking is mostly covered on boto3 docs.这并不难,您要问的内容主要包含在 boto3 文档中。

For creating a new t2.micro on us-east-1a running ubuntu 14.04.用于在运行 ubuntu 14.04 的 us-east-1a 上创建新的 t2.micro。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM