繁体   English   中英

教程:使用来自 S3 的数据使用 boto3 将 python 脚本提交到 EC2

[英]Tutorial: Submitting python script to EC2 using boto3 with data from S3

我是 AWS 的新手,想在 EC2 实例(例如 c4.4xlarge)上运行一个非常并行的 python工作脚本。

我已经解决了有关该主题的问题,但没有找到我需要采取的步骤的高级答案。 我有 AWS 凭证并且在我的笔记本电脑的 python 2 上安装了 boto3。

我如何构建一个 python提交脚本:

  1. 连接到我的 Python工作脚本和依赖项所在的 S3
  2. 启动所需类型的 EC2 实例
  3. 提交要由EC2实例处理的python工作脚本

此外,在我的 python工作脚本中,如何将工作脚本的结果保存回 S3?

最后,如何确保我通过 AWS 访问的 python 版本具有成功运行我的 python工作脚本所需的所有包?

对不起,如果问题太高级并且有任何概念错误。 感谢您的任何指点!

为了实现这一点,我想为您当前的流程提供更多细节建议:

在提交脚本中:

  • 上传/刷新 S3 存储桶上的任何依赖项。
  • 启动 EC2 实例。

在 EC2 实例中:

  • 下载依赖。
  • 做工作。
  • 将结果上传到 S3。
  • 终止实例。

有两种简单的方法可以在 EC2 实例上运行命令,SSH 或使用 user-data 属性。 为简单起见,对于您当前的用例,我建议使用 user-data 方法。

首先,您需要创建一个具有下载/上传到 S3 存储桶的权限的EC2-InstanceProfile 然后您可以创建一个 EC2,安装任何 python 或 pip 包并将其注册为AMI

下面是一些参考代码: 注意这段代码是在 python3 中的,只适用于 Windows 机器。

提交.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
)

实例工作者:

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 依赖项,但如果安装太复杂/繁重,我建议您构建一个映像并从中启动,如之前提到过。

暂无
暂无

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

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