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

概要

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

Terraform

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

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_policy_attachment" "github-actions" {
  name       = "github-actions"
  roles      = [aws_iam_role.github-actions.name]
  policy_arn = "arn:aws:iam::aws:policy/AdministratorAccess"    <-- 権限がわかっている場合は、必要な権限のみとする
}

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