Amazon Config 规则的示例 Amazon Lambda 函数 (Node.js) - Amazon Config
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

Amazon Config 规则的示例 Amazon Lambda 函数 (Node.js)

Amazon Lambda 执行函数以响应 Amazon 服务发布的事件。 Amazon Config 自定义 Lambda 规则的函数接收由发布的事件 Amazon Config,然后该函数使用从该事件中接收的数据以及从 Amazon Config API 检索的数据来评估规则的合规性。用于 Config 规则的函数的运作方式会因其执行的评估是由配置更改触发还是定期触发而有所不同。

有关 Amazon Lambda 函数中常见模式的信息,请参阅《Amazon Lambda 开发人员指南》中的编程模型

评估由配置更改触发时的示例函数

Amazon Config 当它检测到自定义规则范围内的资源的配置更改时,将调用如下例所示的函数。

如果您使用 Amazon Config 控制台创建与函数相关联的规则(例如此示例),请选择配置更改作为触发器类型。如果您使用 Amazon Config API 或创建规则, Amazon CLI 请将MessageType属性设置为ConfigurationItemChangeNotificationOversizedConfigurationItemChangeNotification。通过这些设置,无论何时由于资源更改而 Amazon Config 生成配置项目或超大配置项目,都可触发您的规则。

此示例评估您的资源并检查实例是否匹配资源类型 AWS::EC2::Instance。此规则在 Amazon 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对象 Amazon Lambda 传递给handler函数时运行。在此示例中,该函数接受可选callback参数,该参数用于向调用者返回信息。 Amazon Lambda 还传递一个context对象,其中包含函数在运行时可以使用的信息和方法。请注意,在新版本的 Lambda 中,不再使用上下文。

  2. 此函数检查事件的 messageType 是配置项还是过大配置项,然后返回配置项。

  3. 处理程序调用 isApplicable 函数来确定资源是否已删除。

    注意

    报告已删除资源的规则应返回 NOT_APPLICABLE 的评估结果,以避免不必要的规则评估。

  4. 处理程序调用该evaluateChangeNotificationCompliance函数并传递在事件中 Amazon Config 发布的configurationItemruleParameters对象。

    函数首先评估资源是否为 EC2 实例。如果资源不是 EC2 实例,函数会返回 NOT_APPLICABLE 这一合规性值。

    然后,函数评估配置项中的 instanceType 属性是否与 desiredInstanceType 参数值一致。如果值相等,该函数将返回 COMPLIANT。如果值不相等,该函数将返回 NON_COMPLIANT

  5. 处理程序准备 Amazon Config 通过初始化putEvaluationsRequest对象将评估结果发送到。该对象包含 Evaluations 参数,这一参数用于识别受评估资源的合规性结果、资源类型和 ID。该putEvaluationsRequest对象还包括事件的结果标记,用于标识规则和事件 Amazon Config。

  6. Amazon Config 通过将对象传递给config客户端putEvaluations的方法,处理程序将评估结果发送到。

定期评估时的示例函数

Amazon Config 将调用如下例所示的函数进行定期评估。定期评估按您在 Amazon Config中定义规则时指定的频率进行。

如果您使用 Amazon Config 控制台创建与函数关联的规则(例如此示例),请选择周期作为触发器类型。如果您使用 Amazon Config API 或创建规则, Amazon 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对象 Amazon Lambda 传递给handler函数时运行。在此示例中,该函数接受可选callback参数,该参数用于向调用者返回信息。 Amazon Lambda 还传递一个context对象,其中包含函数在运行时可以使用的信息和方法。请注意,在新版本的 Lambda 中,不再使用上下文。

  2. 为计数指定类型的资源,处理程序会调用 countResourceTypes 函数,而且它传递其从事件收到的 applicableResourceType 参数。countResourceTypes 函数调用 listDiscoveredResources 客户端的 config 方法,该方法返回适用资源的标识符列表。该函数使用此列表的长度来确定适用资源的数量,而且它将此计数返回到处理程序。

  3. 处理程序准备 Amazon Config 通过初始化putEvaluationsRequest对象将评估结果发送到。此对象包括Evaluations参数,该参数标识合规性结果和 Amazon Web Services 账户 在事件中发布的结果。您可以使用 Evaluations 参数将结果应用于 Amazon Config支持的任何资源类型。该putEvaluationsRequest对象还包括事件的结果标记,用于标识规则和事件 Amazon Config。

  4. putEvaluationsRequest 对象中,处理程序调用 evaluateCompliance 函数。此函数测试适用资源的数量是否超出分配给事件所提供的 maxCount 参数的最大值。如果资源的数量超出最大值,函数将返回 NON_COMPLIANT。如果资源的数量没有超出最大值,函数将返回 COMPLIANT

  5. Amazon Config 通过将对象传递给config客户端putEvaluations的方法,处理程序将评估结果发送到。