4
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AWS CDKでIAMのインラインポリシーとサービスロールを作る

Posted at

AppSyncのDataSourceを作るのにサービスロールが必要だったので、覚書。

$ cdk --version
0.23.0 (build 1d705e7)

IAMパッケージ

$ @aws-cdk/aws-iam@0.23.0

ポリシー

だいたいこんな感じになる。
ステートメントをメソッドチェーンでビルダー的に書けるので、この書き方に慣れさえすれば普通に書くより楽かもしれない。

import cdk = require('@aws-cdk/cdk');
import IAM = require('@aws-cdk/aws-iam')
const app = new cdk.App();
const stack = new cdk.Stack(app, 'TestStack');

const statement = new IAM.PolicyStatement()
        .allow()
        .addActions(
          "dynamodb:GetItem",
          "dynamodb:Query",
        )
        .addResources(
          "*"
        )

const servicePolicy = new IAM.Policy(
  stack,
  'AppSyncInlinePolicy', {
    policyName: 'AppSyncInlinePolicy',
    statements: [statement]
  }
)

ロール

さっきのポリシーインスタンスをそのまま放り込んでやればOK。

const serviceRole = new IAM.Role(stack, 'AppSyncDynamoDBRole', {
  assumedBy: new IAM.ServicePrincipal('appsync.amazonaws.com'),
  path: '/service-role/'
})
serviceRole.attachInlinePolicy(servicePolicy)

出力

Resources:
  AppSyncInlinePolicyED30ADB5:
    Type: AWS::IAM::Policy
    Properties:
      PolicyDocument:
        Statement:
          - Action:
              - dynamodb:GetItem
              - dynamodb:Query
            Effect: Allow
            Resource: "*"
        Version: "2012-10-17"
      PolicyName: AppSyncInlinePolicy
      Roles:
        - Ref: AppSyncDynamoDBRoleBDD57878
    Metadata:
      aws:cdk:path: TestStack/AppSyncInlinePolicy/Resource
  AppSyncDynamoDBRoleBDD57878:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Action: sts:AssumeRole
            Effect: Allow
            Principal:
              Service: appsync.amazonaws.com
        Version: "2012-10-17"
      Path: /service-role/
    Metadata:
      aws:cdk:path: TestStack/AppSyncDynamoDBRole/Resource
  CDKMetadata:
    Type: AWS::CDK::Metadata
    Properties:
      Modules: aws-cdk=0.23.0,@aws-cdk/aws-iam=0.23.0,@aws-cdk/cdk=0.23.0,@aws-cdk/cx-api=0.23.0,jsii-runtime=node.js/v10.5.0

感想

とにかくCloudFormationのプロパティをJSのクラスメソッドで書くのが違和感すごい。
ただしIDEの入力補完や型参照を活かしながら書けば、普通にYAML書くよりコード量が減って楽です。

なお破壊的変更でぶっ壊れることがあるみたいですが、最悪cdk synthでCloudFormationにアウトプットしてCDK使うのやめればいいと思うと気楽ではある。

4
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?