Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install google-cicd-terraform@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin google-cicd-terraform v1.0.0 follows the Agent Plugins spec.
gh skills-hub install google-cicd-terraform Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/google-cicd-terraform/ Extract the ZIP to .github/skills/ in your repo. The folder name must match google-cicd-terraform for Copilot to auto-discover it.
Skill Files (8)
SKILL.md 12.5 KB
---
name: google-cicd-terraform
metadata:
version: "1.0.0"
category: DevOps
description: >-
Architect, provision, and troubleshoot infrastructure on Google Cloud using Terraform. This skill ensures best practices like GCS backend usage and least-privilege IAM are followed. Enforces Google's Cloud Foundation Fabric patterns and rigorous validation protocols to ensure secure, idempotent, and scalable deployments across environments. Activate when the user requests infrastructure changes, pipeline design involving Terraform, or debugging Terraform issues.
DO NOT use when deploying application code or container images directly via `gcloud` or `kubectl` without Terraform (use `google-cicd-deploy`), designing high-level CI/CD architecture before choosing an IaC tool (use `google-cicd-pipeline-design`), or managing Cloud Deploy releases and rollouts via `clouddeploy.yaml` (use `google-cicd-release-orchestration`).
---
# Terraform GCP Skill
## Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read and follow the instructions in
[Usage Attribution](references/attribution.md).
This skill provides expert-level guidance for architecting, deploying, and
managing GCP infrastructure using Terraform.
## Prerequisites
Ensure the following prerequisites are satisfied before executing live commands:
* **CLI & Billing**: Install Terraform (`>= 1.6.0`), `tflint`, and the
[Google Cloud SDK](https://docs.cloud.google.com/sdk/docs/install.md.txt)
(`gcloud`), and attach an active **billing account** to the target project.
* **Authentication & Project**: Authenticate via `gcloud auth login` and
`gcloud auth application-default login` (or set
`GOOGLE_APPLICATION_CREDENTIALS` for CI service accounts), then set the
project and region (e.g., `us-central1`; see
[Cloud Locations](https://cloud.google.com/about/locations)):
`gcloud config set project <PROJECT_ID>` and
`gcloud config set compute/region <REGION>`.
* **API Enablement & IAM**: Enable required APIs (with user confirmation) via
`gcloud services enable cloudresourcemanager.googleapis.com
serviceusage.googleapis.com iam.googleapis.com storage.googleapis.com
cloudbuild.googleapis.com developerconnect.googleapis.com
artifactregistry.googleapis.com run.googleapis.com
container.googleapis.com`, and follow least-privilege IAM roles per
[iam-and-security.md](references/iam-and-security.md).
## 🎯 When to Use This Skill
- Designing GCP Landing Zones (Projects, Folders, Shared VPCs).
- Provisioning Google Cloud resources (GKE, Cloud Run, Cloud SQL, Spanner).
- Setting up remote state management via **GCS Backend**.
- Implementing IAM least-privilege via Terraform.
- Troubleshooting `terraform plan` discrepancies in GCP (see
[troubleshooting-gcp.md](references/troubleshooting-gcp.md)).
## 🏗️ Core Architecture: GCS Backend & State
**Always** use a GCS backend for state. Local state is strictly for local
prototyping and must never be committed. If local state directory is used, add
it to .gitignore.
### Standard Backend Configuration
```terraform
terraform {
backend "gcs" {
# Variables (var.*) are not allowed in backend blocks; set literal values
# or pass via: terraform init -backend-config="bucket=tf-state-<PROJECT_ID>"
bucket = "tf-state-<PROJECT_ID>"
prefix = "terraform/state/<ENVIRONMENT>"
}
}
```
Note: The GCS bucket must have Object Versioning enabled to allow recovery from
accidental state corruption or overlapping writes.
### Required Provider Version
Use the Google Cloud Terraform provider version 7.20.0 or higher. This skill
utilizes features (e.g., Developer Connect) introduced in Google Provider
v7.20.0.
```terraform
terraform {
required_version = ">= 1.6.0"
required_providers {
google = {
source = "hashicorp/google"
version = ">= 7.20.0"
}
}
}
```
To retrieve the latest version of the Google provider, use the following
command:
```bash
curl -s https://registry.terraform.io/v1/providers/hashicorp/google | jq -r .version
```
## 🛠️ Execution Protocol (Safety First)
The Agent must follow this lifecycle for every infrastructure change to ensure
idempotency and prevent production outages:
1. Initialize (`terraform init`):
- Verify backend connectivity.
- Ensure provider plugins are downloaded and versions are locked in
`.terraform.lock.hcl`.
2. Validate (`terraform validate` & `tflint`):
- Check for internal HCL consistency.
- Run `tflint` with the Google plugin to catch cloud-specific deprecated
fields or non-optimal configurations.
3. Plan (`terraform plan -out=tfplan`):
- Generate a speculative execution plan.
- Mandatory Step: The Agent must summarize the plan for the user,
specifically highlighting any Destroy actions.
4. Apply (`terraform apply tfplan`):
- Strict Constraint: Only execute the application after the user provides
explicit manual confirmation.
## 🔍 Live Provider Documentation Lookup
To prevent hallucinations regarding new fields or deprecated attributes, the
Agent must verify the grounded truth of the provider schema.
### Schema Inspection via CLI
The primary command for retrieving the machine-readable schema of the currently
initialized providers is:
```bash
$ terraform providers schema -json
```
## 🛡️ GCP-Specific Standards
1. **Resource Naming & "Main" Pattern**: To maintain a clean module interface,
use the main identifier for singleton resources (the primary resource the
module is named after). Use underscores for identifiers and hyphens for
names (see [naming-conventions.md](references/naming-conventions.md)).
```terraform
resource "google_compute_network" "main" {
name = "${var.prefix}-vpc"
auto_create_subnetworks = false
}
```
2. **IAM Management** (see
[iam-and-security.md](references/iam-and-security.md) and
[gcp-networking-patterns.md](references/gcp-networking-patterns.md)):
- Never use `google_project_iam_policy`: This resource is authoritative
and replaces the entire IAM policy for the project. It is the #1 cause
of accidental lockouts.
- Prefer `google_project_iam_member` or `google_project_iam_binding`:
- `google_project_iam_member` is additive and safely grants a role to
a single member.
- `google_project_iam_binding` is authoritative for a single role.
It's useful for managing all members of a role, but be aware it
overwrites existing members for that role.
- Shared VPC: Always distinguish between Host projects (where the network
lives) and Service projects (where resources consume the network).
- Private Google Access: Subnets should always have
private_ip_google_access = true.
- Workload Identity: Prefer GKE Workload Identity over static Service
Account JSON keys.
3. **Cloud Build Triggers with Developer Connect**: When using Developer
Connect git repository links, use `developer_connect_event_config` — NOT
`repository_event_config`. The `repository_event_config` block is for Cloud
Build v2 repository connections and will not work with Developer Connect
resources. An example block to create a Cloud Build trigger with Developer
Connect git repository link is as follows:
```terraform
resource "google_cloudbuild_trigger" "main" {
developer_connect_event_config {
git_repository_link = google_developer_connect_git_repository_link.main.id
push {
branch = var.trigger_branch
}
}
}
```
4. **Developer Connect Connection (GitHub, GitLab, Bitbucket)**: When
configuring `google_developer_connect_connection`, configure the block
matching the user's source control provider (`github_config`,
`github_enterprise_config`, `gitlab_config`, `gitlab_enterprise_config`,
`bitbucket_cloud_config`, or `bitbucket_data_center_config`). If using
`github_config`, always set `github_app` to `"DEVELOPER_CONNECT"` (using
`"FIREBASE"` is incorrect and will cause triggers to fail).
```terraform
resource "google_developer_connect_connection" "main" {
location = var.region
connection_id = var.connection_id
project = var.project_id
# Example for GitHub (use gitlab_config / bitbucket_cloud_config for GitLab / Bitbucket):
github_config {
github_app = "DEVELOPER_CONNECT" # CORRECT
authorizer_credential {
oauth_token_secret_version = "" # Populated after manual authorization
}
}
depends_on = [google_project_service.main["developerconnect.googleapis.com"]]
lifecycle {
ignore_changes = [github_config[0].authorizer_credential]
}
}
```
5. **Developer Connect Git Repository Link**: When configuring
`google_developer_connect_git_repository_link`, use `parent_connection` and
`git_repository_link_id` as required arguments.
```terraform
resource "google_developer_connect_git_repository_link" "main" {
location = var.region
parent_connection = google_developer_connect_connection.main.connection_id
git_repository_link_id = "my-repo-link"
clone_uri = var.git_repo_uri
}
```
## 📂 Directory Structure
Follow this standard (see
[style-and-structure.md](references/style-and-structure.md)) to ensure
compatibility with Antigravity (AGY) discovery and Google best practices:
```
.
└── terraform/
├── main.tf # Entry point / Resource definitions
├── variables.tf # Typed variables with units and descriptions
├── outputs.tf # Resource ID outputs (no direct input pass-through)
├── versions.tf # Provider version pinning
├── network.tf # (Optional) Grouped networking resources
├── examples/ # Example usage for modules
├── files/ # Static files (startup scripts, etc.)
├── templates/ # .tftpl templates
├── scripts/ # Scripts called by Terraform
└── helpers/ # Scripts NOT called by Terraform
```
## ⚠️ Anti-Patterns (Do NOT do these)
- ❌ Legacy GitHub Triggers: Do not use the legacy `github` block in
`google_cloudbuild_trigger`. Always use `developer_connect_event_config`.
- ❌ Hardcoded IDs: Never hardcode Project IDs. Use variables or a
`data "google_project"` source.
- ❌ Service Account Keys: Never generate or store .json keys. Use Workload
Identity Federation or the default metadata server.
- ❌ Broad Scopes: Avoid cloud-platform scopes for GKE nodes; use fine-grained
IAM roles instead.
- ❌ Uppercase Types: Terraform variable types must be lowercase (e.g.,
`type = string` not `type = STRING`).
## 🧪 Testing Strategy
- Consult [testing-and-mocking.md](references/testing-and-mocking.md) for
mocked plan validation and `terraform test` patterns.
- Static Analysis: Use checkov, trivy, or terrascan to catch insecure GCP
configurations (e.g., public GCS buckets).
- Integration Testing: Use terraform test (v1.6+) to assert that GCP labels
and network tags are correctly applied to resources before full deployment.
## 📚 Reference Guides
- [naming-conventions.md](references/naming-conventions.md): Resource
identifier and GCP naming rules.
- [style-and-structure.md](references/style-and-structure.md): Module layout,
formatting, and variable typing standards.
- [iam-and-security.md](references/iam-and-security.md): Least-privilege IAM,
Workload Identity, and Secret Manager integration.
- [gcp-networking-patterns.md](references/gcp-networking-patterns.md): Custom
VPCs, Shared VPC, and Private Service Connect patterns.
- [testing-and-mocking.md](references/testing-and-mocking.md): Terraform
unit/integration testing (`*.tftest.hcl`) and static analysis.
- [troubleshooting-gcp.md](references/troubleshooting-gcp.md): Common GCP
Terraform errors and remediation steps.
## Resource Cleanup & Teardown
Provisioned GKE clusters, Cloud Run services, Cloud SQL instances, Artifact
Registry repositories, and GCS state buckets incur charges (an active billing
account is required even within free tiers; see
[Google Cloud Pricing](https://cloud.google.com/pricing)). Always generate and
summarize a speculative destroy plan (`terraform plan -destroy -out=tfdestroy`)
and obtain explicit manual confirmation from the user before running
`terraform apply tfdestroy` (or `gcloud projects delete <PROJECT_ID>` for
ephemeral sandbox projects).
attribution.md 1.9 KB
# Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.
- **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
subcommand, with the metrics environment variable. Set it inline on each
command because shell state may not persist between commands:
```bash
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:google-cicd-terraform)" \
gcloud <command> [flags]
```
Do not use `gcloud config set` for this: it would persist beyond the current
task and mislabel unrelated usage.
- **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
server, include
`agent-skills/1.0 (skill:google-cicd-terraform)` in the `User-Agent` header.
If a `User-Agent` header is already specified, append this string to the end
of it rather than overwriting existing `User-Agent` data — the collection
pipeline parses the `agent-skills/<version>` and `skill:<name>` tokens, so
any rewording breaks attribution:
```
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:google-cicd-terraform)
```
- **Constraint for Generated Code**: The tracking prefix is strictly for
commands you execute directly in the terminal. Do NOT include this tracking
prefix in generated scripts, Terraform templates, or code provided to the
user for their own repositories.
- **User Opt-Out**: If the user asks to disable or remove tracking or
attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
and custom `User-Agent` suffix from all commands.
gcp-networking-patterns.md 2.1 KB
# GCP Networking Patterns
GCP's global VPC architecture requires specific patterns for Shared VPCs,
Private Access, and Security Perimeters.
## 🤝 Shared VPC Configuration
In a Shared VPC topology, distinguish clearly between the **Host Project**
(manages the network) and the **Service Project** (hosts resources like GKE or
VMs).
### 1. Enabling the Host Project
```terraform
resource "google_compute_shared_vpc_host_project" "host" {
project = var.host_project_id
}
```
### 2. Attaching a Service Project
```terraform
resource "google_compute_shared_vpc_service_project" "service" {
host_project = google_compute_shared_vpc_host_project.host.project
service_project = var.service_project_id
}
```
## 🔒 Private Service Access (PSA)
Required for connecting to managed services like Cloud SQL or Redis via internal
IP addresses.
```terraform
# 1. Reserve an internal IP range
resource "google_compute_global_address" "private_ip_alloc" {
name = "google-managed-services-range"
purpose = "VPC_PEERING"
address_type = "INTERNAL"
prefix_length = 16
network = google_compute_network.main.id
}
# 2. Establish the peering connection
resource "google_service_networking_connection" "private_vpc_connection" {
network = google_compute_network.main.id
service = "servicenetworking.googleapis.com"
reserved_peering_ranges = [google_compute_global_address.private_ip_alloc.name]
}
```
## 🛡️ VPC Service Controls (VPC-SC)
VPC-SC perimeters protect data in services like GCS and BigQuery. Ensure
Terraform has the necessary `access_context_manager` permissions to modify
perimeters.
```terraform
resource "google_access_context_manager_service_perimeter" "perimeter" {
parent = "accessPolicies/${var.access_policy_id}"
name = "accessPolicies/${var.access_policy_id}/servicePerimeters/${var.perimeter_name}"
title = var.perimeter_name
status {
restricted_services = ["storage.googleapis.com", "bigquery.googleapis.com"]
resources = ["projects/${var.project_number}"]
access_levels = [google_access_context_manager_access_level.main.name]
}
}
```
iam-and-security.md 5.2 KB
# IAM and Security Standards for GCP
Prevent outages and security breaches by following additive IAM patterns,
dedicated CI/CD service accounts, and Workload Identity.
## Table of Contents
- [Additive vs. Authoritative IAM](#additive-vs-authoritative-iam) (Lines
17-37)
- [CI/CD Pipeline Service Accounts](#cicd-pipeline-service-accounts-cloud-build-developer-connect-artifact-registry-and-binary-authorization)
(Lines 39-84)
- [Workload Identity (GKE and Agent Registry SPIFFE Identity)](#workload-identity-gke-and-agent-registry-spiffe-identity)
(Lines 86-106)
- [Organization Policy Constraints](#organization-policy-constraints) (Lines
108-127)
## Additive vs. Authoritative IAM
**NEVER** use authoritative resources (`google_project_iam_policy` or
`google_project_iam_binding`) for core projects unless you are explicitly
managing the *entire* policy and understand the risk of lockouts.
Resource | Type | Impact | Usage
:--------------------------- | :-------------------------- | :------------------------------------------ | :----
`google_project_iam_member` | **Additive** | Adds a single member/role. Safe. | **Preferred**
`google_project_iam_binding` | **Authoritative (Role)** | Overwrites all members for a specific role. | Use with caution.
`google_project_iam_policy` | **Authoritative (Project)** | Overwrites the entire project IAM policy. | **BANNED** for general use.
### Example: Safe Additive IAM
```terraform
resource "google_project_iam_member" "storage_admin" {
project = var.project_id
role = "roles/storage.admin"
member = "serviceAccount:${google_service_account.main.email}"
}
```
## CI/CD Pipeline Service Accounts (Cloud Build, Developer Connect, Artifact Registry, and Binary Authorization)
Never use the legacy default Cloud Build service account
(`<PROJECT_NUMBER>@cloudbuild.gserviceaccount.com`) for production triggers.
Provision a dedicated Cloud Build runner service account (`cloudbuild-runner`)
with least-privilege additive IAM roles:
```terraform
resource "google_service_account" "cloudbuild_runner" {
project = var.project_id
account_id = "cloudbuild-runner"
display_name = "Dedicated Cloud Build Runner Service Account"
}
locals {
cloudbuild_runner_roles = [
"roles/logging.logWriter", # Required for CLOUD_LOGGING_ONLY
"roles/artifactregistry.writer", # Push images & export SPDX SBOMs
"roles/developerconnect.readTokenAccessor", # Fetch read tokens for GitHub/GitLab/Bitbucket
"roles/run.developer", # Deploy Cloud Run revisions
"roles/container.developer", # Deploy to GKE clusters
"roles/binaryauthorization.attestorsVerifier" # Verify Binary Authorization attestors on prod
]
}
resource "google_project_iam_member" "cloudbuild_runner_permissions" {
for_each = toset(local.cloudbuild_runner_roles)
project = var.project_id
role = each.value
member = "serviceAccount:${google_service_account.cloudbuild_runner.email}"
}
# Scope serviceAccountUser strictly to the target runtime SA (never project-wide)
resource "google_service_account_iam_member" "cloudbuild_runner_act_as_runtime" {
service_account_id = google_service_account.gsa.name
role = "roles/iam.serviceAccountUser"
member = "serviceAccount:${google_service_account.cloudbuild_runner.email}"
}
# Grant Cloud Build Service Agent least-privilege access to read Developer Connect repository links
resource "google_project_iam_member" "cloudbuild_service_agent_devconnect" {
project = var.project_id
role = "roles/developerconnect.readTokenAccessor"
member = "serviceAccount:service-${var.project_number}@gcp-sa-cloudbuild.iam.gserviceaccount.com"
}
```
## Workload Identity (GKE and Agent Registry SPIFFE Identity)
Bind Kubernetes Service Accounts (KSA) to Google Service Accounts (GSA) without
managing JSON keys. For AI Agents and MCP Servers on GKE, pair Workload Identity
with the `iam.gke.io/spiffe-identity-type: "agent-identity"` pod template
annotation for Google Cloud Agent Registry discovery.
```terraform
# 1. The Google Service Account
resource "google_service_account" "gsa" {
account_id = "app-workload-sa"
project = var.project_id
}
# 2. The IAM Binding for Workload Identity
resource "google_service_account_iam_member" "workload_identity_user" {
service_account_id = google_service_account.gsa.name
role = "roles/iam.workloadIdentityUser"
member = "serviceAccount:${var.project_id}.svc.id.goog[${var.k8s_namespace}/${var.k8s_sa_name}]"
}
```
## Organization Policy Constraints
Common constraints to enforce during `terraform validate` or `plan`:
- `constraints/compute.disableSerialPortAccess`: Prevents unencrypted console
access.
- `constraints/compute.vmExternalIpAccess`: Blocks external IPs for VMs.
- `constraints/iam.allowedPolicyMemberDomains`: Restricts IAM to specific
Workspace/Cloud Identity domains.
```terraform
resource "google_project_organization_policy" "disable_serial_port" {
project = var.project_id
constraint = "constraints/compute.disableSerialPortAccess"
boolean_policy {
enforced = true
}
}
```
naming-conventions.md 2.3 KB
# GCP Naming Conventions for Terraform
Standardizing resource names ensures compatibility with GCP's heterogeneous
naming requirements and maintains consistency across environments.
## 🏗️ Core Principles
1. **Lowercase Only**: Most GCP resources (GCE, GCS, GKE) require lowercase
alphanumeric characters and hyphens.
2. **DNS Compliance (RFC 1035)**: Names must start with a letter, end with a
letter or digit, and use only `-` (no underscores).
3. **Object Naming (Underscores)**: Name all configuration objects
(resource/data source identifiers) using **underscores**.
4. **Resource Names (Hyphens)**: Use **hyphens** for the actual resource names
within GCP.
Recommended:
```terraform
resource "google_compute_instance" "web_server" {
name = "web-server"
}
```
## 📌 Resource-Specific Rules
Resource Type | Regex Pattern | Max Length | Notes
:------------------------ | :------------------------------------ | :--------- | :----
`google_compute_instance` | `^[a-z]([-a-z0-9]*[a-z0-9])?$` | 63 | RFC 1035 compliant.
`google_storage_bucket` | `^[a-z0-9][a-z0-9._-]{1,61}[a-z0-9]$` | 63 | Global namespace; no underscores.
`google_project` | `^[a-z][a-z0-9-]{4,28}[a-z0-9]$` | 30 | Must be globally unique.
## 🧩 The Singleton Pattern (`main`)
To simplify references to a resource that is the only one of its type in a
module, name the identifier `main`.
- **Keep it singular**: Resource names should be singular.
- **No redundancy**: Don't repeat the resource type in the identifier.
Recommended:
```terraform
resource "google_compute_network" "main" {
name = "${var.prefix}-${var.environment}-vpc"
}
```
Not Recommended:
```terraform
resource "google_compute_network" "main_vpc" { ... }
```
## 🌍 Multi-Environment Prefixing
Always use a prefixing logic to prevent collisions and identify ownership.
```terraform
variable "prefix" {
type = string
description = "Project or team prefix (e.g., 'acme')"
}
variable "environment" {
type = string
description = "Target environment (e.g., 'prod', 'staging')"
}
# Implementation
resource "google_service_account" "app_sa" {
account_id = "${var.prefix}-${var.environment}-app"
display_name = "Application Service Account for ${var.environment}"
}
```
style-and-structure.md 2.8 KB
# Terraform Style and Structure Best Practices
This document outlines the standard style and directory structure for GCP
Terraform configurations, ensuring they are maintainable, readable, and follow
Google Cloud's recommended patterns.
## 📂 Standard Module Structure
Follow this layout for both reusable modules and root configurations:
- `main.tf`: Default location for resources.
- `variables.tf`: All variable declarations with types and descriptions.
- `outputs.tf`: All output declarations with descriptions.
- `README.md`: Module documentation (use `terraform-docs` for automation).
- `examples/`: Subdirectories for each usage example with their own READMEs.
- `scripts/`: Custom scripts called by Terraform provisioners.
- `helpers/`: Scripts not called by Terraform.
- `files/`: Static files (e.g., startup scripts).
- `templates/`: Template files (use `.tftpl` extension).
- `docs/`: Additional long-form documentation.
### Logical Grouping
Group resources by shared purpose rather than giving every resource its own
file.
- `network.tf`: VPCs, subnets, firewall rules.
- `instances.tf`: Compute Engine VMs, Managed Instance Groups.
- `iam.tf`: Service accounts and IAM bindings.
## 🔢 Variables and Outputs
### Variables
- **Units in Names**: Include units for numeric values (e.g., `ram_size_gb`,
`disk_size_mib`).
- **Binary vs Decimal**: Use binary prefixes (KiB, MiB, GiB) for storage and
decimal (KB, MB, GB) for other measurements.
- **Positive Booleans**: Name booleans positively (e.g.,
`enable_external_access` instead of `disable_private_endpoint`).
- **Mandatory Descriptions**: All variables must have `description` and
`type`.
- **Default Values**: Provide defaults for environment-independent values;
omit them for environment-specific values (like `project_id`) to force
explicit input.
### Outputs
- **Resource Attributes**: Always reference resource attributes in outputs,
not input variables, to preserve the dependency graph.
- **Descriptions**: All outputs must have a `description`.
## 🛠️ Logic and Complexity
- **Formatting**: Always run `terraform fmt`.
- **Ternaries**: Never use more than one ternary operator on a single line.
- **Complexity**: Split complex interpolated expressions into multiple `local`
values.
- **Count vs For Each**:
- Use `count` for conditional resource creation.
- Use `for_each` for multiple instances of a resource based on a map or
set.
## 🔒 State Preservation
For stateful resources (Cloud SQL, Spanner, etc.), always enable deletion
protection.
```terraform
resource "google_sql_database_instance" "main" {
name = "primary-instance"
database_version = "POSTGRES_15"
settings {
tier = "db-f1-micro"
}
deletion_protection = true
lifecycle {
prevent_destroy = true
}
}
```
testing-and-mocking.md 1.7 KB
# Testing and Mocking GCP Infrastructure
Leverage `terraform test` (v1.6+) and `mock_provider` (v1.7+) to validate
infrastructure logic without deploying real resources.
## 🧪 Unit Testing with `terraform test`
Use assertions to verify that variables and resource configurations meet
requirements.
```terraform
# tests/vpc_validation.tftest.hcl
run "verify_vpc_naming" {
command = plan
assert {
condition = google_compute_network.main.name == "acme-prod-vpc"
error_message = "VPC name did not match the expected prefix/env pattern."
}
assert {
condition = google_compute_network.main.auto_create_subnetworks == false
error_message = "Auto-creation of subnetworks must be disabled."
}
}
```
## 🎭 Mocking the GCP Provider
Mock providers allow CI pipelines to run tests without valid GCP credentials or
network access.
```terraform
# tests/mock_setup.tftest.hcl
mock_provider "google" {
source = "hashicorp/google"
}
run "mock_instance_test" {
command = plan
# Override specific attributes if needed for logic checks
override_resource {
target = google_compute_instance.main
values = {
instance_id = "mock-12345"
}
}
}
```
## 🔍 Integration Assertions
Verify complex configurations like GKE Workload Identity or Private Google
Access.
```terraform
run "check_gke_config" {
command = plan
assert {
condition = can(google_container_cluster.main.workload_identity_config[0].workload_pool)
error_message = "GKE cluster is missing Workload Identity configuration."
}
assert {
condition = alltrue([for s in google_compute_subnetwork.main : s.private_ip_google_access])
error_message = "All subnets must have Private Google Access enabled."
}
}
```
troubleshooting-gcp.md 5.6 KB
# Troubleshooting GCP-Terraform Errors
A guide to identifying and resolving common errors encountered when managing GCP
and CI/CD resources with Terraform.
## Table of Contents
* [403 Forbidden (Permission Denied)](#403-forbidden-permission-denied) (Lines
21-41)
* [Cloud Build Trigger `INVALID_ARGUMENT` with Custom Service Account](#cloud-build-trigger-invalid_argument-with-custom-service-account)
(Lines 43-55)
* [Developer Connect Connection and Repository Link Errors](#developer-connect-connection-and-repository-link-errors-github-gitlab-bitbucket)
(Lines 57-73)
* [Cloud Run Binary Authorization Policy Rejection (`IMAGE_UNTRUSTED`)](#cloud-run-binary-authorization-policy-rejection-image_untrusted)
(Lines 75-89)
* [Resource In Use and Deletion Delays](#resource-in-use-and-deletion-delays)
(Lines 91-107)
* [GCS State Locking](#gcs-state-locking) (Lines 109-123)
* [Provider Schema Inspection](#provider-schema-inspection) (Lines 125-136)
## 403 Forbidden (Permission Denied)
**Symptoms**: `Error 403: Permission '...' denied on resource '...'`.
**Fixes**:
1. **Service Usage API**: Ensure the `serviceusage.googleapis.com` API is
enabled in the project.
2. **Missing Roles**: Verify the principal (Service Account or User) has the
required IAM roles. Use `google_project_iam_member` to add them:
* Artifact Registry repository/image push: `roles/artifactregistry.admin`
or `roles/artifactregistry.writer`
* Developer Connect token fetch (`fetchReadToken`):
`roles/developerconnect.readTokenAccessor` or
`roles/developerconnect.admin`
* Cloud Build trigger creation with custom SA:
`roles/cloudbuild.builds.editor` and `roles/iam.serviceAccountUser` on
the custom service account
* GKE cluster credentials & deployment: `roles/container.developer`
3. **Propagation Delay**: IAM changes can take up to 60 seconds to propagate.
Retry the operation.
## Cloud Build Trigger `INVALID_ARGUMENT` with Custom Service Account
**Symptoms**: `Error 400: invalid argument: if 'build.service_account' is
specified, the build must either (a) specify 'build.logs_bucket', (b) use the
CLOUD_LOGGING_ONLY logging option, or (c) use the NONE logging option`.
**Fixes**:
1. Whenever `service_account` is set on `google_cloudbuild_trigger`, ensure the
referenced `cloudbuild.yaml` or inline `build` block sets
`options { logging = "CLOUD_LOGGING_ONLY" }`.
2. Ensure the custom service account has `roles/logging.logWriter` on the
project.
## Developer Connect Connection and Repository Link Errors (GitHub, GitLab, Bitbucket)
**Symptoms**: `Error waiting for Creating GitRepositoryLink: PERMISSION_DENIED`
or `FAILED_PRECONDITION: Connection is not in COMPLETE state`.
**Fixes**:
1. **Complete OAuth/App Installation**: A `google_developer_connect_connection`
(configured with `github_config`, `gitlab_config`, or
`bitbucket_cloud_config`) must have its installation state completed in the
GCP Console before creating a
`google_developer_connect_git_repository_link`.
2. **Service Agent Role**: Ensure the Cloud Build Service Agent
(`service-<PROJECT_NUMBER>@gcp-sa-cloudbuild.iam.gserviceaccount.com`) has
`roles/developerconnect.admin` or `roles/developerconnect.readTokenAccessor`
before creating a `google_cloudbuild_trigger` with
`developer_connect_event_config`.
## Cloud Run Binary Authorization Policy Rejection (`IMAGE_UNTRUSTED`)
**Symptoms**: Deployment to `prod` Cloud Run service fails with `Admission
webhook denied the request: Image ... denied by Binary Authorization default
policy: Image ... is not attested by attestor ...`.
**Fixes**:
1. Resolve the immutable image digest (`@sha256:...`) in Artifact Registry.
2. Verify whether an attestation exists using `gcloud container binauthz
attestations list --artifact-url="<IMAGE_URI>@<DIGEST>"`.
3. Create the required attestation with
`gcloud container binauthz attestations create` (or via a Cloud Build KMS
signing step) before deploying to `prod` with
`binary_authorization = "default"`.
## Resource In Use and Deletion Delays
**Symptoms**: `Error: Resource ... is still in use` or
`Error deleting Subnetwork: ...`.
**Fixes**:
1. **Dependency Chains**: GCP often has hidden dependencies. For example, a
`google_compute_subnetwork` cannot be deleted if a `google_compute_address`
or a VM is still using it.
2. **Force Destroy**: For `google_storage_bucket` or
`google_artifact_registry_repository`, use `force_destroy = true` (or
`cleanup_policy_dry_run = false`) if you want Terraform to delete a
non-empty container in ephemeral test environments.
3. **Sequential Deletion**: Sometimes `terraform destroy` struggles with
complex VPC peering. Try destroying resources in smaller chunks if a timeout
occurs.
## GCS State Locking
**Symptoms**:
`Error: Error acquiring the state lock: ... GCS bucket ... already locked`.
**Fixes**:
1. **Check for Active Processes**: Ensure no other developer or CI job is
running.
2. **Manual Unlock**: If a process crashed and left the lock behind, use the
force-unlock command with the Lock ID provided in the error message:
```bash
terraform force-unlock <LOCK_ID>
```
## Provider Schema Inspection
To see exactly what fields a resource supports and avoid "Attribute not found"
errors:
```bash
# Export the full provider schema to JSON
terraform providers schema -json > schema.json
# Use jq to find specific resource details
cat schema.json | jq '.provider_schemas["registry.terraform.io/hashicorp/google"].resource_schemas["google_cloudbuild_trigger"]'
```
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE