Closed1

OIDC を使って CDK を GitHub Actions でデプロイする

ひやんが / hiyangerひやんが / hiyanger

構築

① IAMロール作成

https://zenn.dev/kou_pg_0131/articles/gh-actions-oidc-aws
https://makky12.hatenablog.com/entry/2023/07/31/120500

  • 信頼ポリシー
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Federated": "arn:aws:iam::<アカウントID>:oidc-provider/token.actions.githubusercontent.com"
            },
            "Action": "sts:AssumeRoleWithWebIdentity",
            "Condition": {
                "StringEquals": {
                    "token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
                },
                "StringLike": {
                    "token.actions.githubusercontent.com:sub": "repo:hiyanger/github-actions-oidc-cdk-serverless:*"
                }
            }
        }
    ]
}
  • IAMポリシー
  {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Statement1",
            "Effect": "Allow",
            "Action": [
                "sts:AssumeRole"
            ],
            "Resource": [
                "arn:aws:iam::<アカウントID>:role/cdk-hnb659fds-deploy-role-<アカウントID>-ap-northeast-1",
                "arn:aws:iam::<アカウントID>:role/cdk-hnb659fds-file-publishing-role-<アカウントID>-ap-northeast-1",
                "arn:aws:iam::<アカウントID>:role/cdk-hnb659fds-image-publishing-role-<アカウントID>-ap-northeast-1",
                "arn:aws:iam::<アカウントID>:role/cdk-hnb659fds-lookup-role-<アカウントID>-ap-northeast-1"
            ]
        }
    ]
}

② CDK 準備

https://zenn.dev/hiyanger/scraps/36978dc46472da

cdk.yml
name: cdk

on:
  push:
    branches:
        - master
  pull_request:
jobs:
  aws_cdk:
    runs-on: ubuntu-latest
    env: 
      AWS_REGION: "ap-northeast-1"
    
    permissions:
      id-token: write
      contents: read

    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Setup dependencies
        run: npm ci

      - name: Assume Role
        uses: aws-actions/configure-aws-credentials@v2
        with:
          role-to-assume: ${{ secrets.AWS_OIDC_ROLE_ARN }} 
          aws-region: ${{ env.AWS_REGION }}
          
      - name: CDK Diff Check
        if: contains(github.event_name, 'pull_request')
        run: npm run cdk:diff

      - name: CDK Deploy
        if: contains(github.event_name, 'push')
        run: npm run cdk:deploy
package.json(scripts 部分)
  "scripts": {
    "build": "tsc",
    "watch": "tsc -w",
    "test": "jest",
    "cdk": "cdk",
    "cdk:diff": "cdk diff",
    "cdk:deploy": "cdk deploy --require-approval never"  
  },

③ GitHub の seacret へ ARN 登録

結果

diff も deploy もできた☺️

このスクラップは2025/01/26にクローズされました