AWS Config ルールの AWS Lambda 関数の例 (Node.js) - AWS Config

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

AWS Config ルールの AWS Lambda 関数の例 (Node.js)

AWS Lambda は、 AWS サービスによって発行されたイベントに応答して関数を実行します。 AWS Config カスタム Lambda ルールの 関数は、 によって発行されたイベントを受け取り AWS Config、そのイベントから受け取ったデータと AWS Config API から取得したデータを使用してルールのコンプライアンスを評価します。Config ルールの関数のオペレーションは、設定変更でトリガーされる評価を実行するか、定期的にトリガーされる評価を実行するかで異なります。

AWS Lambda 関数内の一般的なパターンについては、「 AWS Lambda デベロッパーガイド」の「モデルのプログラミング」を参照してください。

設定変更でトリガーされる評価の関数の例

AWS Config は、カスタムルールの範囲内にあるリソースの設定変更を検出すると、次の例のような関数を呼び出します。

AWS Config コンソールを使用して、この例のような関数に関連付けられたルールを作成する場合は、トリガータイプとして設定の変更を選択します。 AWS Config API または を使用してルール AWS CLI を作成する場合は、 MessageType 属性を ConfigurationItemChangeNotificationおよび に設定しますOversizedConfigurationItemChangeNotification。これらの設定により、 がリソースの変更の結果として設定項目またはオーバーサイズの設定項目 AWS Config を生成するたびに、ルールをトリガーできます。

この例では、リソースを評価し、インスタンスがリソースタイプ AWS::EC2::Instance と一致するかどうかを確認します。 AWS Config で設定項目またはサイズが大きすぎる設定項目が生成されると、ルールがトリガーされます。

'use strict'; import { ConfigServiceClient, GetResourceConfigHistoryCommand, PutEvaluationsCommand } from "@aws-sdk/client-config-service"; const configClient = new ConfigServiceClient({}); // Helper function used to validate input function checkDefined(reference, referenceName) { if (!reference) { throw new Error(`Error: ${referenceName} is not defined`); } return reference; } // Check whether the message type is OversizedConfigurationItemChangeNotification, function isOverSizedChangeNotification(messageType) { checkDefined(messageType, 'messageType'); return messageType === 'OversizedConfigurationItemChangeNotification'; } // Get the configurationItem for the resource using the getResourceConfigHistory API. async function getConfiguration(resourceType, resourceId, configurationCaptureTime, callback) { const input = { resourceType, resourceId, laterTime: new Date(configurationCaptureTime), limit: 1 }; const command = new GetResourceConfigHistoryCommand(input); await configClient.send(command).then( (data) => { callback(null, data.configurationItems[0]); }, (error) => { callback(error, null); } ); } // Convert the oversized configuration item from the API model to the original invocation model. function convertApiConfiguration(apiConfiguration) { apiConfiguration.awsAccountId = apiConfiguration.accountId; apiConfiguration.ARN = apiConfiguration.arn; apiConfiguration.configurationStateMd5Hash = apiConfiguration.configurationItemMD5Hash; apiConfiguration.configurationItemVersion = apiConfiguration.version; apiConfiguration.configuration = JSON.parse(apiConfiguration.configuration); if ({}.hasOwnProperty.call(apiConfiguration, 'relationships')) { for (let i = 0; i < apiConfiguration.relationships.length; i++) { apiConfiguration.relationships[i].name = apiConfiguration.relationships[i].relationshipName; } } return apiConfiguration; } // Based on the message type, get the configuration item either from the configurationItem object in the invoking event or with the getResourceConfigHistory API in the getConfiguration function. async function getConfigurationItem(invokingEvent, callback) { checkDefined(invokingEvent, 'invokingEvent'); if (isOverSizedChangeNotification(invokingEvent.messageType)) { const configurationItemSummary = checkDefined(invokingEvent.configurationItemSummary, 'configurationItemSummary'); await getConfiguration(configurationItemSummary.resourceType, configurationItemSummary.resourceId, configurationItemSummary.configurationItemCaptureTime, (err, apiConfigurationItem) => { if (err) { callback(err); } const configurationItem = convertApiConfiguration(apiConfigurationItem); callback(null, configurationItem); }); } else { checkDefined(invokingEvent.configurationItem, 'configurationItem'); callback(null, invokingEvent.configurationItem); } } // Check whether the resource has been deleted. If the resource was deleted, then the evaluation returns not applicable. function isApplicable(configurationItem, event) { checkDefined(configurationItem, 'configurationItem'); checkDefined(event, 'event'); const status = configurationItem.configurationItemStatus; const eventLeftScope = event.eventLeftScope; return (status === 'OK' || status === 'ResourceDiscovered') && eventLeftScope === false; } // In this example, the resource is compliant if it is an instance and its type matches the type specified as the desired type. // If the resource is not an instance, then this resource is not applicable. function evaluateChangeNotificationCompliance(configurationItem, ruleParameters) { checkDefined(configurationItem, 'configurationItem'); checkDefined(configurationItem.configuration, 'configurationItem.configuration'); checkDefined(ruleParameters, 'ruleParameters'); if (configurationItem.resourceType !== 'AWS::EC2::Instance') { return 'NOT_APPLICABLE'; } else if (ruleParameters.desiredInstanceType === configurationItem.configuration.instanceType) { return 'COMPLIANT'; } return 'NON_COMPLIANT'; } // Receives the event and context from AWS Lambda. export const handler = async (event, context) => { checkDefined(event, 'event'); const invokingEvent = JSON.parse(event.invokingEvent); const ruleParameters = JSON.parse(event.ruleParameters); await getConfigurationItem(invokingEvent, async (err, configurationItem) => { let compliance = 'NOT_APPLICABLE'; let annotation = ''; const putEvaluationsRequest = {}; if (isApplicable(configurationItem, event)) { // Invoke the compliance checking function. compliance = evaluateChangeNotificationCompliance(configurationItem, ruleParameters); if (compliance === "NON_COMPLIANT") { annotation = "This is an annotation describing why the resource is not compliant."; } } // Initializes the request that contains the evaluation results. if (annotation) { putEvaluationsRequest.Evaluations = [ { ComplianceResourceType: configurationItem.resourceType, ComplianceResourceId: configurationItem.resourceId, ComplianceType: compliance, OrderingTimestamp: new Date(configurationItem.configurationItemCaptureTime), Annotation: annotation }, ]; } else { putEvaluationsRequest.Evaluations = [ { ComplianceResourceType: configurationItem.resourceType, ComplianceResourceId: configurationItem.resourceId, ComplianceType: compliance, OrderingTimestamp: new Date(configurationItem.configurationItemCaptureTime), }, ]; } putEvaluationsRequest.ResultToken = event.resultToken; // Sends the evaluation results to AWS Config. await configClient.send(new PutEvaluationsCommand(putEvaluationsRequest)); }); };
関数のオペレーション

関数はランタイムに以下のオペレーションを実行します。

  1. 関数は、 が event オブジェクトをhandler関数に AWS Lambda 渡すときに実行されます。この例では、関数は、呼び出し元に情報を返すために使用するオプションの callbackパラメータを受け入れます。 AWS Lambda また、 は、関数の実行中に使用できる情報とメソッドを含む context オブジェクトを渡します。Lambda の新しいバージョンでは、コンテキストは使用されなくなりました。

  2. 関数は、イベントの messageType が設定項目であるかサイズが大きすぎる設定項目であるかを確認し、その設定項目を返します。

  3. ハンドラーは、isApplicable 関数を呼び出してリソースが削除されたかどうかを確認します。

    注記

    削除されたリソースをレポートするルールは、不必要なルール評価を避けるために、NOT_APPLICABLE の評価結果を返す必要があります。

  4. ハンドラーは evaluateChangeNotificationCompliance関数を呼び出し、 イベントで AWS Config 発行した configurationItemおよび ruleParameters オブジェクトを渡します。

    関数は最初にリソースが EC2 インスタンスであるかどうかを評価します。リソースが EC2 インスタンスではない場合、関数はコンプライアンス値として NOT_APPLICABLE を返します。

    次に、関数は設定項目の instanceType 属性が desiredInstanceType パラメータ値と等しいかどうかを評価します。値が等しい場合、関数は COMPLIANT を返します。値が等しくない場合、関数は NON_COMPLIANT を返します。

  5. ハンドラーは、 putEvaluationsRequest オブジェクトを初期化 AWS Config して、評価結果を に送信する準備をします。このオブジェクトに含まれている Evaluations パラメータは、評価対象のリソースのコンプライアンス結果、リソースタイプ、および ID を識別します。putEvaluationsRequest オブジェクトには、 のルールとイベントを識別するイベントの結果トークンも含まれます AWS Config。

  6. ハンドラーは、 オブジェクトをconfigクライアントの putEvaluationsメソッドに渡す AWS Config ことで、評価結果を に送信します。

定期的な評価の関数の例

AWS Config は、定期的な評価のために、次の例のような関数を呼び出します。定期的な評価は、 AWS Configでのルールの定義時に指定した間隔で発生します。

AWS Config コンソールを使用して、この例のような関数に関連付けられたルールを作成する場合は、トリガータイプとして「定期的」を選択します。 AWS Config API または を使用してルール AWS CLI を作成する場合は、 MessageType 属性を に設定しますScheduledNotification

この例では、指定したリソースの合計数が指定した最大値を超えているかどうかを確認します。

'use strict'; import { ConfigServiceClient, ListDiscoveredResourcesCommand, PutEvaluationsCommand } from "@aws-sdk/client-config-service"; const configClient = new ConfigServiceClient({}); // Receives the event and context from AWS Lambda. export const handler = async (event, context, callback) => { // Parses the invokingEvent and ruleParameters values, which contain JSON objects passed as strings. var invokingEvent = JSON.parse(event.invokingEvent), ruleParameters = JSON.parse(event.ruleParameters), numberOfResources = 0; if (isScheduledNotification(invokingEvent) && hasValidRuleParameters(ruleParameters, callback)) { await countResourceTypes(ruleParameters.applicableResourceType, "", numberOfResources, async function (err, count) { if (err === null) { var putEvaluationsRequest; const compliance = evaluateCompliance(ruleParameters.maxCount, count); var annotation = ''; if (compliance === "NON_COMPLIANT") { annotation = "Description of why the resource is not compliant."; } // Initializes the request that contains the evaluation results. if (annotation) { putEvaluationsRequest = { Evaluations: [{ // Applies the evaluation result to the AWS account published in the event. ComplianceResourceType: 'AWS::::Account', ComplianceResourceId: event.accountId, ComplianceType: compliance, OrderingTimestamp: new Date(), Annotation: annotation }], ResultToken: event.resultToken }; } else { putEvaluationsRequest = { Evaluations: [{ // Applies the evaluation result to the AWS account published in the event. ComplianceResourceType: 'AWS::::Account', ComplianceResourceId: event.accountId, ComplianceType: compliance, OrderingTimestamp: new Date() }], ResultToken: event.resultToken }; } // Sends the evaluation results to AWS Config. try { await configClient.send(new PutEvaluationsCommand(putEvaluationsRequest)); } catch (e) { callback(e, null); } } else { callback(err, null); } }); } else { console.log("Invoked for a notification other than Scheduled Notification... Ignoring."); } }; // Checks whether the invoking event is ScheduledNotification. function isScheduledNotification(invokingEvent) { return (invokingEvent.messageType === 'ScheduledNotification'); } // Checks the rule parameters to see if they are valid function hasValidRuleParameters(ruleParameters, callback) { // Regular express to verify that applicable resource given is a resource type const awsResourcePattern = /^AWS::(\w*)::(\w*)$/; const isApplicableResourceType = awsResourcePattern.test(ruleParameters.applicableResourceType); // Check to make sure the maxCount in the parameters is an integer const maxCountIsInt = !isNaN(ruleParameters.maxCount) && parseInt(Number(ruleParameters.maxCount)) == ruleParameters.maxCount && !isNaN(parseInt(ruleParameters.maxCount, 10)); if (!isApplicableResourceType) { callback("The applicableResourceType parameter is not a valid resource type.", null); } if (!maxCountIsInt) { callback("The maxCount parameter is not a valid integer.", null); } return isApplicableResourceType && maxCountIsInt; } // Checks whether the compliance conditions for the rule are violated. function evaluateCompliance(maxCount, actualCount) { if (actualCount > maxCount) { return "NON_COMPLIANT"; } else { return "COMPLIANT"; } } // Counts the applicable resources that belong to the AWS account. async function countResourceTypes(applicableResourceType, nextToken, count, callback) { const input = { resourceType: applicableResourceType, nextToken: nextToken }; const command = new ListDiscoveredResourcesCommand(input); try { const response = await configClient.send(command); count = count + response.resourceIdentifiers.length; if (response.nextToken !== undefined && response.nextToken != null) { countResourceTypes(applicableResourceType, response.nextToken, count, callback); } callback(null, count); } catch (e) { callback(e, null); } return count; }
関数のオペレーション

関数はランタイムに以下のオペレーションを実行します。

  1. 関数は、 が event オブジェクトをhandler関数に AWS Lambda 渡すときに実行されます。この例では、関数は、呼び出し元に情報を返すために使用するオプションの callbackパラメータを受け入れます。 AWS Lambda また、 は、関数の実行中に使用できる情報とメソッドを含む context オブジェクトを渡します。Lambda の新しいバージョンでは、コンテキストは使用されなくなりました。

  2. 指定したタイプのリソースをカウントするために、ハンドラーは countResourceTypes 関数を呼び出し、イベントから受け取った applicableResourceType パラメータを渡します。countResourceTypes 関数は、listDiscoveredResources クライアントの config メソッドを呼び出します。クライアントは、該当するリソースの ID のリストを返します。関数は、このリストの長さに基づいて該当するリソースの数を判断し、この数をハンドラーに返します。

  3. ハンドラーは、 putEvaluationsRequest オブジェクトを初期化 AWS Config して、評価結果を に送信する準備をします。このオブジェクトには、コンプライアンス結果を識別する Evaluationsパラメータと、イベントで AWS アカウント 発行された が含まれます。Evaluations パラメータでは、 AWS Configでサポートされている任意のリソースタイプに結果を適用できます。putEvaluationsRequest オブジェクトには、 のルールとイベントを識別するイベントの結果トークンも含まれます AWS Config。

  4. putEvaluationsRequest オブジェクト内で、ハンドラーは evaluateCompliance 関数を呼び出します。この関数は、該当するリソースの数が、イベントから提供された maxCount パラメータに割り当てた最大値を超えているかどうかをテストします。リソース数が最大値を超えている場合、関数は NON_COMPLIANT を返します。リソース数が最大値を超えていない場合、関数は COMPLIANT を返します。

  5. ハンドラーは、 オブジェクトをconfigクライアントの putEvaluationsメソッドに渡す AWS Config ことで、評価結果を に送信します。