Help Center/ Config/ Best Practices/ Automating Resource Management
Updated on 2025-01-21 GMT+08:00

Automating Resource Management

In this section, you will learn how to automate the detection and remediation of noncompliant resources with Config rules and the remediation function. This ensures that noncompliant resources whether resulting from intended or unintended actions can be remediated within minutes, enhancing resource security.

Applicable Scenario

Scenario: You can configure OBS bucket policies to block HTTP access to your buckets. For details Keeping Data in Transit Safe

Procedure

Create a rule.

  1. Log in to the Config Console.
  2. In the navigation pane on the left, choose Resource Compliance.
  3. On the Rules tab, click Add Rule.
  4. On the Basic Configurations page, select obs-bucket-ssl-requests-only in the Built-in Policy area, and click Next.
  5. On the Configure Rule Parameters page, remain the default settings for Resource Scope and select All for Region. Click Next to confirm the configurations and click Submit
  6. Return to the Rules tab to view evaluation results.

Configure mediation.

The following procedure shows how to use a FunctionGraph function to configure remediation. Python is used.

  1. Log in to the FunctionGraph console.
  2. In the navigation pane on the left, click Functions > Function List.
  3. On the Functions tab, click Create Function.
  4. Select Event Function for Function Type, select an agency, and select Python 3.9 for Runtime. The agency selected must contain at least the following permissions:
{
    "Version": "1.1",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "obs:bucket:PutBucketPolicy",
                "obs:bucket:GetBucketPolicy",
                "rms:resources:get"
            ]
        }
    ]
}
  1. After the function is created, add the two dependencies: huaweicloudsdk_obs and huaweicloudsdkconfig, to the function.

  2. Add the following code to index.py:
    import json
    
    from obs.client import ObsClient
    from huaweicloudsdkcore.auth.credentials import GlobalCredentials
    from huaweicloudsdkconfig.v1.region.config_region import ConfigRegion 
    from huaweicloudsdkconfig.v1.config_client import ConfigClient 
    from huaweicloudsdkconfig.v1 import ShowResourceDetailRequest 
    
    def get_resource_region(context, domain_id, resource_id):
        auth = GlobalCredentials(
            ak=context.getSecurityAccessKey(),
            sk=context.getSecuritySecretKey(),
            domain_id=domain_id
        ).with_security_token(context.getSecurityToken())
        client = ConfigClient.new_builder() \
            .with_credentials(credentials=auth) \
            .with_region(region=ConfigRegion.value_of(region_id="cn-north-4")) \
            .build()
        resource = client.show_resource_detail(ShowResourceDetailRequest(resource_id)).to_json_object()
        return resource.get("region_id")
    
    def getBucketPolicy(obsClient, bucket_name):
        resp = obsClient.getBucketPolicy(bucket_name)
        if resp.status < 300:
            print("Get Bucket Policy Succeeded")
            return resp.body.policyJSON
        if resp.status == 404 and resp.errorCode == "NoSuchBucketPolicy":
            print("NoSuchBucketPolicy")
            return "{\"Statement\": []}"
        assert False, f"Get Bucket Policy Failed: {resp.errorCode} | {resp.errorMessage}"
    
    def ensurePolicySSL(obsClient, bucket_name, policy):
        policy["Statement"] = policy["Statement"] + [{
            "Sid": "ensure_secure_transport",
            "Effect": "Deny",
            "Principal": {"ID": ["*"]},
            "Action": ["*"],
            "Resource": [bucket_name, bucket_name + "/*"],
            "Condition": {"Bool": {"g:SecureTransport": ["false"]}}
        }]
        resp = obsClient.setBucketPolicy(bucket_name, policy)
        if resp.status < 300:
            print("Set Bucket Policy Succeeded")
        else:
            print(policy)
            assert False, f"Set Bucket Policy Failed: {resp.errorCode} | {resp.errorMessage}"
    
    def handler(event, context):
        domain_id = event.get("domain_id")
        bucket_name = event.get("bucket_name")
        print("domain_id", domain_id)
        print("bucket_name", bucket_name)
    
        region_id = get_resource_region(context, domain_id, bucket_name)
        print("region_id", region_id)
    
        server = f"https://obs.{region_id}.myhuaweicloud.com"
        obsClient = ObsClient(
            access_key_id=context.getSecurityAccessKey(),
            secret_access_key=context.getSecuritySecretKey(),
            server=server,
            security_token=context.getSecurityToken()
        )
        policy = getBucketPolicy(obsClient, bucket_name)
        policy = json.loads(policy)
        ensurePolicySSL(obsClient, bucket_name, policy)
        obsClient.close()
  3. (Optional) Modify basic settings: Memory (MB) and Execution Timeout (s), and configure Log for the function. You are recommended to complete this step to ensure smooth resource remediation and enable logging in case of any errors that may occur.

Configuring Remediation

  1. Log in to the Config Console.
  2. In the navigation pane on the left, choose Resource Compliance.
  3. On the Rules tab, click the name of the rule.
  4. Click Remediation Management and click Remediation Configuration.
  5. Select Automatic or Manual for Method and remain the default settings for Retry Time Limit and Retries.
  6. Select FGS Template and select the function configured in the previous step.
  7. Set Dependent Resource Type to bucket_name and set the key of Parameter to domain_id and the value to the account ID.
  8. Click Save.

Manually Remediating Resources

The following procedure shows how to manually configure remediation:

  1. Go to the Remediation Management page.
  2. On the Resource Scope tab, select target resources.
    • If you need to remediate the resources selected, click Execute Remediation.
    • If you do not need to remediate the resources, click Add to Remediation Exception.
  3. Log in to the OBS console and go to the details page of the OBS bucket.
  4. Check if the bucket policy has been modified.

FAQs

What Are the Differences Between Manual Remediation and Automatic Remediation?

Manual remediation requires you to manually search for and remediate noncompliant resources. Automatic remediation automatically applies remediation to noncompliant resources detected by a rule.

You are recommended to select manual remediation if it is the first time you configure remediation. Manual remediation can prevent service interruptions caused by resource modifications.

If you change manual remediation to automatic, all noncompliant resources detected after the change will be automatically remediated.

Why Does a Resource Fail to Be Remediated After the Remediation Is Applied?

This is typically caused by incorrect code in the FunctionGraph function or insufficient permissions of FunctionGraph. You can check the reasons by looking at the logs.

Why Is a Resource Still Noncompliant After the Remediation Is Applied?

Typically, a resource modification is reported to Config within 5 minutes of when the resource is modified, and the rule will be automatically triggered to generate the latest evaluation results.