CDK 向自定义创建的 SES 验证电子邮件添加策略

问题描述

使用 AWS 开发工具包,我可以创建一个经过 SES 验证的电子邮件地址。但是我如何创建一个策略来为电子邮件提供 SendEmail 和 SendRawEmail 权限(就像在控制台中一样)?我的理解是 AwsCustomresource 策略属性授予 Lambda 函数创建资源的权限,而不是创建的资源本身。

enter image description here

const customresource = new cr.AwsCustomresource(this,'VerifyEmailIdentity',{
    onCreate: {
        service: 'SES',action: 'verifyEmailIdentity',parameters: {
            EmailAddress: cognitoEmailAddress,},physicalResourceId: cr.PhysicalResourceId.of(`verify-${cognitoEmailAddress}`)
    },onDelete: {
        service: 'SES',action: 'deleteIdentity',parameters: {
            Identity: cognitoEmailAddress
        }
    },policy: cr.AwsCustomresourcePolicy.fromStatements([
        new iam.PolicyStatement({
            effect: iam.Effect.ALLOW,actions: ['ses:VerifyEmailIdentity','ses:DeleteIdentity'],resources: ['*']
        })
    ])
});

解决方法

添加以下附加代码,该代码调用 SES putIdentityPolicy,允许(例如)将 Cognito 服务发送到 SendEmail 和 SendRawEmail。

import * as cr from '@aws-cdk/custom-resources';
import * as iam from '@aws-cdk/aws-iam';

const cognitoEmailAddress = 'myemail@mydomain.com';
const cognitoEmailAddressArn = `arn:aws:ses:${myRegion}:${myAccount}:identity/${cognitoEmailAddress}`;

const policy = {
    Version: '2008-10-17',Statement: [
        {
            Sid: 'stmt1621717794524',Effect: 'Allow',Principal: {
                Service: 'cognito-idp.amazonaws.com'
            },Action: [
                'ses:SendEmail','ses:SendRawEmail'
            ],Resource: cognitoEmailAddressArn
        }
    ]
};

new cr.AwsCustomResource(this,'PutIdentityPolicy',{
    onCreate: {
        service: 'SES',action: 'putIdentityPolicy',parameters: {
            Identity: cognitoEmailAddress,Policy: JSON.stringify(policy),PolicyName: 'CognitoSESEmail'
        },physicalResourceId: cr.PhysicalResourceId.of(`policy-${cognitoEmailAddress}`)
    },onDelete: {
        service: 'SES',action: 'deleteIdentityPolicy',PolicyName: 'CognitoSESEmail'
        }
    },// There is a policy bug in the CDK for custom resources: https://github.com/aws/aws-cdk/issues/4533
    // Use the following policy workaround. https://stackoverflow.com/questions/65886628/verify-ses-email-address-through-cdk
    policy: cr.AwsCustomResourcePolicy.fromStatements([
        new iam.PolicyStatement({
            effect: iam.Effect.ALLOW,actions: ['ses:PutIdentityPolicy','ses:DeleteIdentityPolicy'],resources: ['*']
        })
    ])
});