TerraformでGitHub ActionsのOIDC連携用のIAM Roleを作成する

概要

GitHub Actionsを実行するのに、アクセスキーをSecretsに設定していた場合、漏洩した際のリスクがあるため、定期的なローテーションの運用などがある。
そうすることなく、GitHubにはIAM RoleのARNだけを渡すのみで、一時的なアクセスキーを使って、AWSリソースへアクセスするOIDC連携が最近発表された。
AWSでは下記の設定のみで、準備が整うのでそのコードを記録しておく。

Terraform

※追記: thumbprint_listの固定値が変わったので修正(20240310)

resource "aws_iam_openid_connect_provider" "github-actions" {
  url             = "https://token.actions.githubusercontent.com"
  client_id_list  = ["sts.amazonaws.com"]
  thumbprint_list = [
    "6938fd4d98bab03faadb97b34396831e3780aea1",
    "1c58a3a8518e8759bf075b76b750d4f2df264fcd"
  ]       <-- 固定値
}

resource "aws_iam_role" "github-actions" {
  name = "github-actions"
  path = "/"
  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect = "Allow"
      Action = "sts:AssumeRoleWithWebIdentity"
      Principal = {
        Federated = aws_iam_openid_connect_provider.github-actions.arn
      }
      Condition = {
        StringLike = {
          "token.actions.githubusercontent.com:sub" = [
            "repo:inamuu/example:*",                 <-- ここで必ずリポジトリ制限を行う
          ]
        }
      }
    }]
  })
}

resource "aws_iam_role_policy_attachment" "github-actions-01" {
  role       = aws_iam_role.github-actions.name
  policy_arn = aws_iam_policy.describedb-clusters.arn
}

# フル権限を付与するなら policy_arn にAWSマネージドポリシーで下記を指定
# arn:aws:iam::aws:policy/AdministratorAccess

resource "aws_iam_policy" "describedb-clusters" {
  name        = "describedb-clusters"
  path        = "/"
  description = "Allow to describe db clusters"
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect = "Allow"
      Action = [
        "rds:DescribeDBClusters"
      ]
      Resource = "*"
    }]
  })
}

あとは、上記で作成したIAM RoleをGitHub ActionsのSecretsに登録するのみでOK。