kokoichi206 / cloud-prac

0 stars 0 forks source link

gcp #30

Open kokoichi206 opened 2 months ago

kokoichi206 commented 2 months ago

iam

// セキュリティの向上のために GitHub と GCP の認証に Workload Identity を使う。
// 詳細については以下のドキュメントを参照してください。
// https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-google-cloud-platform

resource "google_iam_workload_identity_pool" "github" {
  project                   = var.project_id
  display_name              = "GitHub Actions Pool"
  workload_identity_pool_id = "github-actions"
  disabled                  = false
}

resource "google_iam_workload_identity_pool_provider" "github" {
  project                            = var.project_id
  workload_identity_pool_id          = google_iam_workload_identity_pool.github.workload_identity_pool_id
  workload_identity_pool_provider_id = "github-actions-provider"
  display_name                       = "GitHub repo Provider"
  description                        = "GitHub Actions の OIDC トークンを Google Cloud で認証するためのプロバイダ。"

  oidc {
    issuer_uri = "https://token.actions.githubusercontent.com"
  }

  attribute_mapping = {
    "google.subject"             = "assertion.sub"
    "attribute.actor"            = "assertion.actor"
    "attribute.repository"       = "assertion.repository"
    "attribute.repository_owner" = "assertion.repository_owner"
  }

  // フェデレーションを許可するリポジトリの指定。指定リポジトリ以外からの実行をさせない。
  attribute_condition = "assertion.repository == 'kokoichi206/sample-repo'"
}

resource "google_service_account" "gh_action_terraform" {
  account_id   = var.service_account_id_for_gh_actions
  display_name = var.service_account_id_for_gh_actions
}

resource "google_service_account_iam_policy" "policy" {
  policy_data        = data.google_iam_policy.workload_identity_user.policy_data
  service_account_id = google_service_account.gh_action_terraform.name
}

data "google_iam_policy" "workload_identity_user" {
  binding {
    members = [
      "principalSet://iam.googleapis.com/${google_iam_workload_identity_pool.github.name}/attribute.repository/kokoichi206/sample-repo"
    ]
    role = "roles/iam.workloadIdentityUser"
  }
}

resource "google_project_iam_member" "service_account_full_access" {
  project = var.project_id
  role    = "roles/editor"
  member  = "serviceAccount:${google_service_account.gh_action_terraform.email}"
}