简体   繁体   English

Python Boto3将文件从ec2上传到S3

[英]Python boto3 upload file to S3 from ec2

If I want to upload a file from my "mac" to S3, I can use 如果要将文件从“ mac”上传到S3,可以使用

import boto3
s3 = boto3.resource('s3', region_name="us-west-1")
s3.meta.client.upload_file('/User/gantao/amz.jpg', 'gantao_created', 'amz.jpg')

But, 但,

Is there any way to upload a file to S3 from EC2 instance (do not use SSH to EC2) ? 有什么方法可以将文件从EC2实例上传到S3(不要使用SSH到EC2)?

The short answer is "yes." 简短的回答是“是”。

The longer answer is that, in order to upload a file from an EC2 instance to S3, the deployed EC2 instance has to have the correct permissions to put_object to S3. 更长的答案是,为了将文件从EC2实例上载到S3,部署的EC2实例必须具有对put_object到S3的正确权限。

You can either do this by configuring your boto client inside your Python code, or by creating and assigning an IAM role with that permission to your EC2 instance. 您可以通过在Python代码中配置boto客户端,或通过将具有该权限的IAM角色创建并分配给您的EC2实例来执行此操作。

The more secure way is to assign the IAM role, since it doesn't require you to have credentials in code or in a file in source control. 比较安全的方法是分配IAM角色,因为它不需要您在代码或源代码管理文件中拥有凭据。

  1. Use the AWS console to create an IAM role with permission to 'put' objects to the S3 bucket in question. 使用AWS控制台创建一个IAM角色,该角色具有将对象“放入”相关S3存储桶的权限。
  2. Assign the IAM role to your EC2 instance. 将IAM角色分配给您的EC2实例。

To create an IAM role: 创建IAM角色:

https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html

To add an IAM role to your EC2 instance: 要将IAM角色添加到您的EC2实例:

https://aws.amazon.com/blogs/security/easily-replace-or-attach-an-iam-role-to-an-existing-ec2-instance-by-using-the-ec2-console/ https://aws.amazon.com/blogs/security/easily-replace-or-attach-an-iam-role-to-an-existing-ec2-instance-by-using-the-ec2-console/

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

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