🐙

GitHub Actions から AWS に Federated Login する

2023/10/19に公開

公式ドキュメント

https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services

Terraform

AWS アカウントにつき1つ必要

locals {
  github_url = "https://token.actions.githubusercontent.com"
}

data "tls_certificate" "github" {
  url = local.github_url
}

resource "aws_iam_openid_connect_provider" "github" {
  url             = local.github_url
  client_id_list  = ["sts.amazonaws.com"]
  thumbprint_list = [data.tls_certificate.github.certificates[0].sha1_fingerprint]
}

必要に応じて量産

locals {
  github_organization = "hoge"
  github_repository   = "fuga"
}

// GitHub リポジトリ hoge/fuga 以下の全アクションで AssumeRole 可能
data "aws_iam_policy_document" "assume_role_policy" {
  version = "2012-10-17"
  statement {
    effect  = "Allow"
    actions = ["sts:AssumeRoleWithWebIdentity"]
    principals {
      type        = "Federated"
      identifiers = [aws_iam_openid_connect_provider.github.arn]
    }
    condition {
      test     = "StringEquals"
      variable = "token.actions.githubusercontent.com:aud"
      values   = aws_iam_openid_connect_provider.github.client_id_list
    }
    condition {
      test     = "StringLike"
      variable = "token.actions.githubusercontent.com:sub"
      values   = ["repo:${local.github_organization}/${local.github_repository}:*"]
    }
  }
}

// 上記の AssumeRole Policy を持つ任意の IAM Role を利用可能
// 例として AmazonS3ReadOnlyAccess をアタッチ
resource "aws_iam_role" "github_actions" {
  name               = "GithubActionsRole"
  assume_role_policy = data.aws_iam_policy_document.assume_role_policy.json
}
resource "aws_iam_role_policy_attachment" "github_actions_s3_readonly" {
  role       = aws_iam_role.github_actions.id
  policy_arn = "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess"
}

GitHub Workflow

name: example-workflow
on:
  push:
    branches:
      - main

permissions:
  id-token: write # aws-actions/configure-aws-credentials で Federated Login するために必要
  contents: read  # actions/checkout でコンテンツを取得するために必要

jobs:
  example:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@v4
        with:
          aws-region: "${{ vars.AWS_REGION }}"
          role-to-assume: "arn:aws:iam::${{ vars.AWS_ACCOUNT_ID }}:role/GithubActionsRole"
          role-session-name: "後からトレースしやすいセッション名"

      - name: Example
        run: aws s3 ls
Happy Elements

Discussion