CloudFormation 删除更新堆栈操作上的 AWS Cognito Lambda 触发器

问题描述

我注意到,每当部署新的 CloudFormation 堆栈更改时,我的用户池触发器都会被删除,并且必须在 AWS 仪表板中手动重新添加或以编程方式重新添加。这有点令人担忧,因为这些触发器通过 Cognito 和后端系统之间的通信执行一些关键操作。

起初我认为这是我们正在使用的部署框架,但这里是一个 CF 模板的准系统示例,我可以复制它:

更新以反映用户池的 Lambda 附件

{
  "AWstemplateFormatVersion": "2010-09-09","Resources": {
    "UserPool": {
      "Type": "AWS::Cognito::UserPool","Properties": {
        "UserPoolName": "test","UsernameAttributes": [
          "email"
        ],"EmailVerificationMessage": "Your verification code is {####}.","EmailVerificationSubject": "Your verification code","Policies": {
          "PasswordPolicy": {
            "MinimumLength": 8,"RequireLowercase": true,"RequireNumbers": true
          }
        }
      }
    },"UserPoolClient": {
      "Type": "AWS::Cognito::UserPoolClient","Properties": {
        "ClientName": "Test Client","UserPoolId": {
          "Ref": "UserPool"
        },"ExplicitAuthFlows": [
          "ALLOW_REFRESH_TOKEN_AUTH","ALLOW_USER_PASSWORD_AUTH","ALLOW_USER_SRP_AUTH"
        ],"GenerateSecret": false
      }
    },"PreSignUpHandlerLambdaFunction": {
      "Type": "AWS::Lambda::Function","Properties": {
        "Role": "arn:aws:iam::...","Code": {
          "S3Bucket": "code-bucket","S3Key": "code-bucket/functions.zip"
        },"Handler": "handlers/pre-sign-up.default","Runtime": "nodejs12.x","FunctionName": "test-preSignUpHandler","MemorySize": 1024,"Timeout": 6
      }
    },"PreSignUpHandlerCustomCognitoUserPool1": {
      "Type": "Custom::CognitoUserPool","Version": 1,"DependsOn": [
        "PreSignUpHandlerLambdaFunction"
      ],"Properties": {
        "Servicetoken": "arn:aws:lambda:...","UserPoolName": "test","UserPoolConfigs": [
          {
            "Trigger": "PreSignUp"
          }
        ]
      }
    }
  }
}

我已经深入研究了更新生成的 CloudWatch 日志,但关于用户池更新和触发器的删除,没有任何事情是透明的。 有没有其他人遇到过这种情况,是否有任何解决方法

解决方法

这是 CloudFormation 的预期行为。当在堆栈更新时检测到配置漂移时,它会将其恢复到与您的堆栈模板一致的状态。如果要保留更改,则应在 CFN 模板中指定触发器。请务必在资源政策中授予认知访问权限:

{
    "Version": "2012-10-17","Id": "default","Statement": [
        {
            "Sid": "lambda-allow-cognito-my-function","Effect": "Allow","Principal": {
              "Service": "cognito-idp.amazonaws.com"
            },"Action": "lambda:InvokeFunction","Resource":  "arn:aws:lambda:us-east-1:123456789012:function:my-function","Condition": {
              "StringEquals": {
                "AWS:SourceAccount": "123456789012"
              },"ArnLike": {
                "AWS:SourceArn": "arn:aws:cognito-idp:us-east-1:123456789012:userpool/us-east-1_myUserPoolId"
              }
            }
        }
     ]
}