locals{project="my-project-id" # GCPプロジェクトIDを指定"service_account_roles=["roles/storage.admin", # リソース管理のための権限付与"roles/resourcemanager.projectIamAdmin", # workload identity user role binding needs this permission"roles/iam.serviceAccountTokenCreator", # to allow impersonation of the service account]}# workload identity pool for HCP Terraformresource"google_iam_workload_identity_pool""hcp_terraform"{workload_identity_pool_id="hcp-terraform-pool"display_name="HCP Terraform Pool"description="Used to authenticate to Google Cloud"}# workload identity pool provider for HCP Terraformresource"google_iam_workload_identity_pool_provider""hcp_terraform"{workload_identity_pool_id=google_iam_workload_identity_pool.hcp_terraform.workload_identity_pool_idworkload_identity_pool_provider_id="hcp-terraform-provider"display_name="HCP Terraform Provider"description="Used to authenticate to Google Cloud"attribute_condition="assertion.sub.startsWith(\"organization:my-org:project:my-project:workspace:my-workspace\")"attribute_mapping={"google.subject"="assertion.sub","attribute.aud"="assertion.aud","attribute.terraform_run_phase"="assertion.terraform_run_phase","attribute.terraform_project_id"="assertion.terraform_project_id","attribute.terraform_project_name"="assertion.terraform_project_name","attribute.terraform_workspace_id"="assertion.terraform_workspace_id","attribute.terraform_workspace_name"="assertion.terraform_workspace_name","attribute.terraform_organization_id"="assertion.terraform_organization_id","attribute.terraform_organization_name"="assertion.terraform_organization_name","attribute.terraform_run_id"="assertion.terraform_run_id","attribute.terraform_full_workspace"="assertion.terraform_full_workspace",}oidc{issuer_uri="https://app.terraform.io"}}# service account that HCP Terraform will impersonateresource"google_service_account""hcp_terraform"{account_id="hcp-terraform"display_name="Service Account for HCP Terraform"}# IAM verifies the HCP Terraform Workspace ID before authorizing access to impersonate the service accountresource"google_service_account_iam_member""workload_identity_user"{service_account_id=google_service_account.hcp_terraform.namerole="roles/iam.workloadIdentityUser"member="principalSet://iam.googleapis.com/${google_iam_workload_identity_pool.hcp_terraform.name}/*"}# grant service account permissions to the roles defined in local.service_account_rolesresource"google_project_iam_member""hcp_terraform_roles"{for_each=toset(local.service_account_roles)member="serviceAccount:${google_service_account.hcp_terraform.email}"role=each.valueproject=local.project}
上記のコードは、Google Cloud の Dynamic Provider Credentials を設定するための基本的な例です。 リソースを作成するには Google Cloud で api を有効化する必要があります。適切な api を有効化しないと、以下のようなエラーが発生します。