前置
- AWS賬戶
- EC2例項已安裝AWS CLI
步驟1:配置IAM使用者
- 建立IAM使用者
- 新增以下策略:
AmazonS3FullAccess策略
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:*",
"s3-object-lambda:*"
],
"Resource": "*"
}
]
}
AmazonEC2FullAccess策略
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "ec2:*",
"Effect": "Allow",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "elasticloadbalancing:*",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "cloudwatch:*",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "autoscaling:*",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "iam:CreateServiceLinkedRole",
"Resource": "*",
"Condition": {
"StringEquals": {
"iam:AWSServiceName": [
"autoscaling.amazonaws.com",
"ec2scheduled.amazonaws.com",
"elasticloadbalancing.amazonaws.com",
"spot.amazonaws.com",
"spotfleet.amazonaws.com",
"transitgateway.amazonaws.com"
]
}
}
}
]
}
步驟2:在EC2上配置AWS CLI
執行aws configure
並輸入以下資訊:
AWS Access Key ID [None]: ${IAM使用者訪問金鑰ID}
AWS Secret Access Key [None]: ${IAM使用者私有訪問金鑰}
Default region name [None]: us-west-2
Default output format [None]: json
步驟3:檔案複製操作
使用AWS CLI的cp
命令,語法如下:
aws s3 cp <本地路徑> <S3Uri> # 上傳至S3
aws s3 cp <S3Uri> <本地路徑> # 從S3下載
aws s3 cp <S3Uri> <S3Uri> # S3儲存桶間複製
示例
# 上傳檔案至S3
aws s3 cp myfile.txt s3://my-bucket/
# 從S3下載檔案
aws s3 cp s3://my-bucket/myfile.txt ./
# 在S3儲存桶間複製
aws s3 cp s3://source-bucket/file.txt s3://dest-bucket/
安全最佳實踐
- 使用最小許可權訪問 - 建議將S3許可權限制到特定儲存桶
- 定期輪換IAM訪問金鑰
- 切勿共享或提交AWS憑證
- 考慮對EC2例項使用IAM角色而不是訪問金鑰