📝Terraform
Use GCS bucket for storage
Module to create bucket:
variable "location" {
type = string
default = "US"
}
terraform {
required_providers {
google = {
version = "~> 4.20.0"
}
}
}
resource "random_id" "instance_id" {
byte_length = 8
}
resource "google_storage_bucket" "main" {
# bucket names must be globally-unique, so we add a random suffix
name = "tfstate-${random_id.instance_id.hex}"
location = var.location
storage_class = "STANDARD"
versioning {
enabled = true
}
}
output "bucket_name" {
value = google_storage_bucket.main.name
}
Use bucket as a backend:
terraform {
backend "gcs" {
bucket = "<bucket_name>"
}
}
Integrate GCP with Github workflows
# GitHub workflows integration
#
# For more details, see: https://github.com/google-github-actions/auth#setup
variable "repository" {
type = string
# format: username/repo-name
description = "Repostitory to grant access to"
}
resource "google_project_service" "iam" {
service = "iam.googleapis.com"
}
resource "google_project_service" "iamcredentials" {
service = "iamcredentials.googleapis.com"
}
resource "google_project_service" "cloudresourcemanager" {
service = "cloudresourcemanager.googleapis.com"
}
resource "google_service_account" "github" {
account_id = "github"
display_name = "GitHub workflows"
}
resource "google_iam_workload_identity_pool" "github" {
provider = google-beta
workload_identity_pool_id = "github"
description = "Workload identity pool for GitHub workflows"
}
resource "google_iam_workload_identity_pool_provider" "github" {
provider = google-beta
workload_identity_pool_id = google_iam_workload_identity_pool.github.workload_identity_pool_id
workload_identity_pool_provider_id = "github"
display_name = "GitHub"
attribute_mapping = {
"google.subject" = "assertion.sub"
"attribute.actor" = "assertion.actor"
"attribute.repository" = "assertion.repository"
}
oidc {
issuer_uri = "https://token.actions.githubusercontent.com"
}
}
resource "google_service_account_iam_binding" "github_iam" {
provider = google-beta
service_account_id = google_service_account.github.name
role = "roles/iam.workloadIdentityUser"
members = [
"principalSet://iam.googleapis.com/${google_iam_workload_identity_pool.github.name}/attribute.repository/${var.repository}"
]
}
output "github_service_account_email" {
value = google_service_account.github.email
}
output "github_workload_identity_pool_provider_id" {
value = google_iam_workload_identity_pool_provider.github.name
}