ITの隊長のブログ

ITの隊長のブログです。Rubyを使って仕事しています。最近も色々やっているお(^ω^ = ^ω^)

AWS CDKに入門(したい)

スポンサードリンク

aws.amazon.com

チュートリアルがあったのでそこみてやろうとしました。

前提

  • npm入っています
  • Python入っています
  • awscli入っています
  • inline policy作っておきます(今回はstudy-cdkにしました)
  • IAMユーザー作っておいて、aws configureコマンド実行済みです

きれいな手順

install

$ npm install -g aws-cdk
$ cdk --version
$ aws sts get-caller-identity
{
    "UserId": "hogehoge",
    "Account": "fugafuga", # これを使う
    "Arn": "arn:aws:iam::fugafuga:user/study-cdk"
}
$ cdk bootstrap aws://fugafuga/us-west-2

projectの作成

$ mkdir cdk-demo
$ cd cdk-demo
$ cdk init --language typescript

コード書いてdeploy

$ # npm install @aws-cdk/aws-ec2  # 手順にはあったがいらない
$ vim cdk-demo/lib/cdk-demo-stack.ts
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
// import * as sqs from 'aws-cdk-lib/aws-sqs';
import { aws_ec2 as Ec2 } from 'aws-cdk-lib';

export class CdkDemoStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    // The code that defines your stack goes here

    // example resource
    // const queue = new sqs.Queue(this, 'CdkDemoQueue', {
    //   visibilityTimeout: cdk.Duration.seconds(300)
    // });

    // The code that defines your stack goes here
    // CHANGE: We have created the vpc object from the Vpc class.
    const vpc = new Ec2.Vpc(this, 'MainVpc',{

      // CHANGE: this is where we define how many AZs to use
      maxAzs: 2,

      // CHANGE: We define a single subnet configuration per AZ.
      subnetConfiguration:  [
        {
          // CHANGE: this is it's CIDR mask so 255.255.255.0
          cidrMask: 24,

          // CHANGE: a name for each of these subnets
          name: 'public-subnet',

          // CHANGE: and the subnet type to be used - here we will have
          // a public subnet. There are other options available here.
          subnetType: Ec2.SubnetType.PUBLIC
        },
      ]
    });
  }
}
$ cdk deploy
$ cdk destroy  # 掃除

ハマったこと

inline policyを作る必要がある

いっぱいエラーがでたので詰めまくってたら下記が完成した.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "s3:CreateBucket",
                "iam:CreateRole",
                "iam:AttachRolePolicy",
                "cloudformation:CreateChangeSet",
                "iam:PutRolePolicy",
                "ecr:DeleteRepository",
                "cloudformation:DeleteChangeSet",
                "s3:PutEncryptionConfiguration",
                "s3:GetEncryptionConfiguration",
                "iam:PassRole",
                "cloudformation:DescribeStackEvents",
                "iam:DetachRolePolicy",
                "iam:DeleteRolePolicy",
                "ecr:DescribeRepositories",
                "cloudformation:DescribeChangeSet",
                "cloudformation:ExecuteChangeSet",
                "s3:DeleteBucket",
                "s3:PutBucketVersioning",
                "iam:GetRole",
                "s3:PutBucketPublicAccessBlock",
                "ecr:CreateRepository",
                "iam:DeleteRole",
                "s3:DeleteBucketPolicy",
                "cloudformation:DescribeStacks",
                "sts:AssumeRole",
                "cloudformation:GetTemplate",
                "cloudformation:DeleteStack",
                "s3:PutBucketPolicy",
                "ec2:*"
            ],
            "Resource": "*"
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "ssm:PutParameter",
                "ssm:DeleteParameter",
                "ssm:GetParameters",
                "ssm:GetParameter"
            ],
            "Resource": "arn:aws:ssm:*:fugafuga:parameter/*"
        }
    ]
}

最初から推奨するやり方で進めてそいつをコピーすればよかった...

bootstrapの結果が帰ってこない

強制キャンセルして、cloudformationのコンソール画面でstack削除してあげましょう.

と、思ったんだけど、どうやらcloudformation:DeleteStackを与えてあげたら、再実行で削除してくれるっぽい.

が、やっぱりs3バケットは削除してくれないっぽいのでいちいち手動で削除.

自動生成されたs3を削除すると積む

正確にはロールバック等でs3バケットが必要なので、もしcloudformationでstack削除したい場合は、復帰させてあげましょう.

なぜか DELETE_IN_PROGRESS から進まない

焦る.

該当のCloudformationのスタックの詳細画面でリソースをみると、 DELETE_IN_PROGRESS になっているリソースがあったりするので、そいつを削除して再作成するとロールバックが進み終了する.

ちゃんと削除されているか確認してから、再実行すること.

deployでエラー

手順では、ec2のモジュールをインストールしてた.

$ npm install @aws-cdk/aws-ec2
$ cdk deploy
⨯ Unable to compile TypeScript:
lib/cdk-demo-stack.ts:19:25 - error TS2345: Argument of type 'this' is not assignable to parameter of type 'Construct'.
  Type 'CdkDemoStack' is missing the following properties from type 'Construct': onValidate, onPrepare, onSynthesize

19     const vpc = new Vpc(this, 'MainVpc',{
                           ~~~~


Subprocess exited with error 1

ぐぐったら???ってなったが、下記で納得した.

dev.classmethod.jp

$ rm -rf node_modules/
$ vim packages.json  # 追加したec2のモジュールの行削除
$ npm install

ただし、コードの方は↑を参考にしても動かなったので諦めてドキュメントを参照して書いた

権限足りないぞエラー

$ cdk deploy
[Error at /CdkDemoStack] You are not authorized to perform this operation.

Found errors

VPCなので、EC2周りのロールが足りないエラー。脳死でFullAccess(いけない)

current credentials could not be used to assume 'arn:aws:iam::fugafuga:role/cdk-hnb659fds-lookup-role-fugafuga-us-west-2', but are for the right account. Proceeding anyway.

権限が足りない...

stackoverflow.com

雑感

CDKやCloudformationというよりは、IAMでせっせと足りないロールを追加する作業でした。。。茨の道すぎる。とりあえず動いたのは感動。