简体   繁体   English

使用 AWS CDK 为 lambda 指定自定义角色

[英]Specifying a custom role for lambda with the AWS CDK

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.我意识到它很新,但我没有看到任何语言的示例如何为使用 AWS CDK 创建的 lambda 指定角色。

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.为了尝试为函数指定一个现有的 IAM 角色,但这似乎不是正确的语法。 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.我也可以(或者甚至更喜欢)动态生成特定于该 lambda 的自定义角色,但我也没有看到任何有关如何执行此操作的示例。

Does anyone have any insight on how to accomplish this?有没有人对如何实现这一点有任何见解?

A Lambda already comes with an execution role, and it already has the basic execution permissions. Lambda 已经带有执行角色,并且它已经具有基本的执行权限。 If you want to add additional permissions to the role it has, do something like the following:如果要为其拥有的角色添加其他权限,请执行以下操作:

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

Or better yet, use one of the convenience functions for permissions on some resources:或者更好的是,使用其中一种便利功能来获取某些资源的权限:

bucket.grantRead(lambda.role);

Even though the lambda comes with an IAM role, you can create a custom role for the lambda.即使 lambda 带有 IAM 角色,您也可以为 lambda 创建自定义角色。 You just have to make sure to assign correct minimum required permissions to it.您只需要确保为其分配正确的最低所需权限。

You can create a role like this:您可以创建这样的角色:

    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")
                    ]
                })

If the lambda does not need to be in a VPC you can skip AWSLambdaVPCAccessExecutionRole.如果 lambda 不需要位于 VPC 中,您可以跳过 AWSLambdaVPCAccessExecutionRole。

And to assign this role to the lambda function:并将此角色分配给 lambda 函数:

const lambda = new lambda.Function(this, 'lambda', {
                runtime:....,
                code:...,
                role: customRole,
                handler:....,
                memorySize:...,
                timeout:....,
                vpc:...,
                environment: {
                   ....
                }
            });

The accepted answer by @rix0rrr doesn't work any more. @rix0rrr 接受的答案不再有效。 Seems CDK get some updates.似乎 CDK 得到了一些更新。 Currently version is目前版本是

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

Updated code:更新代码:

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

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

    lambda.addToRolePolicy(statement); 

Bill's answer works, but here's another way:比尔的回答有效,但这是另一种方式:

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

lambda.addToRolePolicy(new iam.PolicyStatement({
  effect: iam.Effect.ALLOW,
  actions: [ 'lambda:InvokeFunction' ],
  resources: [ '*' ]
}));

I came across a similar situation, and found an answer like我遇到了类似的情况,并找到了类似的答案


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)

I didn't managed to add role during lambda creation, but next code gives to lambda access to external role, created in another CDK:我没有在 lambda 创建过程中添加角色,但接下来的代码允许 lambda 访问在另一个 CDK 中创建的外部角色:

lambdaFn.addToRolePolicy(new iam.PolicyStatement({
  effect: iam.Effect.ALLOW,
  actions: [ "sts:AssumeRole" ],
  resources: [externalRoleArn]
}))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM