When you create a rule, configure a custom remediation using Function Compute to fix resources identified as Non-compliant.
Prerequisites
Background
This topic uses the ecs-running-instance-no-public-ip managed rule as an example to configure and run a custom remediation.
The ecs-running-instance-no-public-ip managed rule identifies running ECS instances with a public IPv4 address as non-compliant. The remediation then stops these instances.
Procedure
Log on to the Cloud Config console.
Optional. In the upper-left corner, select an account group.
This operation is required only if you are using a management account of a resource directory. Otherwise, you do not need to perform the operation.
In the left-side navigation pane, choose .
-
On the Rules page, click Create Rule.
-
On the Select Create Method page, select Based on managed rule, select the ecs-running-instance-no-public-ip rule from the templates, and then click Next.
-
On the Set Basic Properties page, keep the default parameter settings and click Next.
-
On the Set Effective Scope page, keep the default parameter settings and click Next.
-
On the Set Correction page, turn on the Set Correction switch, select Function Compute, set Invoke Type to Manual Remediation, select a Function ARN, and then click Submit.
Important-
Automatic remediation modifies non-compliant resources based on your preset parameters, which can disrupt your business operations. Therefore, Invoke Type is set to Manual Remediation by default. We recommend keeping this setting.
-
If you are sure that the remediation will not impact your business, you can set Invoke Type to Automatic Remediation. When Cloud Config detects a non-compliant resource, it automatically executes the remediation.
Click Create New Function to create a service and a function in the Function Compute console. Quickly create a function.
When you create the function, set Function Type to Event Function and runtime to python 3. Configure other parameters as needed. Example code:
#!/usr/bin/env python # -*- encoding: utf-8 -*- import json from aliyunsdkcore.client import AcsClient from aliyunsdkcore.acs_exception.exceptions import ClientException from aliyunsdkcore.acs_exception.exceptions import ServerException from aliyunsdkcore.auth.credentials import AccessKeyCredential from aliyunsdkcore.auth.credentials import StsTokenCredential from aliyunsdkecs.request.v20140526.StopInstanceRequest import StopInstanceRequest from aliyunsdkcore.auth.credentials import AccessKeyCredential from aliyunsdkcore.auth.credentials import StsTokenCredential from aliyunsdkkms.request.v20160120.DecryptRequest import DecryptRequest # -*- coding: utf-8 -*- import logging import json logger = logging.getLogger() def handler(event, context): get_resources_non_compliant(event, context) def get_resources_non_compliant(event, context): resources = parse_json(event) for resource in resources: remediation(resource, context) def parse_json(content): """ Parses a string into a JSON object :param content: json string content :return: Json object """ try: return json.loads(content) except Exception as e: logger.error('Parse content:{} to json error:{}.'.format(content, e)) return None def remediation(resource, context): logger.info(resource) region_id = resource['regionId'] account_id = resource['accountId'] resource_id = resource['resourceId'] resource_type = resource['resourceType'] config_rule_id = resource['configRuleId'] if resource_type == 'ACS::ECS::Instance' and config_rule_id == 'cr-f8a1626622af005d****': print(region_id, account_id, resource_id, resource_type, config_rule_id) stop_ecs_instance(context, region_id, resource_id) def stop_ecs_instance(context, resource_region_id, resource_id): logger.info("Stopping instance {}{}".format(resource_region_id, resource_id)) creds = context.credentials client = AcsClient(creds.access_key_id, creds.access_key_secret, region_id=resource_region_id) request = StopInstanceRequest() request.set_accept_format('json') request.set_InstanceId("i-hp3f6lofgrnml5mt****") request.set_StoppedMode("KeepCharging") request.add_query_param('SecurityToken', creds.security_token) response = client.do_action_with_exception(request) logger.info(response)NoteLatest sample code: aliyun-config-remediation.py.
Key functions:
-
handler: Default entry point called when Cloud Config triggers a remediation. The
handleris set when you create the function. -
get_resources_non_compliant: Parses non-compliant resources. -
remediation: Entry point for custom remediation logic. Configure based on your compliance requirements. For the "ecs-running-instance-no-public-ip" rule, this function stops instances that have a public IP address.
-
-
Run the remediation manually.
-
On the Rules page, find the target rule and click Remediation Detail in the Remediation Template column.
-
On the Remediation Detail tab, click Perform Manual Correction next to Remediation Detail.
The Execution Result List section shows remediation results and failure reasons.
NoteOn the Remediation Detail tab, click the Function ARN next to Remediation Template to open the Function Code tab in the Function Compute console.
-
Related documents
For function code and permission configurations in multi-account environments, Implement custom remediation for non-compliant resources in a multi-account environment by using Resource Directory.