51
50

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Lambdaでコマンドやシェルスクリプトを実行してみる(Node.js)

Posted at

Lambdaでコマンドやシェルスクリプトを実行してみる(Node.js)

小ネタです。

コマンドの実行をとりあえずやってみる

Lambdaを選択後のBlueprintを選ぶ画面で node-exec というのがあるのでそれを選べば実行できます。

コードは以下のようになっていました。

index.js
var exec = require('child_process').exec;

exports.handler = function(event, context) {
    if (!event.cmd) {
        context.fail('Please specify a command to run as event.cmd');
        return;
    }
    child = exec(event.cmd, function(error) {
        // Resolve with result of process
        context.done(error, 'Process complete!');
    });

    // Log process stdout and stderr
    child.stdout.on('data', console.log);
    child.stderr.on('data', console.error);
};

child_process.execメソッドでは第一引数に実行するコマンドを指定し、第2引数でコマンドが終了した時に結果をコールバックで受け取とっています。上記例だとevent.cmdとして実行するコマンドを指定しています。
また、コマンド実行時の標準出力、標準エラー出力はdataイベントが発生したタイミングで随時console.logとして出力されるようになっています。

Node.jsのv0.11以降であればexecSyncというメソッドが追加されており、同期的にコマンド実行ができますが、2015/12/26現在のLambdaで実行可能なNode.jsはv0.10.36となっていたのでこれは使えないですね。。。。

話が少しそれてしまいました。
試しにマネージメントコンソールのLambdaのページからコマンドを実行してみます。

画面上で作成したfunctionを指定し、

Action->Configure test event

と選択し

{
  "cmd": "cat /etc/system-release"
}

という形で記述する事でコマンドを実行する事ができます。
ちなみに実行すると以下の結果でした。

2015-12-26T06:48:42.028Z	b37dec85-ab9c-11e5-a810-83acc71c00c9	Amazon Linux AMI release 2015.09

シェルスクリプトを実行してみる

では次にシェルスクリプトを実行してみます。Nodeのコードを./exec.shを実行するように変更し、併せて実行するシェルスクリプトのファイルをアップロードする事で実行するようにしています。

ディレクト、ファイルを作成します。

$mkdir node-exec
$cd node-exec
$vi index.js
$vi exec.sh
index.js
var exec = require('child_process').exec;

exports.handler = function(event, context) {
  child = exec('/bin/bash ./exec.sh', function(error) {
      // Resolve with result of process
      context.done(error, 'Process complete!');
  });

  // Log process stdout and stderr
  child.stdout.on('data', console.log);
  child.stderr.on('data', console.error);
};
exec.sh
# !/bin/bash


# 以下にシェルスクリプトを書く
ls /usr/bin
ls /bin

ファイル作成後、zip圧縮し、lambdaへアップロードします。

# zipにまとめる
$zip -r node-exec.zip index.js exec.sh

# コードのアップロード.function-nameが違う場合には適宜変更
$aws lambda update-function-code --function-name node-exec --zip-file fileb://./node-exec.zip

上記を実行する事でコマンドが実行できます。

[おまけ]lambdaで色々やってみた

以下、おまけです。

  • awsコマンドはインストールされているか->されていません
  • curlによるメタデータの取得->できませんでした
  • curlによるgoogleへの接続->できました
  • echo $PATH->/usr/local/bin:/usr/bin:/bin。コマンドをざっと見る限り、Linuxコマンドはあまり制限されていないようでした
51
50
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
51
50

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?