Todos os produtos
Search
Central de documentação

Cloud Config:Crie uma regra personalizada com o Function Compute

Última atualização: Jul 20, 2026

Use uma função do Function Compute para criar uma regra de conformidade personalizada no Cloud Config. Este tópico usa a verificação da quantidade de núcleos de CPU de uma instância ECS como exemplo.

Pré-requisitos

O Function Compute deve estar ativado. Para mais informações, consulte Activate Function Compute.

Nota

O uso do Function Compute gera custos. Para mais informações, consulte Billing overview.

Informações básicas

Para conceitos, casos de uso e princípios de funcionamento das regras personalizadas baseadas em funções, consulte Definition and working principles of custom function rules.

Procedimento

Neste exemplo, uma função verifica a quantidade de núcleos de CPU das instâncias ECS. Instâncias com dois ou menos núcleos de CPU são marcadas como não conformes.

  1. Crie um service.

    1. Faça login no console do Function Compute.

    2. No painel de navegação à esquerda, clique em Services & Functions.

    3. Na barra de navegação superior, selecione uma região, como ou Singapore (Singapore).

    4. Na página Services, clique em Create Service.

    5. No painel Create Service, insira um Name para o service e mantenha os valores padrão dos demais parâmetros.

    6. Clique em OK.

  2. Crie uma função.

    1. No service criado na Etapa 1, clique em Create Function.

    2. Na página Create Function, insira um Function Name. Defina Request Handler Type como Event Handler e Runtime como Python 3.10. Mantenha os valores padrão dos outros parâmetros.

    3. Clique em Create.

  3. Configure o código da função.

    1. Copie o código a seguir e cole-o no arquivo index.py.

      # #!/usr/bin/env python
      # # -*- encoding: utf-8 -*-
      import json
      import logging
      
      from aliyunsdkcore.client import AcsClient
      from aliyunsdkcore.request import CommonRequest
      
      logger = logging.getLogger()
      # Compliance types.
      COMPLIANCE_TYPE_COMPLIANT = 'COMPLIANT'
      COMPLIANCE_TYPE_NON_COMPLIANT = 'NON_COMPLIANT'
      COMPLIANCE_TYPE_NOT_APPLICABLE = 'NOT_APPLICABLE'
      # Resource configuration delivery types.
      CONFIGURATION_TYPE_COMMON = 'COMMON'
      CONFIGURATION_TYPE_OVERSIZE = 'OVERSIZE'
      CONFIGURATION_TYPE_NONE = 'NONE'
      
      # The entry point function that orchestrates and processes business logic.
      def handler(event, context):
          """
          The handler function.
          :param event: The event data.
          :param context: The context object.
          :return: The evaluation results.
          """
          # The input parameters of the function.
          logger.info(f'Printing function input parameters:{event}')
      
          # Validate the event. You can copy this code block directly.
          evt = validate_event(event)
          if not evt:
              return None
          creds = context.credentials
          rule_parameters = evt.get('ruleParameters')
          result_token = evt.get('resultToken')
          invoking_event = evt.get('invokingEvent')
          ordering_timestamp = evt.get('orderingTimestamp')
      
          # The resource configuration. This parameter has a value when the trigger is set to Configuration Change.
          # When you create or manually run a rule, Cloud Config invokes the function to evaluate all specified resources one by one.
          # If the configuration of a resource changes, Cloud Config automatically invokes the function to evaluate the resource based on the change.
          configuration_item = invoking_event.get('configurationItem')
          account_id = configuration_item.get('accountId')
          resource_id = configuration_item.get('resourceId')
          resource_type = configuration_item.get('resourceType')
          region_id = configuration_item.get('regionId')
          resource_name = configuration_item.get('resourceName')
      
          # Check whether the size of the delivered resource configuration exceeds the upper limit (100 KB).
          # If it does, you must call the API for querying resource details to obtain the complete data.
          configuration_type = invoking_event.get('configurationType')
          if configuration_type and configuration_type == CONFIGURATION_TYPE_OVERSIZE:
              resource_result = get_discovered_resource(creds, resource_id, resource_type, region_id)
              resource_json = json.loads(resource_result)
              configuration_item["configuration"] = resource_json["DiscoveredResourceDetail"]["Configuration"]
      
          # Evaluate the resource. You must implement the evaluation logic based on your business requirements. The following code is for reference only.
          compliance_type, annotation = evaluate_configuration_item(
              rule_parameters, configuration_item)
      
          # Set the evaluation results. The format must comply with the following example.
          evaluations = [
              {
                  'accountId': account_id,
                  'complianceResourceId': resource_id,
                  'complianceResourceName': resource_name,
                  'complianceResourceType': resource_type,
                  'complianceRegionId': region_id,
                  'orderingTimestamp': ordering_timestamp,
                  'complianceType': compliance_type,
                  'annotation': annotation
              }
          ]
      
          # Submit the evaluation results to Cloud Config. You can copy this code block directly.
          put_evaluations(creds, result_token, evaluations)
          return evaluations
      
      # Evaluate the number of CPU cores in the ECS instance.
      def evaluate_configuration_item(rule_parameters, configuration_item):
          """
          The evaluation logic.
          :param rule_parameters: The parameters of the rule.
          :param configuration_item: The configuration item.
          :return: The compliance evaluation result.
          """
          # Initialize the return values.
          compliance_type = COMPLIANCE_TYPE_COMPLIANT
          annotation = None
      
          # Obtain the complete configuration of the resource.
          full_configuration = configuration_item['configuration']
          if not full_configuration:
              annotation = 'Configuration is empty.'
              return compliance_type, annotation
      
          # Convert the configuration to the JSON format.
          configuration = parse_json(full_configuration)
          cpu_count = configuration.get('Cpu')
          eq_count = rule_parameters.get('CpuCount')
          if cpu_count and cpu_count <= int(eq_count):
            annotation = json.dumps({"configuration":cpu_count,"desiredValue":eq_count,"operator":"Greater","property":"$.Cpu"})
            compliance_type = COMPLIANCE_TYPE_NON_COMPLIANT
            return compliance_type, annotation
          return compliance_type, annotation
      
      def validate_event(event):
          """
          Validate the event.
          :param event: The event data.
          :return: The JSON object.
          """
          if not event:
              logger.error('Event is empty.')
          evt = parse_json(event)
          logger.info('Loading event: %s .' % json.dumps(evt))
      
          if 'resultToken' not in evt:
              logger.error('ResultToken is empty.')
              return None
          if 'ruleParameters' not in evt:
              logger.error('RuleParameters is empty.')
              return None
          if 'invokingEvent' not in evt:
              logger.error('InvokingEvent is empty.')
              return None
          return evt
      
      def parse_json(content):
          """
          Parse a JSON string.
          :param content: The JSON string.
          :return: The JSON object.
          """
          try:
              return json.loads(content)
          except Exception as e:
              logger.error('Parse content:{} to json error:{}.'.format(content, e))
              return None
      
      # Submit the evaluation results to Cloud Config. You can copy this code block directly.
      def put_evaluations(creds, result_token, evaluations):
          """
          Submits the evaluation results to Cloud Config.
          :param context: The context of Function Compute.
          :param result_token: The callback token.
          :param evaluations: The evaluation results.
          :return: None
          """
          # The Function Compute service role must have the AliyunConfigFullAccess permission.
          client = AcsClient(creds.access_key_id, creds.access_key_secret, region_id='cn-shanghai')
      
          # Create a request and set its parameters. The domain is config.cn-shanghai.aliyuncs.com.
          request = CommonRequest()
          request.set_domain('config.cn-shanghai.aliyuncs.com')
          request.set_version('2020-09-07')
          request.set_action_name('PutEvaluations')
          request.add_body_params('ResultToken', result_token)
          request.add_body_params('Evaluations', evaluations)
          request.add_body_params('SecurityToken', creds.security_token)
          request.set_method('POST')
      
          try:
              response = client.do_action_with_exception(request)
              logger.info('PutEvaluations with request: {}, response: {}.'.format(request, response))
          except Exception as e:
              logger.error('PutEvaluations error: %s' % e)
      Nota

      Este código verifica a quantidade de núcleos de CPU. Para identificar o nome do parâmetro da sua regra, inspecione a configuração do recurso (configuration). Para mais informações, consulte View resource information e Step 6. Por exemplo, na seção Configuration Details de uma instância ECS, clique em View JSON. O parâmetro referente à quantidade de núcleos de CPU é Cpu. Obtenha o valor esperado de CpuCount em rule_parameters.

      A função envia os resultados da avaliação ao chamar a operação de api PutEvaluations. Observe o campo DeleteMode. Se ativado, os resultados de avaliação não atualizados durante a avaliação atual serão excluídos automaticamente.

    2. No canto superior esquerdo, clique em Deploy Code.

  4. Crie uma regra personalizada usando o Function Compute.

    1. Faça login no console do Cloud Config.

    2. Opcional. No canto superior esquerdo, selecione um grupo de contas.

      Esta etapa é necessária apenas se você usar uma conta de gerenciamento de um diretório de recursos. Caso contrário, ignore esta etapa.

    3. No painel de navegação à esquerda, escolha Compliance & Audit > Rules.

    4. Na página Rules, clique em Create Rule.

    5. Na página Select Create Method, selecione Based on Function Compute, escolha o Function ARN e clique em Next.

      Para o Function ARN, defina a Region como ou Singapore (Singapore). Em Service, selecione o service criado na Etapa 1. Em Function, escolha a função criada na Etapa 2.

    6. Na página Set Basic Properties, insira um Rule Name e clique em Add Rule Parameter. Preencha CpuCount nos Rule Parameters e 2 no Expected Value. Em seguida, defina o Trigger como Configuration Changes e clique em Next.

      Nota
      • O nome do parâmetro da regra deve corresponder à chave rule_parameters no código da Etapa 3.

      • Ao criar, modificar ou reavaliar uma regra, o Cloud Config envia as configurações de todos os recursos do tipo especificado ao Function Compute para avaliação.

    7. Na página Set Effective Scope, defina o Resource Type como ECS Instance e clique em Next.

      Nota
      • Para evitar avaliações inválidas, selecione apenas os tipos de recursos que deseja avaliar.

      • A regra avalia todos os recursos do tipo associado na sua conta.

    8. Na página Set Correction, clique em Submit.

      Nota

      Você pode ativar a opção Set Correction e configurar uma correção personalizada. Consulte Set a custom remediation.

  5. Visualize os resultados da detecção.

    A lista de Rules exibe a quantidade de recursos não conformes detectados pela regra.

    Nota

    Clique em um Rule Identifier ou em Details na coluna Actions para visualizar o Compliance Result of Related Resources.

    Se a coluna Non-compliant Resources da regra exibir No Data, mas existirem recursos correspondentes na sua conta, a invocação da função ou o envio da avaliação pode ter falhado. Na aba Invocation Log da função, clique em Request Log na coluna Actions para solucionar o problema. Para mais informações, consulte View invocation logs.

Tópicos relacionados