2

我是AWS lambda的新手。我的问题是, 我在Jenkins(托管在AWS)中有一个RPM,它使用'S3 artifacts'插件将其复制到S3存储桶。我必须将此RPM从S3存储桶复制到其他EC2实例。 在从Jenkins复制到S3之后,Lambda函数是否可以触发S3将S3文件从RPM复制到Ec2?如何使用AWS Lambda函数将文件从S3复制到EC2实例?

 s3-plugin   lambda 

詹金斯---------------> S3 -----------> EC2

回答

1

简短的答案是否定的。 S3本身无法复制任何地方

想想这个的正确方法是S3可以发送一个可以启动Lambda函数的通知。您的Lambda函数然后可以对该实例执行一些操作。看起来相当复杂。

我会跳过使用Lambda并编写了一个脚本,可以直接从您的实例订阅S3存储桶通知SNS主题。该脚本会在将文件上传到S3时直接下载到您的实例。这个解决方案也是可扩展的,你可以有很多订阅这个主题的实例等。

+0

你能详细说明你的脚本是如何工作的吗?通过http订阅? – einSelbst

+0

我会使用AWS SDK订阅SNS主题,然后下载该文件。 – kixorz

+0

感谢您的回复。我仍然不明白订阅中可以使用哪种协议。可以创建例如。某些用户通过SDK订阅电子邮件但在SNS发送新通知时不会通知EC2实例。 http://docs.aws.amazon.com/sns/latest/api/API_Subscribe.html – einSelbst

1

所以如果你是Lambda的新手,你必须首先知道你可以直接在Lambda函数命令行中输入你自己的代码,或者你也可以上传一个包含你的功能的.zip文件。第二个是我们将用来从s3复制到EC2的那个。

¿为什么我们要用这个函数上传一个.zip文件? 因为通过这种方式我们可以安装我们需要的所有依赖关系。

现在,为了实现这一点,首先,您的lambda函数需要通过SSH连接到您的EC2实例。之后,你可以执行一些命令行来下载你想要的S3文件。

所以把这段代码到你的拉姆达函数(exports.handler内....),并以“NPM安装简单的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(); 

对于这个工作安装简单-SSH的依赖,您应该确保您的EC2计算机已启用权限,以便可以通过SSH进行输入。

相关问题