2017-02-22 31 views
1

我想在AWS lambda中安排一个作业,我从Json API中获取数据。我想每次都将JSON文件传输到Amazon S3。我已经设置了S3存储桶和aws lambda函数,并具有适当的IAM角色。我正在Python中编写AWS lambda函数。代码可以在EC2实例上正常工作,但如果我将它放入AWS Lambda中,则不会将文件传输到S3。如何在aws lambda中执行bash命令

import os 


def lambda_handler(event, context): 
    #changing the directory to /tmp 
    os.chdir("/tmp") 
    print "loading function" 
    #downloading file to 
    os.system("wget https://jsonplaceholder.typicode.com/posts/1 -P /tmp") 
    #using aws-cli to transfer file to amazon S3 
    os.system("aws s3 sync . s3://targetbucket") 

我是新来的aws lambda。我没有收到任何错误,但它没有给我预期的输出

回答

2

AWS Lambda在默认情况下没有aws cli

您可以创建一个deployment package其中awscli它或使用python boto3库。

import boto3 

s3client = boto3.client('s3') 
for filename in os.listdir('/tmp'): # assuming there will not be any sub-directories 
    fpath = os.path.join('/tmp',filename) 
    if os.path.isfile(fpath): 
     s3client.upload_file(fpath, 'targetbucket', filename) 
+0

感谢您的回复。你的代码工作正常。看来我无法使用下载文件 - os.system(“wget https://jsonplaceholder.typicode.com/posts/1 -P/tmp”) 我是否需要创建部署包以使用bash命令os.system(“bash命令”)? – liferacer

+0

@Navjot我从来没有检查过'wget'是否在lambda中工作。否则,您可以使用'urllib'模块。 'urllib.urlretrieve(“https://jsonplaceholder.typicode.com/posts/1”,“file.json”)' – franklinsijo

+0

是的 它适用于urllib。感谢您的建议。我想我将不得不部署wget和awscli作为部署包的一部分。 – liferacer