我之前看过这个问题的提问:如何使用boto3在EC2上进行SSH并运行命令?很多答案都说用户不必使用ssh
连接到EC2并运行命令。然而,我还是不知道如何通过boto3运行python脚本。在boto2中,有一个名为run_instances
的函数,用户可以将他们的脚本传递到EC2节点并运行它,就像下面的代码列表一样。
def run(self, **kwargs):
ec2 = boto.connect_ec2(settings.PDF_AWS_KEY, settings.PDF_AWS_SECRET)
sqs = boto.connect_sqs(settings.PDF_AWS_KEY, settings.PDF_AWS_SECRET)
queue = sqs.create_queue(REQUEST_QUEUE)
num = queue.count()
launched = 0
icount = 0
reservations = ec2.get_all_instances()
for reservation in reservations:
for instance in reservation.instances:
if instance.state == "running" and instance.image_id == AMI_ID:
icount += 1
to_boot = min(num - icount, MAX_INSTANCES)
if to_boot > 0:
startup = BOOTSTRAP_SCRIPT % {
'KEY': settings.PDF_AWS_KEY,
'SECRET': settings.PDF_AWS_SECRET,
'RESPONSE_QUEUE': RESPONSE_QUEUE,
'REQUEST_QUEUE': REQUEST_QUEUE}
r = ec2.run_instances(
image_id=AMI_ID,
min_count=to_boot,
max_count=to_boot,
key_name=KEYPAIR,
security_groups=SECURITY_GROUPS,
user_data=startup)
launched = len(r.instances)
return launched
BOOTSTRAP_SCRIPT
是一个Python脚本。
我使用boto3编写了一些代码:
# -*- coding: utf-8 -*-
SCRIPT_TORUN = """
import boto3
bucket = random_str()
image_name = random_str()
s3 = boto3.client('s3')
Somedata = 'hello,update'
upload_path = 'test/' + image_name
s3.put_object(Body=Somedata, Bucket='cloudcomputing.assignment.storage', Key=upload_path)
"""
import boto3
running_instance = []
ec2 = boto3.resource('ec2')
for instance in ec2.instances.all():
if instance.state['Name'] == 'running': # Choose running instance and save their instance_id
running_instance.append(instance.id)
print instance.id, instance.state
print running_instance
我可以获取运行实例的详细信息,有人能告诉我是否有类似于boto3
中的run_instances
函数,我可以使用它在我的一个正在运行的EC2实例中运行脚本SCRIPT_TORUN
。
SSH
运行脚本?我能否指定一个实例来运行脚本,因为在run_instances
函数中我没有找到像 'instance_id' 这样的参数。 - Coding_Rabbit