Google Cloud Terraform

Google Cloud Terraform

Guides an agent to design, provision and debug Google Cloud infrastructure with Terraform, enforcing GCS state backends, least-privilege IAM and Cloud Foundation Fabric patterns.

Skill files8 files

references/

SKILL.md318 lines
1
---
2
name: google-cicd-terraform
3
metadata:
4
version: "1.0.1"
5
category: DevOps
6
description: >-
7
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.
8
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`).
9
---
10
11
# Terraform GCP Skill
12
13
## Usage Attribution
14
15
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
16
MUST read and follow the instructions in
17
[Usage Attribution](references/attribution.md).
18
19
This skill provides expert-level guidance for architecting, deploying, and
20
managing GCP infrastructure using Terraform.
21
22
## Prerequisites
23
24
Ensure the following prerequisites are satisfied before executing live commands:
25
26
* **CLI & Billing**: Install Terraform (`>= 1.6.0`), `tflint`, and the
27
[Google Cloud SDK](https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt)
28
(`gcloud`), and attach an active **billing account** to the target project.
29
* **Authentication & Project**: Authenticate via `gcloud auth login` and
30
`gcloud auth application-default login` (or set
31
`GOOGLE_APPLICATION_CREDENTIALS` for CI service accounts), then set the
32
project and region (e.g., `us-central1`; see
33
[Cloud Locations](https://cloud.google.com/about/locations)):
34
`gcloud config set project <PROJECT_ID>` and
35
`gcloud config set compute/region <REGION>`.
36
* **API Enablement & IAM**: Enable required APIs (with user confirmation) via
37
`gcloud services enable cloudresourcemanager.googleapis.com
38
serviceusage.googleapis.com iam.googleapis.com storage.googleapis.com
39
cloudbuild.googleapis.com developerconnect.googleapis.com
40
artifactregistry.googleapis.com run.googleapis.com
41
container.googleapis.com`, and follow least-privilege IAM roles per
42
[iam-and-security.md](references/iam-and-security.md).
43
44
## 🎯 When to Use This Skill
45
46
- Designing GCP Landing Zones (Projects, Folders, Shared VPCs).
47
- Provisioning Google Cloud resources (GKE, Cloud Run, Cloud SQL, Spanner).
48
- Setting up remote state management via **GCS Backend**.
49
- Implementing IAM least-privilege via Terraform.
50
- Troubleshooting `terraform plan` discrepancies in GCP (see
51
[troubleshooting-gcp.md](references/troubleshooting-gcp.md)).
52
53
## 🏗️ Core Architecture: GCS Backend & State
54
55
**Always** use a GCS backend for state. Local state is strictly for local
56
prototyping and must never be committed. If local state directory is used, add
57
it to .gitignore.
58
59
### Standard Backend Configuration
60
61
```terraform
62
terraform {
63
backend "gcs" {
64
# Variables (var.*) are not allowed in backend blocks; set literal values
65
# or pass via: terraform init -backend-config="bucket=tf-state-<PROJECT_ID>"
66
bucket = "tf-state-<PROJECT_ID>"
67
prefix = "terraform/state/<ENVIRONMENT>"
68
}
69
}
70
```
71
72
Note: The GCS bucket must have Object Versioning enabled to allow recovery from
73
accidental state corruption or overlapping writes.
74
75
### Required Provider Version
76
77
Use the Google Cloud Terraform provider version 7.20.0 or higher. This skill
78
utilizes features (e.g., Developer Connect) introduced in Google Provider
79
v7.20.0.
80
81
```terraform
82
terraform {
83
required_version = ">= 1.6.0"
84
85
required_providers {
86
google = {
87
source = "hashicorp/google"
88
version = ">= 7.20.0"
89
}
90
}
91
}
92
```
93
94
To retrieve the latest version of the Google provider, use the following
95
command:
96
97
```bash
98
curl -s https://registry.terraform.io/v1/providers/hashicorp/google | jq -r .version
99
```
100
101
## 🛠️ Execution Protocol (Safety First)
102
103
The Agent must follow this lifecycle for every infrastructure change to ensure
104
idempotency and prevent production outages:
105
106
1. Initialize (`terraform init`):
107
108
- Verify backend connectivity.
109
110
- Ensure provider plugins are downloaded and versions are locked in
111
`.terraform.lock.hcl`.
112
113
2. Validate (`terraform validate` & `tflint`):
114
115
- Check for internal HCL consistency.
116
117
- Run `tflint` with the Google plugin to catch cloud-specific deprecated
118
fields or non-optimal configurations.
119
120
3. Plan (`terraform plan -out=tfplan`):
121
122
- Generate a speculative execution plan.
123
124
- Mandatory Step: The Agent must summarize the plan for the user,
125
specifically highlighting any Destroy actions.
126
127
4. Apply (`terraform apply tfplan`):
128
129
- Strict Constraint: Only execute the application after the user provides
130
explicit manual confirmation.
131
132
## 🔍 Live Provider Documentation Lookup
133
134
To prevent hallucinations regarding new fields or deprecated attributes, the
135
Agent must verify the grounded truth of the provider schema.
136
137
### Schema Inspection via CLI
138
139
The primary command for retrieving the machine-readable schema of the currently
140
initialized providers is:
141
142
```bash
143
$ terraform providers schema -json
144
```
145
146
## 🛡️ GCP-Specific Standards
147
148
1. **Resource Naming & "Main" Pattern**: To maintain a clean module interface,
149
use the main identifier for singleton resources (the primary resource the
150
module is named after). Use underscores for identifiers and hyphens for
151
names (see [naming-conventions.md](references/naming-conventions.md)).
152
153
```terraform
154
resource "google_compute_network" "main" {
155
name = "${var.prefix}-vpc"
156
auto_create_subnetworks = false
157
}
158
```
159
160
2. **IAM Management** (see
161
[iam-and-security.md](references/iam-and-security.md) and
162
[gcp-networking-patterns.md](references/gcp-networking-patterns.md)):
163
164
- Never use `google_project_iam_policy`: This resource is authoritative
165
and replaces the entire IAM policy for the project. It is the #1 cause
166
of accidental lockouts.
167
168
- Prefer `google_project_iam_member` or `google_project_iam_binding`:
169
170
- `google_project_iam_member` is additive and safely grants a role to
171
a single member.
172
- `google_project_iam_binding` is authoritative for a single role.
173
It's useful for managing all members of a role, but be aware it
174
overwrites existing members for that role.
175
176
- Shared VPC: Always distinguish between Host projects (where the network
177
lives) and Service projects (where resources consume the network).
178
179
- Private Google Access: Subnets should always have
180
private_ip_google_access = true.
181
182
- Workload Identity: Prefer GKE Workload Identity over static Service
183
Account JSON keys.
184
185
3. **Cloud Build Triggers with Developer Connect**: When using Developer
186
Connect git repository links, use `developer_connect_event_config` — NOT
187
`repository_event_config`. The `repository_event_config` block is for Cloud
188
Build v2 repository connections and will not work with Developer Connect
189
resources. An example block to create a Cloud Build trigger with Developer
190
Connect git repository link is as follows:
191
192
```terraform
193
resource "google_cloudbuild_trigger" "main" {
194
developer_connect_event_config {
195
git_repository_link = google_developer_connect_git_repository_link.main.id
196
push {
197
branch = var.trigger_branch
198
}
199
}
200
}
201
```
202
203
4. **Developer Connect Connection (GitHub, GitLab, Bitbucket)**: When
204
configuring `google_developer_connect_connection`, configure the block
205
matching the user's source control provider (`github_config`,
206
`github_enterprise_config`, `gitlab_config`, `gitlab_enterprise_config`,
207
`bitbucket_cloud_config`, or `bitbucket_data_center_config`). If using
208
`github_config`, always set `github_app` to `"DEVELOPER_CONNECT"` (using
209
`"FIREBASE"` is incorrect and will cause triggers to fail).
210
211
```terraform
212
resource "google_developer_connect_connection" "main" {
213
location = var.region
214
connection_id = var.connection_id
215
project = var.project_id
216
217
# Example for GitHub (use gitlab_config / bitbucket_cloud_config for GitLab / Bitbucket):
218
github_config {
219
github_app = "DEVELOPER_CONNECT" # CORRECT
220
authorizer_credential {
221
oauth_token_secret_version = "" # Populated after manual authorization
222
}
223
}
224
225
depends_on = [google_project_service.main["developerconnect.googleapis.com"]]
226
227
lifecycle {
228
ignore_changes = [github_config[0].authorizer_credential]
229
}
230
}
231
```
232
233
5. **Developer Connect Git Repository Link**: When configuring
234
`google_developer_connect_git_repository_link`, use `parent_connection` and
235
`git_repository_link_id` as required arguments.
236
237
```terraform
238
resource "google_developer_connect_git_repository_link" "main" {
239
location = var.region
240
parent_connection = google_developer_connect_connection.main.connection_id
241
git_repository_link_id = "my-repo-link"
242
clone_uri = var.git_repo_uri
243
}
244
```
245
246
## 📂 Directory Structure
247
248
Follow this standard (see
249
[style-and-structure.md](references/style-and-structure.md)) to ensure
250
compatibility with Antigravity (AGY) discovery and Google best practices:
251
252
```
253
.
254
└── terraform/
255
├── main.tf # Entry point / Resource definitions
256
├── variables.tf # Typed variables with units and descriptions
257
├── outputs.tf # Resource ID outputs (no direct input pass-through)
258
├── versions.tf # Provider version pinning
259
├── network.tf # (Optional) Grouped networking resources
260
├── examples/ # Example usage for modules
261
├── files/ # Static files (startup scripts, etc.)
262
├── templates/ # .tftpl templates
263
├── scripts/ # Scripts called by Terraform
264
└── helpers/ # Scripts NOT called by Terraform
265
```
266
267
## ⚠️ Anti-Patterns (Do NOT do these)
268
269
- ❌ Legacy GitHub Triggers: Do not use the legacy `github` block in
270
`google_cloudbuild_trigger`. Always use `developer_connect_event_config`.
271
272
- ❌ Hardcoded IDs: Never hardcode Project IDs. Use variables or a
273
`data "google_project"` source.
274
275
- ❌ Service Account Keys: Never generate or store .json keys. Use Workload
276
Identity Federation or the default metadata server.
277
278
- ❌ Broad Scopes: Avoid cloud-platform scopes for GKE nodes; use fine-grained
279
IAM roles instead.
280
281
- ❌ Uppercase Types: Terraform variable types must be lowercase (e.g.,
282
`type = string` not `type = STRING`).
283
284
## 🧪 Testing Strategy
285
286
- Consult [testing-and-mocking.md](references/testing-and-mocking.md) for
287
mocked plan validation and `terraform test` patterns.
288
- Static Analysis: Use checkov, trivy, or terrascan to catch insecure GCP
289
configurations (e.g., public GCS buckets).
290
- Integration Testing: Use terraform test (v1.6+) to assert that GCP labels
291
and network tags are correctly applied to resources before full deployment.
292
293
## 📚 Reference Guides
294
295
- [naming-conventions.md](references/naming-conventions.md): Resource
296
identifier and GCP naming rules.
297
- [style-and-structure.md](references/style-and-structure.md): Module layout,
298
formatting, and variable typing standards.
299
- [iam-and-security.md](references/iam-and-security.md): Least-privilege IAM,
300
Workload Identity, and Secret Manager integration.
301
- [gcp-networking-patterns.md](references/gcp-networking-patterns.md): Custom
302
VPCs, Shared VPC, and Private Service Connect patterns.
303
- [testing-and-mocking.md](references/testing-and-mocking.md): Terraform
304
unit/integration testing (`*.tftest.hcl`) and static analysis.
305
- [troubleshooting-gcp.md](references/troubleshooting-gcp.md): Common GCP
306
Terraform errors and remediation steps.
307
308
## Resource Cleanup & Teardown
309
310
Provisioned GKE clusters, Cloud Run services, Cloud SQL instances, Artifact
311
Registry repositories, and GCS state buckets incur charges (an active billing
312
account is required even within free tiers; see
313
[Google Cloud Pricing](https://cloud.google.com/pricing)). Always generate and
314
summarize a speculative destroy plan (`terraform plan -destroy -out=tfdestroy`)
315
and obtain explicit manual confirmation from the user before running
316
`terraform apply tfdestroy` (or `gcloud projects delete <PROJECT_ID>` for
317
ephemeral sandbox projects).
318

© Google LLC · Apache 2.0 · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…