Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive
Help Center/ Config/ Best Practices/ Automating Resource Management

Automating Resource Management

Updated on 2025-01-21 GMT+08:00

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.

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback