2017-10-04 31 views
0

我有一個boto3腳本,可以使用我的賬戶的AccessKeyId和SecretAccessKey成功將文件上傳到S3存儲桶。這工作正常。我應該用boto3寫一個只有IAM實例配置文件的S3存儲桶,但是怎麼做?

但我應該從這個實例中刪除我的憑據,並只使用附加到實例的IAM角色。我已經做了各種嘗試,但還沒有得到這個工作,一般用:

botocore.exceptions.ClientError: An error occurred (InvalidToken) when 
calling the PutObject operation: The provided token is malformed or 
otherwise invalid. 

我的代碼:

!/usr/bin/env python 

import datetime 
import sys 
import os 
import ConfigParser 
import boto3 

s3 = boto3.resource('s3') 

config = ConfigParser.ConfigParser() 
configfile = config.read('edi.config') 

s3bucket = config.get('default', 's3bucket') 

s3bucket = s3bucket.strip() 

print 's3bucket: ', s3bucket 

today = datetime.date.today() 

todaystr = today.strftime('%m_%d_%Y') 
os.chdir(todaystr) 
try: 
    os.mkdir('uploaded') 
except: 
    pass 

for f in os.listdir('.'): 
    if not os.path.isfile(f): 
     continue 

print 'uploading', f 
data = open(f) 

s3.Bucket('ustc-submissions-non-prod').put_object(Key='closewatch/incoming/%s' % f, Body=data) 
os.rename(f,'uploaded/%s' % f) 

我發現一張紙條,在其他地方,我需要承擔boto3內的IAM角色,但(a)我沒有這樣做的許可,(b)我沒有權限給予我自己的許可,(c)我的同事認爲這不應該是必需的。

有人有這種事情的完整例子嗎?

+0

沒有代碼,它有點難以猜測,但在所有可能的情況下,你都不需要傳遞任何東西。有關更多信息,請參見[boto3 credentials](http://boto3.readthedocs.io/en/latest/guide/configuration.html)。您的使用案例是第8點。 – stdunbar

+0

您需要編輯您的帖子以包含您的代碼(減去憑證),以便我們可以看到您跌倒的位置。如果實例具有正確的IAM角色,您*絕對*不需要訪問密鑰。 –

+0

你可以在命令行中輸入s3 cp foo.txt s3:// bucketname /'嗎? (如果沒有找到'aws'命令,'pip install awscli') –

回答

0

它看起來像問題必須是最新版本的boto3中的錯誤。

我想它在Ruby中:

require 'aws-sdk-s3' 

s3 = Aws::S3::Resource.new(region:'us-west-2') 
obj = s3.bucket('bucket-name').object('key') 
obj.upload_file('/path/to/source/file') 

這個工作,因爲我需要只使用IAM角色!

+0

我想你現在已經有足夠的信息在這裏打開一個問題:https://github.com/boto/boto3/issues –

0

建議:

  1. 升級和/或重新安裝所需的軟件包和依賴的當前版本:

    pip install --upgrade --ignore-installed botocore boto3 awscli 
    
  2. 驗證aws configure list顯示iam-role下類型:

    access_key  ****************DFAB   iam-role 
    secret_key  ****************zxQ4   iam-role 
    
  3. 簡化您的代碼。如果你想要做的只是上傳一個文件,那麼你正在走一條很長的風景線!試試這個MCVE代替:

    import boto3 
    with open('example.txt', 'w') as f: 
        f.write('This is an example.') 
    s3 = boto3.client('s3') 
    s3.upload_file(Filename='example.txt', 
           Bucket='ustc-submissions-non-prod', 
           Key='example.txt') 
    
  4. 一旦你的角色問題得到解決:如果您的企業需要的是通過上載新文件,他們在同步與S3存儲的本地目錄,可以考慮使用現有的aws s3 sync命令來代替的自定義腳本。

+0

感謝您的建議;我創建了一個具有相同角色的新實例(FullS3AccessToEC2),但是在嘗試上面列出的腳本時,我再次收到'token'錯誤:oto3.exceptions.S3UploadFailedError:無法將example.txt上載到ustc-submission-non-prod/example.txt:調用PutObject操作時發生錯誤(InvalidToken):提供的令牌格式不正確或無效。 –

+0

在bash提示符下運行'aws s3 ls'時你看到同樣的錯誤嗎? –

+0

是的!我想知道如果我應該嘗試boto2? –

相關問題