如何使用AWS Lambda函数将文件从S3复制到EC2实例?

4

我是AWS Lambda的新手。我的问题是:在Jenkins(托管于AWS)中有一个RPM,通过“S3 artifacts”插件将其复制到S3存储桶中。我必须将此RPM从S3存储桶复制到其他EC2实例。是否有办法Lambda函数可以触发S3从S3复制RPM文件到EC2,以便在从Jenkins复制到S3后进行复制?

      s3-plugin          lambda   

Jenkins--------------->S3----------->Ec2

2个回答

3
如果您是Lambda的新手,首先要知道的是您可以直接将自己的代码放在Lambda函数命令行中,或者上传一个包含您的函数的.zip文件。我们将使用第二种方法来实现从S3到EC2的复制。
为什么我们要上传一个包含函数的.zip文件呢?因为这样我们就可以安装所有需要和想要的依赖项。
现在,为了使这一切成为可能,首先,您的Lambda函数需要通过SSH连接到您的EC2实例。之后,您可以执行一些命令行以下载所需的S3文件。
所以,请将以下代码放入您的Lambda函数(exports.handler内部...),并使用“npm install simple-ssh”安装simple-ssh依赖项。
// imagine that the input variable is the JSON sended from the client.
//input = {
    //s3_file_path : 'folder/folder1/file_name',
    //bucket       : 'your-bucket',
//};

// Use this library to connect easly with your EC2 instance.
var SSH = require('simple-ssh');
var fs  = require('fs');

// This is the full S3 URL object that you need to download the file.
var s3_file_url    = 'https://' + input.bucket + '.s3.amazonaws.com/' + input.s3_file_path;


/**************************************************/
/*                      SSH                       */
/**************************************************/
var ssh = new SSH({
    host: 'YOUR-EC2-PUBLIC-IP',
    user: 'USERNAME',
    passphrase: 'YOUR PASSPHRASE', // If you have one
    key : fs.readFileSync("../credentials/credential.pem") // The credential that you need to connect to your EC2 instance through SSH
});

// wget will download the file from the URL we passed
ssh.exec('wget ' + s3_file_url).start();

// Also, if you wanna download the file to another folder, just do another exec behind to enter to the folder you want.
ssh.exec('cd /folder/folder1/folder2').exec('wget ' + s3_file_url).start();

为了使此功能正常工作,您应确保启用EC2实例的权限,以便可以通过SSH进行访问。


2
简短的回答是不可以。S3本身不能将任何东西复制到其他地方。
正确的思考方式是,S3可以发送通知来启动Lambda函数。您的Lambda函数可以对实例执行某些操作。这似乎相当复杂。
我建议跳过使用Lambda,编写一个脚本直接从您的实例订阅S3存储桶通知SNS主题。该脚本会在文件上传到S3时直接将文件下载到您的实例。此解决方案也可扩展,您可以让多个实例订阅此主题等。

1
你能详细说明一下你的脚本是如何工作的吗?通过http订阅。 - einSelbst
我会使用AWS SDK订阅SNS主题,然后下载文件。 - adamkonrad
感谢您的回复。我仍然不明白在订阅中可以使用哪种协议。通过SDK可以为某个用户创建例如电子邮件订阅,但这不会在SNS发送新通知时通知EC2实例。http://docs.aws.amazon.com/sns/latest/api/API_Subscribe.html - einSelbst
SNS主要通过HTTP(长轮询)进行订阅。我会根据您编写文件下载脚本的语言选择SDK。 - adamkonrad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接