GitHub ActionsでAWS OIDC Providerを使ってAssumeRoleする設定のCDK版

詳しいことは下記の記事に書いてあってとても助かった。CDK版は探した感じ無かったので自分で書いたので共有。

GitHub Actions OIDCでconfigure-aws-credentialsでAssumeRoleする | DevelopersIO

GitHub Actions が OpenId Connect に対応したので AWS OIDC Provider と連携する - tech.guitarrapc.cóm

import * as cdk from '@aws-cdk/core'
import * as iam from '@aws-cdk/aws-iam'

/**
 * GitHub actionsから呼び出すOIDC providerとiam roleを作成する。
 * https://github.com/aws-actions/configure-aws-credentials#sample-iam-role-cloudformation-template
 */
export class GitHubOIDCStack extends cdk.Stack {
    constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
        super(scope, id, props)

        const gitHubOIDCProvider = new iam.OpenIdConnectProvider(this, 'GitHubOIDCProvider', {
            url: 'https://token.actions.githubusercontent.com',
            clientIds: ['sts.amazonaws.com'],
            thumbprints: ['a031c46782e6e6c662c2c87c76da9aa62ccabd8e']
        });

        const principal = new iam.FederatedPrincipal(gitHubOIDCProvider.openIdConnectProviderArn, {
            "ForAnyValue:StringLike": {
                "token.actions.githubusercontent.com:sub": [
                    `repo:${organization}/${repoName1}:*`,
                    `repo:${organization}/${repoName2}:*`,
                ]
            }
        }, "sts:AssumeRoleWithWebIdentity")

        const iamRole = new iam.Role(this, 'GitHubActionRole', {
            assumedBy: principal,
            managedPolicies: [iam.ManagedPolicy.fromAwsManagedPolicyName("ReadOnlyAccess")],
        })
    }
}