5
2

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(TypeScript)でリソース毎にファイルを作る

Posted at
$ cdk --version
0.23.0 (build 1d705e7)

やりたいこと

AppSyncなど、いろんなリソースを作る必要がある場合、lib/aws-cdk-stack.tsファイルが冗長になる。
リソース毎に別ファイルで管理して、見通しを良くしたい。

やったこと

こんな感じのクラスを作る。


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

class IAMRole {
  static create(stack: cdk.Stack, name: string) {
    const servicePolicy = new IAM.Policy(
      stack,
      'AppSyncInlinePolicy', {
        policyName: `${name}InlinePolicy`,
        statements: [
          new IAM.PolicyStatement()
            .allow()
            .addActions(
              "dynamodb:GetItem",
              "dynamodb:Query",
              "dynamodb:Scan",
            )
            .addResources(
              "arn:aws:dynamodb:us-east-1:*:table/MyTable"
            )
        ]
      }
    )

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

export default IAMRole

元ファイルでは以下のように呼び出す。


import cdk = require('@aws-cdk/cdk');
import IAMRole from './iam'

export class AwsCdkStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    const serviceRole: IAM.Role = IAMRole.create(stack, id)
  }
}

雑多なこと

クラスにする必要ある?

IAMRole.createって書きたかったからそうした。特に意味はなく、関数にしても良いと思う。


const createIAMRole = (stack: cdk.Stack, name: string): IAM.Role => {
    const servicePolicy = new IAM.Policy(
      stack,
      'AppSyncInlinePolicy', {
        policyName: `${name}InlinePolicy`,
        statements: [
          new IAM.PolicyStatement()
            .allow()
            .addActions(
              "dynamodb:GetItem",
              "dynamodb:Query",
              "dynamodb:Scan",
            )
            .addResources(
              "arn:aws:dynamodb:us-east-1:*:table/MyTable"
            )
        ]
      }
    )

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

このあたりは好みでしょう。

5
2
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
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?