At the moment, JavaScript / Node.js is the only language that can be used as a Lambda function in AWS Lambda. But some people want to write it in Python, so I ran the script written in Python.
But it's not difficult. We know that scripts that run as Lambda functions can execute external commands. We also found in a previous survey that there is a python runtime in the environment (see ls results in Uncover AWS Lambda).
So all you have to do is generate a script written in Python using JavaScript in your Lambda function and call it as an external command using child_process ().
Let's do it now.
This time, instead of generating the script in the Lambda function, the script prepared in advance is saved in S3, and it is acquired by HTTP access in the environment of the Lambda function and executed. In addition, when fetching a file by HTTP, curl is used because there is no wget in the environment of Lambda function for some reason.
First, prepare a Python script that you want to execute. This time I tried it and made it look like this.
test.py
#! /usr/bin/python
print "Hello, Wordl!"
Give this to S3 and make public to enable HTTP access.
Next is the code of the Lambda function that is actually registered.
index.js
exports.handler = function(event, context) {
var exec = require('child_process').exec;
var cmd = "curl -s https://s3-ap-northeast-1.amazonaws.com/<bucket name>/test.py > /tmp/test.py;chmod 755 /tmp/test.py;/tmp/test.py"
var child = exec(cmd, function(error, stdout, stderr) {
if (!error) {
console.log('standard out: ' + stdout);
console.log('standard error: ' + stderr);
context.done();
} else {
console.log("error code: " + error.code + ", err: " + error);
context.done(error,'lambda');
}
});
};
Yes, as you may have noticed, the previous script is the same. I'm just changing the external command to execute. The commands that are actually being executed are simply executing the following in order.
Now let's invoke the Lambda function.
2014-11-26T11:51:47.683Z a0862c9f-7562-11e4-8f05-ebd8b45899f3 standard out: Hello, Wordl!
Oh, it was executed properly and "Hello, World!" Was output!
So, regardless of whether it is actually useful or not, I ran a script written in Python with a Lambda function.
** Disclaimer This is an individual opinion, regardless of the company or organization to which it belongs. ** **
Recommended Posts