Terraform for Google Cloud Platform (GCP)¶
Overview¶
This skill provides guidance for creating and managing Google Cloud Platform (GCP) infrastructure using Terraform. It includes examples for common resources, best practices, and troubleshooting tips.
When to Use¶
Use this skill when: - Automating the setup of GCP infrastructure. - Managing existing GCP resources with Terraform. - Learning best practices for Terraform and GCP integration.
Step-by-Step Instructions¶
1. Prerequisites¶
Ensure the following are installed and configured: - Terraform - Google Cloud SDK - A GCP project with billing enabled - A service account key with appropriate permissions
2. Authenticate with GCP¶
- Create a service account in your GCP project.
- Assign the necessary roles (e.g.,
roles/editor). - Download the service account key as a JSON file.
- Set the
GOOGLE_APPLICATION_CREDENTIALSenvironment variable:
3. Initialize Terraform¶
- Create a new directory for your Terraform configuration files.
- Write a
main.tffile with the following content: - Run the following commands:
4. Create Resources¶
Add resource blocks to your main.tf file. For example, to create a Compute Engine instance:
resource "google_compute_instance" "vm_instance" {
name = "example-instance"
machine_type = "e2-medium"
zone = "us-central1-a"
boot_disk {
initialize_params {
image = "debian-cloud/debian-11"
}
}
network_interface {
network = "default"
access_config {}
}
}
5. Apply Changes¶
Run the following command to apply your configuration:
6. Manage State¶
- Use remote state storage (e.g., Google Cloud Storage) for collaboration.
- Lock state files to prevent conflicts.
Examples¶
- Compute Engine Instance: See the
google_compute_instanceexample above. - Cloud Storage Bucket:
Best Practices¶
- Use modules to organize your Terraform code.
- Secure your service account key and avoid committing it to version control.
- Regularly update your Terraform provider plugins.
Common Pitfalls¶
- Misconfigured Credentials: Ensure the
GOOGLE_APPLICATION_CREDENTIALSvariable points to the correct file. - State File Conflicts: Use remote state storage and locking mechanisms.
- Insufficient Permissions: Verify that your service account has the necessary roles.