2017-08-24 43 views
1

通過谷歌搜索,我發現this tutorial on accessing S3 from EC2 instance without credential file。我遵循它的指示並獲得了期望的實例。 aws web控制檯頁面看起來像 enter image description here如何給ec2實例訪問s3使用boto3

但是,我不想每次都使用Web控制檯手動執行此操作。我如何使用boto3創建這樣的EC2實例?

我試圖

s = boto3.Session(profile_name='dev', region_name='us-east-1') 
ec2 = s.resource('ec2') 
rc = ec2.create_instances(ImageId='ami-0e297018', 
          InstanceType='t2.nano', 
          MinCount=1, 
          MaxCount=1, 
          KeyName='my-key', 
          IamInstanceProfile={'Name': 'harness-worker'}, 
         ) 

其中harness-worker是獲得S3的IAM角色,但沒有別的。 它也用於aws web控制檯教程的第一種方法。

後來我有錯誤說

ClientError: An error occurred (UnauthorizedOperation) when calling the RunInstances operation: You are not authorized to perform this operation.

難道我顯然是錯誤的?

dev配置文件有AmazonEC2FullAccess。如果沒有行IamInstanceProfile={'Name': 'harness-worker'},create_instances能夠創建實例。

回答

2

要將IAMP分配給實例,AmazonEC2FullAccess是不夠的。另外,您需要以下特權才能將角色傳遞給實例。

參見:Granting an IAM User Permission to Pass an IAM Role to an Instance

{ 
    "Effect": "Allow", 
    "Action": "iam:PassRole", 
    "Resource": "*" 
} 

首先,你可以充分IAM訪問您的個人資料dev,看看它的工作原理。然後刪除完整的IAM訪問權限,只給出iam:PassRole並重試。

0

這與您嘗試分配新EC2實例的角色無關。您正在運行的Python腳本沒有RunInstances權限。

+0

對不起,我是boto3和aws的新手。你能解釋一下如何解決它?謝謝。 – nos

+0

如果您的python腳本正在使用與AWS API接口的IAM憑據,則您需要進行一些排序。這些憑證沒有權限創建新的EC2實例。這不是你的代碼的問題。這是您正在使用的IAM帳戶或個人資料的問題。 –

+0

開發人員配置文件具有AmazonEC2FullAccess。沒有行IamInstanceProfile = {'Name':'harness-worker'},create_instances能夠創建實例。 – nos