如何使用 aws CDK 授予 particular/full 对 Elastic beanstalk 的访问权限?

How to give particular/full access to Elastic beanstalk using aws CDK?

我已经创建了 aws 管道以使用 CDK typescript 代码将我的 dot net 框架应用程序部署到 elastic beanstalk。

但在部署步骤中失败并出现以下错误

Insufficient permissions The provided role does not have the elasticbeanstalk:CreateApplicationVersion permission

我不确定如何使用 aws cdk 分配权限。

我应该如何在下面的代码中添加权限

下面是我的部署阶段代码


const appName = "SampleDotNetMVCWebApp";
const newRole = new iam.Role(this, "Role", {
  assumedBy: new iam.ServicePrincipal("elasticbeanstalk.amazonaws.com")
});

newRole.addToPolicy(
  new iam.PolicyStatement({
    resources: ["*"],
    actions: ["elasticbeanstalk:CreateApplicationVersion"]
  })
);

const app = new elasticbeanstalk.CfnApplication(this, "EBApplication", {
  applicationName: appName
});

const elbEnv = new elasticbeanstalk.CfnEnvironment(this, "Environment", {
  environmentName: "SampleMVCEBEnvironment",
  applicationName: appName,
  platformArn: platform,
  solutionStackName: "64bit Windows Server 2012 R2 v2.5.0 running IIS 8.5"
});

pipeline.addStage({
  stageName: "Deploy",
  actions: [   
    new ElasticBeanStalkDeployAction({
      actionName: "DeployToEB",
      applicationName: appName,
      environmentName: "SampleMVCEBEnvironment",
      input: cdkBuildOutput,
      role: newRole
    })
  ]
});

注意:在上面的代码中,aws 管道操作 "ElasticBeanStalkDeployAction" 是自定义操作,因为 aws cdk 尚未发布此部署到 eb 操作功能。 您可以在此处查看问题和实施 IAction 的代码 https://github.com/aws/aws-cdk/issues/2516

您需要为 ElasticBeanStalkDeployAction 添加权限才能创建 CreateApplicationVersion,使用 .addToPolicy

These policies will be created with the role, whereas those added by addToPolicy are added using a separate CloudFormation resource (allowing a way around circular dependencies that could otherwise be introduced).

   const elasticBeanStalkDeployAction =  new ElasticBeanStalkDeployAction({
      actionName: 'DeployToEB',
      applicationName: appName,
      environmentName: 'SampleMVCEBEnvironment',
      input: cdkBuildOutput 
    })


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

稍后,使用您创建的对象并将其传递到操作中:

pipeline.addStage({
  stageName: 'Deploy',
actions: [elasticBeanStalkDeployAction]
});

或者按照此处的建议 - https://github.com/aws/aws-cdk/issues/2516

这个问题可以通过在 ElasticBeanStalkDeployAction

的绑定方法中添加策略来解决
public bind(scope: Construct, stage: codepipeline.IStage, options: codepipeline.ActionBindOptions):
      codepipeline.ActionConfig {
    options.role.addManagedPolicy(
        iam.ManagedPolicy.fromAwsManagedPolicyName(
          "AWSElasticBeanstalkFullAccess"
        ));
  }