An official English-language version of the documentation is not available. For your convenience only, we have introduced the use of machine-translation software capable of producing rough translations in various languages, including English.This machine-translated version of the documentation was produced using only machine-translation software and without any human intervention. We are making continuous efforts to improve the machine-translation software. HOWEVER, MACHINE TRANSLATIONS MAY CONTAIN ERRORS. ANY RELIANCE BY YOU UPON THIS MACHINE TRANSLATION IS SOLELY AT YOUR OWN RISK, AND ALIBABA CLOUD SHALL NOT BE LIABLE TO YOU OR ANY OTHER PARTIES FOR ANY ADVERSE CONSEQUENCES (DIRECT, INDIRECT, CONSEQUENTIAL OR OTHERWISE) ARISING FROM OR IN CONNECTION WITH THE DOCUMENTATION OR ANY TRANSLATIONS THEREOF.

To request a human-translated version of this article or to comment on the quality of machine translation, please use the "More suggestions" text area in the feedback form below to submit feedback.

Configure the audit service to provide you with dozens of preset rules. For more information, see List of preset rules. You can also customize rules.

A custom rule runs in the same way as a predefined rule. The only difference is that the system preset rule is that the audit service has already built the rule function in function compute, you can directly select the function to be used in the configuration audit console. However, to customize rules, you must define rules in function compute in advance, you need to enter the ARN of the rule function in the configuration audit console.

With custom rules, you can better support personalized compliance scenarios.

Create a custom rule

There are two steps. The first step is to create a function in function compute. The second step is to create a rule in configure audit service, just like preset rules. This article focuses on step 1. For step 2, see Create a rule.

To create a custom rule, you must first create a function in the function compute console. Currently, function compute supports the following programming languages: Java8, Nodejs6, Nodejs8, Python2.7, Python3, PHP7.2, and dotnetcore2.1. Java 8 and dotnetcore support code package Upload (including oss upload). Other languages support code package Upload and online editing. For more information about function compute, see Function Compute.

The following example shows how to customize a rule.

  • Rule scenario: evaluate whether an ECS instance is started by a specific image
  • Function languages use Python3

Create a rule function in function compute and reference it in configuration audit.

For more information about how to create function compute, see Function Compute.

  • After a rule function is created in function compute, an ARN function is automatically generated. The function ARN can be viewed on the overview page of the created function compute.
  • To reference the rule function in the configure audit service console, enter the ARN in the preceding figure.

Rule Function Code construction

The essence of a rule is a piece of logic judgment code, which is placed in the rule function you just created. In an actual continuous audit, the rule function is triggered to make an assessment.

  • The following is the sample code of the rule. The code of this function mainly consists of two functions. handler is the entry function, that is, the function called When custom compliance is triggered. The hander must be configured when the function is being built.
  • The other function is put_evaluations, which is called in the handler and returns the compliance result.
#! /usr/bin/env python
# -*- coding: utf-8 -*-
@ File: index. py
@ Time: 18:19:00
@ Author: wb510457
# Version: 1.0
@ License: (C) Copyright 2017-2018, Alibaba inc.
@ Desc: None

# Put the import lib here
import logging
import json
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkcore.request import CommonRequest

root = logging.getLogger()

# Function handler
Def handler (event, context ):
    Processing functions
    : Param event: event
    : Param context: context
    : Return: assessment result
    # Event data format conversion
    Evt = json. loads (event)
    If not evt:
        return None

   # Input parameters
    Rule_parameters = evt. get ('ruleparameters ')
    # Input parameter -- image instance id
    Image_id = rule_parameters.get (imageIds)
    # Callback in function compute
    Result_token = evt. get ('resulttoken ')
    # Function execution parameter information
    Blocking_event = evt. get ('blockingevent ')

    # Initialize the return value.
    Compilance_type = 'not _ applicable'
    Annotation = None

    # Obtain configuration items
    Operation_item = updateking_event.get ('operationitem ')
    If not operation_item:
        Logger. error ('configuration item is empty .')
        return None
    # Assessment
    If image_id in configuration_item
      Compilance_type = 'compute'
    If not image_id in configuration_item
      Compilance_type = 'non _ compute'
   # Start time of command execution
    Ordering_timestamp = operation_item.get ('capturetime ')
    # Resource id
    Instance_id = destination_item.get ('instanceid ')
    # Resource type
    Instance_type = destination_item.get ('instancetype ')

    # Evaluation results
    Evicted = [
            'Compilanceresourceid': instance_id,
            'Compilanceresourcetype ': instance_type,
            'Orderingtimestamp': ordering_timestamp,
            'Compilancetype': compilance_type,
            'Annotation': annotation

    # Write back the evaluation result-write the evaluation result data
    Put_evaluators (context, result_token, evaluators)
    Return evisibility
# Write back the evaluation result-write the evaluation result data
Def put_evaluations (context, result_token, evaluations ):
    Callback Config Open API write back Evaluation Results
    : Param context: function compute context
    : Param result_token: the callback token.
    : Param evisibility: evaluation result
    : Return: None
    # Create an AcsClient instance
    client = AcsClient(
        Context. credentials. access_key_id,
        Context. credentials. access_key_secret,
        Context. region,

    # Create a request, and set required parameters.
    request = CommonRequest()
    Request. set_domain ('config domain ')
    Request. set_action_name ('putevalue ')
    Request. add_body_params ('resulttoken', result_token)
    Request. add_body_params ('evaluate', evaluate)
    Request. set_method ('post ')

        response = client.do_action_with_exception(request)
        Logger.info ('putevaluedwith request: % s, response: % s' %
                    (Request, response ))
    except Exception as e:
        Logger. error ('putevaluederror: % s' % e)

Input parameters of a rule function

Event parameter. The input parameter information entered in the rule function is saved in the rule parameters, and other content is the event information automatically generated when the rule is triggered. The JSON format is as follows:

    version: "version ",
    orderingTimestamp: "command execution start time ",
      messageType: "Message Type ",
          "accountId": "User ID ",
            "arn": "resource ARN ",
            "availabilityzone": "Available zone ",
            "regionId": "region id ",
            "configuration": "configuration information of resources in string format, which varies with resources ",
            "configurationDiff": "configuration change content ",
            "relationship": "relationship ",
            "relationshipDiff": "Relationship content change ",
            "captureTime": "capture time ",
            "resourceCreationTime": "resource creation time ",
            "resourceStatus": "resource status ",
            "resourceId": "resource ID ",
      "resourceName": "Resource Name ",
            "resourceType": "c4",
            "supplementaryConfiguration": "supplemental configuration ",
            "tags": "tags"
        notificationCreationTimestamp: "event message generation time"
    resultToken: "callback information of the user in function compute" 

Context parameter. The context information, which is automatically included when the rule is triggered.

  • context.credentials.access_key_id: "accessKey value"
  • context.credentials. access_key_secret: "accessSecret value"
  • context.region:"region information"

After creating a custom rule in function compute, you can copy the ARN of the function and create the rule again after configuring the audit service.