我是AWS新手,我想运行一个在EC2实例(例如c4.4xlarge)上令人尴尬地并行的python工作脚本。
我已经经历过关于这个问题的问题,但没有找到一个高层次的答案,我需要采取的步骤。我有AWS凭证,并在我的笔记本电脑的python 2上安装了boto3。
如何构造python提交脚本:
此外,在我的python工作脚本中,如何将工作脚本的结果保存回S3?
最后,如何确保我通过AWS访问的python版本拥有成功运行python工作脚本所需的所有包?
很抱歉,如果问题太高,任何概念上的错误。谢谢你的指点!
发布于 2021-08-04 12:53:05
为了实现这一点,我想对您当前的流程提出更多的细节建议:
在提交脚本中:
在EC2实例中:
在EC2实例上运行命令有两种简单的方法,即SSH或使用用户数据属性。为了简单起见,对于当前的用例,我建议使用用户数据方法。
首先,您需要创建一个具有下载/上传到EC2-InstanceProfile桶的权限的S3。然后您可以创建一个EC2,安装任何python或pip包并将其注册为AMI。
下面是一些参考代码:注意,该代码在python3中,只适用于Windows计算机。
submission.py:
import boto3
s3_client = boto3.client('s3')
ec2 = boto3.resource('ec2')
deps = {
'remote' : [
"/path/to/s3-bucket/obj.txt"
],
'local' : [
"/path/to/local-directory/obj.txt"
]
}
for remote, local in zip(deps['remote'], deps['local']):
s3_client.upload_file(local, bucket_name, remote)
user_data = f"""<powershell>
cd {path_to_instance_worker_dir}; python {path_to_instance_worker_script}
</powershell>
"""
instance = ec2.create_instances(
MinCount=1,
MaxCount=1,
ImageId=image_id,
InstanceType=your_ec2_type,
KeyName=your_key_name,
IamInstanceProfile={
'Name': instance_profile_name
},
SecurityGroupIds=[
instance_security_group,
],
UserData=user_data
)instance_worker:
import boto3
s3_client = boto3.client('s3')
deps = {
'remote' : [
"/path/to/s3-bucket/obj.txt"
],
'local' : [
"/path/to/local-directory/obj.txt"
]
}
for remote, local in zip(deps['remote'], deps['local']):
s3_client.download_file(bucket_name, remote, local)
result = do_work()
# write results to file
s3_client.upload_file(result_file, bucket_name, result_remote)
# Get the instance ID from inside (This is only for Windows machines)
p = subprocess.Popen(["powershell.exe", "(Invoke-WebRequest -Uri 'http://169.254.169.254/latest/meta-data/instance-id').Content"])
out = p.communicate()[0]
instance_id = str(out.strip().decode('ascii'))
ec2_client.terminate_instances(InstanceIds=[instance_id, ])在这段代码中,我从内部终止实例,为了做到这一点,您必须首先获得instnace_id,查看这里以获得更多的引用。
最后,如何确保我通过AWS访问的python版本拥有成功运行python工作脚本所需的所有包?
理论上,您可以使用用户数据运行您想要的任何脚本或CLI命令,包括安装python和pip依赖项,但是如果安装起来太复杂/太重,我建议您构建一个映像并从它启动,如前所述。
https://stackoverflow.com/questions/56791681
复制相似问题