You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CloudFormation中Config规则调用Lambda权限配置失败求助

解决AWS Config规则与Lambda权限的创建顺序冲突问题

这个问题其实是AWS Config和CloudFormation配合时的常见坑——Config规则创建后会立刻发起一次Lambda调用做验证,但这时候你配置的Lambda权限还没创建完成(因为权限依赖于Config规则的Arn,所以创建顺序是先规则后权限),就导致了权限未就绪的报错。

下面是既能保留SourceArn的权限限制,又能解决顺序冲突的方案:

核心思路

先创建禁用状态的Config规则,待Lambda权限完全配置完成后,再通过自定义资源自动启用规则,避免初始验证调用时机与权限创建的冲突。

完整CloudFormation模板示例

Resources:
  # 1. 目标Lambda函数(示例)
  testLambda:
    Type: AWS::Lambda::Function
    Properties:
      Runtime: python3.9
      Handler: index.lambda_handler
      Code:
        ZipFile: |
          import json
          def lambda_handler(event, context):
              # 这里替换为你的Lambda业务逻辑
              return {"status": "success"}
      Role: !GetAtt LambdaExecutionRole.Arn

  # Lambda执行基础角色
  LambdaExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

  # 2. 创建禁用状态的Config规则
  testConfigRule:
    Type: AWS::Config::ConfigRule
    Properties:
      ConfigRuleName: testConfigRule
      ConfigRuleState: DISABLED  # 初始禁用,避免立即触发Lambda调用
      Source:
        Owner: CUSTOM_LAMBDA
        SourceDetails:
          - EventSource: aws.config
            MessageType: ConfigurationItemChangeNotification
        SourceIdentifier: !GetAtt testLambda.Arn

  # 3. Lambda权限:仅允许当前Config规则调用
  lambdaInvokePermission:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName: !GetAtt testLambda.Arn
      SourceArn: !GetAtt testConfigRule.Arn
      Action: lambda:InvokeFunction
      Principal: config.amazonaws.com
    DependsOn: testConfigRule

  # 4. 自定义Lambda:用于启用Config规则
  EnableConfigRuleFunction:
    Type: AWS::Lambda::Function
    Properties:
      Runtime: python3.9
      Handler: index.lambda_handler
      Role: !GetAtt EnableConfigRuleRole.Arn
      Code:
        ZipFile: |
          import boto3
          import cfnresponse

          config_client = boto3.client('config')

          def lambda_handler(event, context):
              try:
                  if event['RequestType'] in ['Create', 'Update']:
                      # 启用目标Config规则
                      config_client.put_config_rule(
                          ConfigRuleName=event['ResourceProperties']['ConfigRuleName'],
                          ConfigRuleState='ENABLED'
                      )
                  cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
              except Exception as e:
                  cfnresponse.send(event, context, cfnresponse.FAILED, {'Error': str(e)})

  # 自定义Lambda的执行角色
  EnableConfigRuleRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      Policies:
        - PolicyName: EnableConfigRulePolicy
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action: config:PutConfigRule
                Resource: !GetAtt testConfigRule.Arn
              - Effect: Allow
                Action:
                  - logs:CreateLogGroup
                  - logs:CreateLogStream
                  - logs:PutLogEvents
                Resource: arn:aws:logs:*:*:*

  # 5. CloudFormation自定义资源:触发启用规则的操作
  EnableConfigRuleResource:
    Type: Custom::EnableConfigRule
    Properties:
      ServiceToken: !GetAtt EnableConfigRuleFunction.Arn
      ConfigRuleName: testConfigRule
    DependsOn: lambdaInvokePermission

关键细节说明

  1. 禁用初始规则状态:通过ConfigRuleState: DISABLED让Config规则创建后不会立即发起Lambda调用,避开权限未就绪的窗口期。
  2. 严格权限限制:Lambda权限的SourceArn依然绑定目标Config规则的Arn,确保只有该规则能调用Lambda,符合你的安全需求。
  3. 依赖顺序控制:自定义资源EnableConfigRuleResource依赖于lambdaInvokePermission,确保只有当权限完全配置完成后,才会启用Config规则,此时规则调用Lambda的权限已经就绪。

调整后的创建流程:
Lambda函数 → 禁用状态的Config规则 → Lambda权限 → 自定义启用规则资源 → 启用Config规则(触发合法调用)

内容的提问来源于stack exchange,提问作者user1951756

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:51:59