20

I realize it's pretty new but I don't see any examples in any language how you would specify a role for the lambda created with the AWS CDK.

I was attempting to do this

const cdk       = require('@aws-cdk/cdk');
const lambda    = require('@aws-cdk/aws-lambda');
const iam       = require('@aws-cdk/aws-iam');

const path      = require('path');

class MyStack extends cdk.Stack {
    constructor (parent, id, props) {
            super(parent, id, props);

            //
            // Create a lambda...
            const fn = new lambda.Function(this, 'MyFunction-cdktest', {
                runtime: lambda.Runtime.NodeJS810,
                handler: 'index.handler',
                code: lambda.Code.directory( path.join( __dirname, 'lambda')),
                role: iam.RoleName('lambda_basic_execution')
            });

    }
}

class MyApp extends cdk.App {
        constructor (argv) {
                super(argv);

                new MyStack(this, 'hello-cdk');
        }
}

console.log(new MyApp(process.argv).run());

in order to try and specify an existing IAM role for the function but that doesn't seem to be correct syntax. I also would be ok with ( or maybe even prefer ) to generate the custom role on the fly specific to this lambda but I didn't see any examples on how to do that either.

Does anyone have any insight on how to accomplish this?

4

6 回答 6

26

一个 Lambda 已经带有一个执行角色,并且它已经拥有了基本的执行权限。如果要为其拥有的角色添加其他权限,请执行以下操作:

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

lambda.addToRolePolicy(new iam.PolicyStatement()
   .addResource('arn:aws:....')
   .addAction('s3:GetThing'));

或者更好的是,使用便利功能之一来获取某些资源的权限:

bucket.grantRead(lambda.role);
于 2018-10-04T19:29:16.567 回答
16

即使 lambda 附带 IAM 角色,您也可以为 lambda 创建自定义角色。您只需确保为其分配正确的最低要求权限。

您可以像这样创建角色:

    const customRole = new Role(this, 'customRole', {
                    roleName: 'customRole',
                    assumedBy: new ServicePrincipal('lambda.amazonaws.com'),
                    managedPolicies: [
                        ManagedPolicy.fromAwsManagedPolicyName("service-role/AWSLambdaVPCAccessExecutionRole"),
                        ManagedPolicy.fromAwsManagedPolicyName("service-role/AWSLambdaBasicExecutionRole")
                    ]
                })

如果 lambda 不需要位于 VPC 中,您可以跳过 AWSLambdaVPCAccessExecutionRole。

并将此角色分配给 lambda 函数:

const lambda = new lambda.Function(this, 'lambda', {
                runtime:....,
                code:...,
                role: customRole,
                handler:....,
                memorySize:...,
                timeout:....,
                vpc:...,
                environment: {
                   ....
                }
            });
于 2020-05-15T22:04:10.643 回答
13

@rix0rrr 接受的答案不再起作用。似乎 CDK 得到了一些更新。当前版本是

"@aws-cdk/core": "^1.1.0"

更新代码:

    import iam = require("@aws-cdk/aws-iam");

    const statement = new iam.PolicyStatement();
    statement.addActions("lambda:InvokeFunction");
    statement.addResources("*");

    lambda.addToRolePolicy(statement); 
于 2019-07-24T13:46:19.803 回答
11

比尔的回答有效,但这是另一种方式:

import iam = require("@aws-cdk/aws-iam");

lambda.addToRolePolicy(new iam.PolicyStatement({
  effect: iam.Effect.ALLOW,
  actions: [ 'lambda:InvokeFunction' ],
  resources: [ '*' ]
}));
于 2019-08-29T02:54:15.563 回答
3

我遇到了类似的情况,并找到了类似的答案


import * as lambda from '@aws-cdk/aws-lambda';

import iam = require("@aws-cdk/aws-iam");

      // define lambda fucntion
        const lambdaFunction = new lambda.Function(this, 'my-lambda', {
            code: this.lambdaCode,
            functionName: 'athena-gateway',
            handler: 'index.handler',
            runtime: lambda.Runtime.NODEJS_12_X,
            timeout: Duration.minutes(14)
        });

        // provide athena,s3 access to lambda function
        const athenaAccessPolicy = new iam.PolicyStatement({
            effect: iam.Effect.ALLOW,
            actions: [
                "s3:*",
                "athena:*"                            ]

        });
        athenaAccessPolicy.addAllResources();
        lambdaFunction.addToRolePolicy(athenaAccessPolicy)

于 2020-07-28T10:27:34.480 回答
0

在创建 lambda 时我没有设法添加角色,但接下来的代码让 lambda 可以访问在另一个 CDK 中创建的外部角色:

lambdaFn.addToRolePolicy(new iam.PolicyStatement({
  effect: iam.Effect.ALLOW,
  actions: [ "sts:AssumeRole" ],
  resources: [externalRoleArn]
}))
于 2021-03-21T21:13:51.660 回答