AWS CDK:将特定的S3资源添加到IAM策略

时间:2020-07-06 01:35:54

标签: amazon-web-services amazon-iam aws-cdk

我想创建一个Lambda函数,其角色可以读取/写入特定的S3存储桶。以下是我编写的代码,但在AWS控制台策略中,该代码未显示存储桶arn,而是显示为s3:::[object Object]我是否缺少某些内容?

const role = new IAM.Role(this, 'MyRole', {
      assumedBy: new IAM.ServicePrincipal('lambda.amazonaws.com'),
      roleName: 'DefaultRoleName'
    });

    role.addToPolicy(new IAM.PolicyStatement({
      resources: [lambda_source.bucketArn],
      actions: ['s3:GetObject', 'lambda:InvokeFunction']
    }));

    // lambda_source.grantReadWrite(role) // I have tried this, and this is also outputs the same result.

    const myLambda = new lambda.Function(this, 'MYLHandler', {
      runtime: lambda.Runtime.NODEJS_12_X,
      code: lambda.Code.fromBucket(lambda_source.bucketName, 'lambda.zip'),
      handler: 'index.handler',
      functionName: 'MyLambda',
      role: role
    });

以下是AWS控制台IAM角色策略文档中的输出:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:GetObject",
                "lambda:InvokeFunction"
            ],
            "Resource": "arn:aws:s3:::[object Object]",
            "Effect": "Allow"
        }
    ]
}

2 个答案:

答案 0 :(得分:1)

user是一个对象,而不是您期望的字符串。打印对象,以查看其实际含义以及是否包含带有ARN的字段。

答案 1 :(得分:0)

您可以import the bucket并授予权限:

const bucket = Bucket.fromBucketAttributes(this, 'ImportedBucket', {
    bucketArn: 'arn:aws:s3:::my-bucket'
});

// now you can just call methods on the bucket
bucket.grantRead(mylambda);