LambdaのClowdWatchログに、bat実行結果の戻り値を出力したい

0

EC2インスタンス(Windows)にあるbatファイルを、Lambdaで、Systems Manager Run Commandを利用して実行させています。

CloudWatchログにバッチの戻り値(EXIT値)である「9」を出力させたいのですが、現状では、「START RequestId:」と、「END RequestId:」 しか出力されません。

どうコードを修正していけば、状況が改善されますでしょうか。 ご支援をいただけますと幸いに存じます、何卒宜しくお願い致します。

以下コード全文です。

exit /b 9
'use strict';

const AWS = require('aws-sdk')
const ssm = new (require('aws-sdk/clients/ssm'))();

module.exports.handler = async event => {

	try {
		let params = {
			DocumentName: 'AWS-RunPowerShellScript',
			InstanceIds: ['対象のインスタンスID'],
			Parameters: {
				commands: ['chcp 65001; Start-Process -wait test_win.bat'], 
				workingDirectory:['C:\\Users\\administrator\\temp'], 
			},
			// タイムアウト設定
			TimeoutSeconds: 3600 // 1 hour
    		}
		const sendCommandResult = await ssm.sendCommand(params).promise();  
			} catch(e){
    	console.log(e);
	}	

	};

以上

1 Answer
0

はじめに、SendCommand API で実行した bat ファイルの exit code を Run Command の exit code とする場合、bat ファイルを実行した際の exit code を明示的に exit に渡す必要があります。

そのため、Lambda 関数から SendCommand API を実行する際、commands パラメータを以下のように定義することをご検討ください。

commands: ['chcp 65001; $process = Start-Process test_win.bat -PassThru -Wait', 'exit $process.Exitcode'], 

次に、SendCommand API は非同期的な API であり、実行した bat ファイルの実行結果を同期的に取得することができません。

対策といたしまして、Lambda 関数から SendCommand API の実行後に GetCommandInvocation API を定期的に実行し、Status プロパティが Success となった時点のレスポンスを確認いただく方法が考えられます。

なお、SendCommand API にて bat ファイルを実行した際の exit code を明示的に exit に渡している場合、bat ファイルの exit code は GetCommandInvocation API のレスポンスの ResponseCode プロパティに記録されます。

そのため、Lambda 関数から以下のような処理をおこなうことで、bat ファイルの exit code を CloudWatch Logs に出力いただけるかと存じます。

  1. SendCommand API で bat ファイルを実行し、その際のレスポンスに含まれる CommandId を取得
  2. GetCommandInvocation API を 1 で取得した CommandId に対して実行し、レスポンスから Status の値を取得
  3. 2 を一定間隔で繰り返し、GetCommandInvocation API のレスポンスに含まれる Status プロパティの値が Success となった時点で、ResponseCode プロパティの値をログに出力
AWS
Ito_K
answered a year ago
  • Ito K様 ご回答ありがとうございます。 commands パラメータの修正だけでなく、GetCommandInvocation API を利用したコードを、Lambda内に書く必要があるのですね。 このあたり難解なため、少し時間をかけて確認していきたいと思います。

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions