Post

Estação de Trabalho como Código (Parte 14): Infraestrutura no GCP com Terraform

Aprenda a provisionar infraestrutura no Google Cloud Platform (GCP) usando Terraform. Este tutorial cobre configuração do gcloud CLI, criação de Service Account, projetos, redes VPC, instâncias de Compute Engine, módulos Terraform e como organizar seu código para múltiplos ambientes.

Estação de Trabalho como Código (Parte 14): Infraestrutura no GCP com Terraform

Tutorial Anterior: Estação de Trabalho como Código (Parte 13): Infraestrutura no Azure com Terraform

Introdução

O Google Cloud Platform (GCP) é o terceiro grande provedor de nuvem, conhecido por sua excelência em análise de dados, machine learning e infraestrutura de computação de alto desempenho. O GCP oferece uma abordagem moderna e intuitiva para infraestrutura em nuvem, com ferramentas poderosas como BigQuery, Cloud AI e Kubernetes Engine.

Neste tutorial, vamos aprender a provisionar infraestrutura no GCP usando Terraform, cobrindo conceitos como projetos, redes de VPC, instâncias de Compute Engine, módulos reutilizáveis e como organizar seu código para múltiplos ambientes.

Observação: Esta parte foca em Terraform (recomendado). Se preferir usar gcloud CLI manualmente, consulte a documentação oficial. No entanto, recomendamos Terraform para automação profissional.

Objetivos desta Parte

  • Instalar e configurar o gcloud CLI
  • Criar um projeto GCP e habilitar APIs necessárias
  • Criar uma Service Account para acesso via Terraform
  • Configurar o provider GCP no Terraform
  • Criar redes VPC e sub-redes
  • Provisionar instâncias de Compute Engine
  • Organizar código em módulos reutilizáveis
  • Usar variáveis para flexibilidade

Pré-requisitos

  • Conclusão da Parte 13 desta série
  • Conta GCP criada (pode usar free tier com $300 em créditos)
  • Terraform instalado (Parte 7)
  • gcloud CLI instalado (Parte 11)

A quem se destina

Este tutorial é ideal para:

  • DevOps Engineers: Que precisam provisionar infraestrutura no GCP
  • Arquitetos de Nuvem: Que querem usar IaC para GCP
  • SysAdmins: Que querem expandir para a nuvem
  • Profissionais de TI: Que querem implementar IaC em GCP

Pré-conhecimento: Conhecimento de Terraform, GCP e networking (coberto nas partes anteriores) é recomendado.

Tempo Estimado

150-180 minutos

Isso inclui:

  • Leitura e compreensão: ~25 min
  • Configuração gcloud CLI: ~15 min
  • Criação de projeto e Service Account: ~15 min
  • Criação de estrutura Terraform: ~20 min
  • Desenvolvimento de módulos: ~50 min
  • Execução e testes: ~30 min
  • Troubleshooting: ~15 min

Dica Útil: Use o free tier do GCP para experimentar sem custos. Você tem $300 em créditos de teste.


Entendendo GCP

Antes de começar, é importante entender os conceitos fundamentais.

O que é GCP?

GCP (Google Cloud Platform) é uma plataforma de computação em nuvem que oferece mais de 100 serviços diferentes. Os principais são:

  • Computação: Compute Engine, App Engine, Cloud Functions
  • Armazenamento: Cloud Storage, Cloud Firestore, Datastore
  • Banco de Dados: Cloud SQL, BigQuery, Cloud Spanner
  • Rede: VPC, Cloud Load Balancing, Cloud CDN
  • Segurança: Cloud IAM, Cloud KMS, Cloud Armor

Conceitos Principais

ConceitoDescrição
ProjectContêiner para todos os recursos GCP
RegionLocalização geográfica com múltiplos datacenters
ZoneDatacenter isolado dentro de uma região
VPCRede virtual isolada onde você executa recursos
SubnetSegmento de rede dentro de uma VPC
Compute EngineMáquina virtual no GCP
FirewallRegras para controlar tráfego
Service AccountIdentidade para automação e Terraform

Verificando Pré-Requisitos

Antes de começar, certifique-se de que seu ambiente está pronto.

Passo 1: Verificar Terraform

1
2
3
4
5
# Verifique se Terraform está instalado
$ terraform --version

# Você deve ver:
# Terraform v1.14.5

Passo 2: Verificar gcloud CLI

1
2
3
4
5
6
# Verifique se gcloud CLI está instalado
$ gcloud --version

# Você deve ver:
# Google Cloud SDK 557.0.0
# core 2026.02.17

Passo 3: Verificar Login no GCP

1
2
3
4
# Verifique se está logado no GCP
$ gcloud auth list

# Você deve ver sua conta listada

Configurando GCP

Passo 1: Instalar gcloud CLI

1
2
3
4
5
6
7
8
# Instale gcloud CLI
$ curl https://sdk.cloud.google.com | bash

# Ou use apt
$ sudo apt-get install google-cloud-sdk

# Verifique
$ gcloud --version

Passo 2: Fazer Login

1
2
3
4
5
# Faça login no GCP
$ gcloud auth login

# Você será solicitado a abrir um link e fazer login
# Siga as instruções na tela

Passo 3: Listar Projetos

1
2
3
4
# Liste seus projetos
$ gcloud projects list

# Você deve ver seus projetos listados

Criando Projeto GCP

Passo 1: Criar Projeto

1
2
3
4
5
6
7
# Crie um novo projeto
$ gcloud projects create workspace-as-code-gcp \
  --name="Workspace as Code - GCP"

# Você verá:
# Create in progress for [workspace-as-code-gcp].
# Waiting for [operations/cp.xxxxx] to finish...done.

Passo 2: Definir Projeto Padrão

1
2
3
4
5
6
7
8
# Defina o projeto como padrão
$ gcloud config set project workspace-as-code-gcp

# Verifique
$ gcloud config get-value project

# Você verá:
# workspace-as-code-gcp

Passo 3: Habilitar APIs Necessárias

1
2
3
4
5
6
7
# Habilite as APIs necessárias
$ gcloud services enable compute.googleapis.com
$ gcloud services enable servicenetworking.googleapis.com
$ gcloud services enable cloudresourcemanager.googleapis.com

# Verifique
$ gcloud services list --enabled

Criando Service Account

Passo 1: Criar Service Account

1
2
3
4
5
6
# Crie uma Service Account
$ gcloud iam service-accounts create terraform \
  --display-name="Terraform Service Account"

# Você verá:
# Created service account [terraform].

Passo 2: Criar Chave JSON

1
2
3
4
5
6
# Crie uma chave JSON para a Service Account
$ gcloud iam service-accounts keys create ~/workspace-as-code/terraform/providers/gcp/terraform-key.json \
  --iam-account=terraform@workspace-as-code-gcp.iam.gserviceaccount.com

# Você verá:
# created key [xxxxx] of type [json] as [terraform-key.json]

Passo 3: Conceder Permissões

1
2
3
4
5
6
7
# Conceda permissões de Editor à Service Account
$ gcloud projects add-iam-policy-binding workspace-as-code-gcp \
  --member="serviceAccount:terraform@workspace-as-code-gcp.iam.gserviceaccount.com" \
  --role="roles/editor"

# Você verá:
# Updated IAM policy for project [workspace-as-code-gcp].

Passo 4: Configurar Variável de Ambiente

1
2
3
4
5
6
7
8
9
10
# Configure a variável de ambiente para Terraform
$ export GOOGLE_APPLICATION_CREDENTIALS="$HOME/workspace-as-code/terraform/providers/gcp/terraform-key.json"

# Ou adicione ao ~/.bashrc para persistência
$ cat >> ~/.bashrc << 'EOF'
export GOOGLE_APPLICATION_CREDENTIALS="$HOME/workspace-as-code/terraform/providers/gcp/terraform-key.json"
EOF

# Recarregue
$ source ~/.bashrc

Criando Estrutura Terraform para GCP

Passo 1: Criar Diretórios

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Crie a estrutura de diretórios
$ mkdir -p ~/workspace-as-code/terraform/providers/gcp/{modules,environments}
$ cd ~/workspace-as-code/terraform/providers/gcp

# Estrutura esperada:
# gcp/
# ├── modules/
# │   ├── network/
# │   │   ├── main.tf
# │   │   ├── variables.tf
# │   │   └── outputs.tf
# │   ├── firewall/
# │   │   ├── main.tf
# │   │   ├── variables.tf
# │   │   └── outputs.tf
# │   └── compute/
# │       ├── main.tf
# │       ├── variables.tf
# │       └── outputs.tf
# ├── environments/
# │   ├── dev/
# │   │   ├── main.tf
# │   │   ├── terraform.tfvars
# │   │   └── backend.tf
# │   ├── staging/
# │   └── prod/
# ├── main.tf
# ├── variables.tf
# ├── outputs.tf
# └── provider.tf

Passo 2: Criar Arquivo de Provider

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Crie arquivo provider.tf
$ cat > ~/workspace-as-code/terraform/providers/gcp/provider.tf << 'EOF'
terraform {
  required_version = "~> 1.14.5"
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = "~> 5.0"
    }
  }
}

provider "google" {
  project = var.gcp_project_id
  region  = var.gcp_region
}
EOF

# Verifique
$ cat ~/workspace-as-code/terraform/providers/gcp/provider.tf

Passo 3: Criar Variáveis Principais

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# Crie arquivo variables.tf
$ cat > ~/workspace-as-code/terraform/providers/gcp/variables.tf << 'EOF'
variable "gcp_project_id" {
  description = "GCP Project ID"
  type        = string
  default     = "workspace-as-code-gcp"
}

variable "gcp_region" {
  description = "GCP region"
  type        = string
  default     = "us-central1"
}

variable "gcp_zone" {
  description = "GCP zone"
  type        = string
  default     = "us-central1-a"
}

variable "project_name" {
  description = "Project name"
  type        = string
  default     = "workspace-as-code"
}

variable "environment" {
  description = "Environment name (dev, staging, prod)"
  type        = string
  default     = "dev"
}

variable "network_cidr" {
  description = "CIDR block for VPC"
  type        = string
  default     = "10.0.0.0/16"
}

variable "subnet_cidr" {
  description = "CIDR block for subnet"
  type        = string
  default     = "10.0.1.0/24"
}

variable "machine_type" {
  description = "GCP machine type"
  type        = string
  default     = "e2-micro"
}
EOF

# Verifique
$ cat ~/workspace-as-code/terraform/providers/gcp/variables.tf

Criando Módulos Terraform

Módulo 1: Network (VPC + Subnet)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# Crie diretório do módulo
$ mkdir -p ~/workspace-as-code/terraform/providers/gcp/modules/network

# Crie arquivo main.tf
$ cat > ~/workspace-as-code/terraform/providers/gcp/modules/network/main.tf << 'EOF'
# VPC Network
resource "google_compute_network" "main" {
  name                    = "${var.project_name}-${var.environment}-vpc"
  auto_create_subnetworks = false

  depends_on = [
    google_compute_network.main
  ]
}

# Subnet
resource "google_compute_subnetwork" "main" {
  name          = "${var.project_name}-${var.environment}-subnet"
  ip_cidr_range = var.subnet_cidr
  region        = var.gcp_region
  network       = google_compute_network.main.id
}
EOF

# Crie arquivo variables.tf
$ cat > ~/workspace-as-code/terraform/providers/gcp/modules/network/variables.tf << 'EOF'
variable "project_name" {
  description = "Project name"
  type        = string
}

variable "environment" {
  description = "Environment name"
  type        = string
}

variable "gcp_region" {
  description = "GCP region"
  type        = string
}

variable "subnet_cidr" {
  description = "CIDR block for subnet"
  type        = string
}
EOF

# Crie arquivo outputs.tf
$ cat > ~/workspace-as-code/terraform/providers/gcp/modules/network/outputs.tf << 'EOF'
output "network_id" {
  description = "VPC Network ID"
  value       = google_compute_network.main.id
}

output "network_name" {
  description = "VPC Network name"
  value       = google_compute_network.main.name
}

output "subnet_id" {
  description = "Subnet ID"
  value       = google_compute_subnetwork.main.id
}

output "subnet_name" {
  description = "Subnet name"
  value       = google_compute_subnetwork.main.name
}
EOF

Módulo 2: Firewall

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# Crie diretório do módulo
$ mkdir -p ~/workspace-as-code/terraform/providers/gcp/modules/firewall

# Crie arquivo main.tf
$ cat > ~/workspace-as-code/terraform/providers/gcp/modules/firewall/main.tf << 'EOF'
# Firewall rule for SSH
resource "google_compute_firewall" "allow_ssh" {
  name    = "${var.project_name}-${var.environment}-allow-ssh"
  network = var.network_name

  allow {
    protocol = "tcp"
    ports    = ["22"]
  }

  source_ranges = ["0.0.0.0/0"]
  target_tags   = ["ssh"]
}

# Firewall rule for HTTP
resource "google_compute_firewall" "allow_http" {
  name    = "${var.project_name}-${var.environment}-allow-http"
  network = var.network_name

  allow {
    protocol = "tcp"
    ports    = ["80"]
  }

  source_ranges = ["0.0.0.0/0"]
  target_tags   = ["http"]
}

# Firewall rule for HTTPS
resource "google_compute_firewall" "allow_https" {
  name    = "${var.project_name}-${var.environment}-allow-https"
  network = var.network_name

  allow {
    protocol = "tcp"
    ports    = ["443"]
  }

  source_ranges = ["0.0.0.0/0"]
  target_tags   = ["https"]
}
EOF

# Crie arquivo variables.tf
$ cat > ~/workspace-as-code/terraform/providers/gcp/modules/firewall/variables.tf << 'EOF'
variable "project_name" {
  description = "Project name"
  type        = string
}

variable "environment" {
  description = "Environment name"
  type        = string
}

variable "network_name" {
  description = "Network name"
  type        = string
}
EOF

# Crie arquivo outputs.tf
$ cat > ~/workspace-as-code/terraform/providers/gcp/modules/firewall/outputs.tf << 'EOF'
output "ssh_rule_id" {
  description = "SSH Firewall Rule ID"
  value       = google_compute_firewall.allow_ssh.id
}

output "http_rule_id" {
  description = "HTTP Firewall Rule ID"
  value       = google_compute_firewall.allow_http.id
}

output "https_rule_id" {
  description = "HTTPS Firewall Rule ID"
  value       = google_compute_firewall.allow_https.id
}
EOF

Módulo 3: Compute Engine

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# Crie diretório do módulo
$ mkdir -p ~/workspace-as-code/terraform/providers/gcp/modules/compute

# Crie arquivo main.tf
$ cat > ~/workspace-as-code/terraform/providers/gcp/modules/compute/main.tf << 'EOF'
# Generate SSH key if not exists
resource "tls_private_key" "main" {
  algorithm = "Ed25519"
}

# Compute Engine Instance
resource "google_compute_instance" "main" {
  name         = "${var.project_name}-${var.environment}-instance"
  machine_type = var.machine_type
  zone         = var.gcp_zone

  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-12"
      size  = 20
    }
  }

  network_interface {
    network    = var.network_name
    subnetwork = var.subnet_name

    access_config {
      # Ephemeral public IP
    }
  }

  metadata = {
    ssh-keys = "debian:${tls_private_key.main.public_key_openssh}"
  }

  tags = ["ssh", "http", "https"]

  depends_on = [
    tls_private_key.main
  ]
}

# Save private key locally
resource "local_file" "private_key" {
  content         = tls_private_key.main.private_key_openssh
  filename        = "${path.module}/../../${var.project_name}-${var.environment}-key.pem"
  file_permission = "0600"
}
EOF

# Crie arquivo variables.tf
$ cat > ~/workspace-as-code/terraform/providers/gcp/modules/compute/variables.tf << 'EOF'
variable "project_name" {
  description = "Project name"
  type        = string
}

variable "environment" {
  description = "Environment name"
  type        = string
}

variable "gcp_zone" {
  description = "GCP zone"
  type        = string
}

variable "machine_type" {
  description = "GCP machine type"
  type        = string
  default     = "e2-micro"
}

variable "network_name" {
  description = "Network name"
  type        = string
}

variable "subnet_name" {
  description = "Subnet name"
  type        = string
}
EOF

# Crie arquivo outputs.tf
$ cat > ~/workspace-as-code/terraform/providers/gcp/modules/compute/outputs.tf << 'EOF'
output "instance_id" {
  description = "Compute Engine Instance ID"
  value       = google_compute_instance.main.id
}

output "instance_name" {
  description = "Compute Engine Instance name"
  value       = google_compute_instance.main.name
}

output "instance_public_ip" {
  description = "Compute Engine Instance public IP"
  value       = google_compute_instance.main.network_interface[0].access_config[0].nat_ip
}

output "instance_private_ip" {
  description = "Compute Engine Instance private IP"
  value       = google_compute_instance.main.network_interface[0].network_ip
}

output "private_key_path" {
  description = "Path to private key file"
  value       = local_file.private_key.filename
}
EOF

Criando Configuração Principal

Passo 1: Arquivo Main

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# Crie arquivo main.tf
$ cat > ~/workspace-as-code/terraform/providers/gcp/main.tf << 'EOF'
# Módulo Network
module "network" {
  source = "./modules/network"

  project_name = var.project_name
  environment  = var.environment
  gcp_region   = var.gcp_region
  subnet_cidr  = var.subnet_cidr
}

# Módulo Firewall
module "firewall" {
  source = "./modules/firewall"

  project_name = var.project_name
  environment  = var.environment
  network_name = module.network.network_name
}

# Módulo Compute
module "compute" {
  source = "./modules/compute"

  project_name = var.project_name
  environment  = var.environment
  gcp_zone     = var.gcp_zone
  machine_type = var.machine_type
  network_name = module.network.network_name
  subnet_name  = module.network.subnet_name
}
EOF

# Verifique
$ cat ~/workspace-as-code/terraform/providers/gcp/main.tf

Passo 2: Arquivo Outputs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# Crie arquivo outputs.tf
$ cat > ~/workspace-as-code/terraform/providers/gcp/outputs.tf << 'EOF'
output "network_id" {
  description = "VPC Network ID"
  value       = module.network.network_id
}

output "network_name" {
  description = "VPC Network name"
  value       = module.network.network_name
}

output "subnet_id" {
  description = "Subnet ID"
  value       = module.network.subnet_id
}

output "instance_id" {
  description = "Compute Engine Instance ID"
  value       = module.compute.instance_id
}

output "instance_name" {
  description = "Compute Engine Instance name"
  value       = module.compute.instance_name
}

output "instance_public_ip" {
  description = "Compute Engine Instance public IP"
  value       = module.compute.instance_public_ip
}

output "instance_private_ip" {
  description = "Compute Engine Instance private IP"
  value       = module.compute.instance_private_ip
}

output "private_key_path" {
  description = "Path to private key file"
  value       = module.compute.private_key_path
}
EOF

# Verifique
$ cat ~/workspace-as-code/terraform/providers/gcp/outputs.tf

Criando Ambientes

Passo 1: Ambiente Dev

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# Crie diretório do ambiente
$ mkdir -p ~/workspace-as-code/terraform/providers/gcp/environments/dev

# Crie arquivo terraform.tfvars
$ cat > ~/workspace-as-code/terraform/providers/gcp/environments/dev/terraform.tfvars << 'EOF'
gcp_project_id = "workspace-as-code-gcp"
gcp_region     = "us-central1"
gcp_zone       = "us-central1-a"
project_name   = "workspace-as-code"
environment    = "dev"
network_cidr   = "10.0.0.0/16"
subnet_cidr    = "10.0.1.0/24"
machine_type   = "e2-micro"
EOF

# Crie arquivo main.tf (referencia módulos)
$ cat > ~/workspace-as-code/terraform/providers/gcp/environments/dev/main.tf << 'EOF'
terraform {
  required_version = "~> 1.14.5"
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = "~> 5.0"
    }
  }
}

provider "google" {
  project = var.gcp_project_id
  region  = var.gcp_region
}

module "gcp_infrastructure" {
  source = "../../"

  gcp_project_id = var.gcp_project_id
  gcp_region     = var.gcp_region
  gcp_zone       = var.gcp_zone
  project_name   = var.project_name
  environment    = var.environment
  network_cidr   = var.network_cidr
  subnet_cidr    = var.subnet_cidr
  machine_type   = var.machine_type
}
EOF

# Crie arquivo variables.tf
$ cat > ~/workspace-as-code/terraform/providers/gcp/environments/dev/variables.tf << 'EOF'
variable "gcp_project_id" {
  type = string
}

variable "gcp_region" {
  type = string
}

variable "gcp_zone" {
  type = string
}

variable "project_name" {
  type = string
}

variable "environment" {
  type = string
}

variable "network_cidr" {
  type = string
}

variable "subnet_cidr" {
  type = string
}

variable "machine_type" {
  type = string
}
EOF

Executando Terraform

Passo 1: Inicializar Terraform

1
2
3
4
5
6
7
8
# Navegue para o diretório
$ cd ~/workspace-as-code/terraform/providers/gcp

# Inicialize Terraform
$ terraform init

# Você deve ver:
# Terraform has been successfully configured!

Passo 2: Validar Configuração

1
2
3
4
5
# Valide a sintaxe
$ terraform validate

# Você deve ver:
# Success! The configuration is valid.

Passo 3: Formatar Código

1
2
3
4
# Formate o código
$ terraform fmt -recursive

# Isso vai formatar todos os arquivos .tf

Passo 4: Planejar Execução

1
2
3
4
# Crie um plano
$ terraform plan -out=tfplan

# Você verá as mudanças que serão feitas

Passo 5: Aplicar Configuração

1
2
3
4
5
# Aplique o plano
$ terraform apply tfplan

# Você verá:
# Apply complete! Resources: 6 added, 0 changed, 0 destroyed.

Passo 6: Verificar Saída

1
2
3
4
5
6
7
# Veja os outputs
$ terraform output

# Você verá:
# instance_public_ip = "35.192.123.45"
# instance_private_ip = "10.0.1.2"
# ...

Acessando a Instância GCP

Passo 1: Obter IP Público

1
2
3
4
5
# Obtenha o IP público
$ terraform output instance_public_ip

# Você verá:
# "35.192.123.45"

Passo 2: Obter Caminho da Chave Privada

1
2
3
4
5
# Obtenha o caminho da chave privada
$ terraform output private_key_path

# Você verá:
# "~/workspace-as-code/terraform/providers/gcp/workspace-as-code-dev-key.pem"

Passo 3: Conectar via SSH

1
2
3
4
5
6
7
8
9
10
# Conecte à instância
$ ssh -i $(terraform output -raw private_key_path) debian@$(terraform output -raw instance_public_ip)

# Você deve ver:
# The authenticity of host '35.192.123.45 (35.192.123.45)' can't be established.
# Are you sure you want to continue connecting (yes/no)?

# Digite: yes

# Você deve estar conectado à instância

Passo 4: Verificar Instância

1
2
3
4
# Verifique informações da instância
$ uname -a
$ cat /etc/os-release
$ df -h

Tabela de Módulos Terraform

MóduloDescriçãoRecursos
networkCria VPC e subnetVPC, Subnet
firewallCria regras de firewallFirewall Rules (SSH, HTTP, HTTPS)
computeCria instânciaCompute Engine, SSH Key

Troubleshooting

Erro: “The caller does not have permission”

Problema: Service Account sem permissões ou credenciais inválidas.

Solução:

1
2
3
4
5
6
# Verifique variável de ambiente
$ echo $GOOGLE_APPLICATION_CREDENTIALS

# Ou recrie Service Account
$ gcloud iam service-accounts create terraform \
  --display-name="Terraform Service Account"

Erro: “Project not found”

Problema: Projeto não existe ou ID incorreto.

Solução:

1
2
3
4
5
6
# Liste projetos
$ gcloud projects list

# Ou crie novo projeto
$ gcloud projects create workspace-as-code-gcp \
  --name="Workspace as Code - GCP"

Erro: “API not enabled”

Problema: API necessária não está habilitada.

Solução:

1
2
3
# Habilite as APIs
$ gcloud services enable compute.googleapis.com
$ gcloud services enable servicenetworking.googleapis.com

Erro: “Quota exceeded”

Problema: Limite de recursos atingido.

Solução:

1
2
3
4
5
6
# Verifique quotas
$ gcloud compute project-info describe --project=workspace-as-code-gcp

# Ou use máquina menor
# Edite terraform.tfvars
machine_type = "e2-micro"

Instância não responde a SSH

Problema: Firewall bloqueia SSH.

Solução:

1
2
3
4
5
6
7
# Verifique regras de firewall
$ gcloud compute firewall-rules list

# Ou adicione regra manualmente
$ gcloud compute firewall-rules create allow-ssh \
  --allow=tcp:22 \
  --source-ranges=0.0.0.0/0

Dicas e Boas Práticas

Dica 1: Use Variáveis para Flexibilidade

1
2
3
4
5
6
7
8
9
# Bom
variable "machine_type" {
  default = "e2-micro"
}

# Ruim
resource "google_compute_instance" "main" {
  machine_type = "e2-micro"
}

Dica 2: Organize em Módulos

1
2
3
4
modules/
├── network/
├── firewall/
└── compute/

Dica 3: Use Outputs para Referências

1
2
3
output "instance_public_ip" {
  value = module.compute.instance_public_ip
}

Dica 4: Versione Tudo

1
2
3
$ git add .
$ git commit -m "feat: add GCP infrastructure"
$ git push origin main

Dica 5: Use Workspaces para Ambientes

1
2
3
$ terraform workspace new dev
$ terraform workspace new staging
$ terraform workspace new prod

Integrando com workspace-as-code

Passo 1: Organizar Estrutura

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Verifique a estrutura
$ tree ~/workspace-as-code/terraform/providers/gcp/

# Você deve ver:
# gcp/
# ├── modules/
# │   ├── network/
# │   ├── firewall/
# │   └── compute/
# ├── environments/
# │   └── dev/
# ├── main.tf
# ├── variables.tf
# ├── outputs.tf
# └── provider.tf

Passo 2: Versionar no Git

1
2
3
4
5
6
7
8
# Adicione ao Git
$ cd ~/workspace-as-code
$ git add terraform/providers/gcp/
$ git commit -m "feat: add GCP infrastructure with Terraform"
$ git push origin main

# Verifique
$ git log --oneline | head -5

Script de Validação

Para verificar se tudo foi configurado corretamente:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/bin/bash
# Script de validação de GCP Terraform

echo "Validando GCP Terraform..."

# Verificar gcloud CLI
if command -v gcloud &> /dev/null; then
    echo "✓ gcloud CLI instalado"
else
    echo "✗ gcloud CLI não instalado"
    exit 1
fi

# Verificar login
if gcloud auth list | grep -q "ACTIVE"; then
    echo "✓ Login GCP OK"
else
    echo "✗ Não está logado no GCP"
    exit 1
fi

# Verificar Terraform
if command -v terraform &> /dev/null; then
    echo "✓ Terraform instalado"
else
    echo "✗ Terraform não instalado"
    exit 1
fi

# Verificar estrutura
if [ -d "terraform/providers/gcp/modules" ]; then
    echo "✓ Módulos existem"
else
    echo "✗ Módulos não existem"
    exit 1
fi

# Validar Terraform
cd terraform/providers/gcp
if terraform validate &> /dev/null; then
    echo "✓ Terraform válido"
else
    echo "✗ Terraform inválido"
    exit 1
fi

echo ""
echo "Validação concluída com sucesso!"

Conclusão

Você aprendeu a provisionar infraestrutura no GCP usando Terraform. Com Terraform, você pode definir infraestrutura como código, versioná-la no Git e reutilizá-la em múltiplos ambientes.

O Que Você Alcançou

✓ Instalação e configuração do gcloud CLI ✓ Criação de projeto GCP ✓ Criação de Service Account ✓ Configuração do provider GCP no Terraform ✓ Criação de redes VPC ✓ Provisão de instâncias de Compute Engine ✓ Configuração de firewall ✓ Organização em módulos reutilizáveis ✓ Uso de variáveis para flexibilidade

Próximos Passos Imediatos

  1. Configure gcloud CLI:
    1
    
    $ gcloud auth login
    
  2. Crie projeto GCP:
    1
    
    $ gcloud projects create workspace-as-code-gcp
    
  3. Habilite APIs:
    1
    
    $ gcloud services enable compute.googleapis.com
    
  4. Crie Service Account:
    1
    
    $ gcloud iam service-accounts create terraform
    
  5. Crie estrutura Terraform:
    1
    
    $ mkdir -p ~/workspace-as-code/terraform/providers/gcp/{modules,environments}
    
  6. Crie módulos:
    1
    
    $ mkdir -p ~/workspace-as-code/terraform/providers/gcp/modules/{network,firewall,compute}
    
  7. Copie arquivos dos exemplos acima

  8. Inicialize Terraform:
    1
    2
    
    $ cd ~/workspace-as-code/terraform/providers/gcp
    $ terraform init
    
  9. Valide e aplique:
    1
    2
    3
    
    $ terraform validate
    $ terraform plan
    $ terraform apply
    
  10. Versione no Git:
    1
    2
    3
    
    $ git add terraform/
    $ git commit -m "feat: add GCP infrastructure"
    $ git push origin main
    

Próximo Tutorial

Com infraestrutura no GCP configurada, você completou a série de multi-cloud! O próximo passo é consolidar tudo o que aprendeu.


Recursos Adicionais


Fim da Parte 14

Próxima: Balanço Geral e Fechamento da Série

This post is licensed under CC BY 4.0 by the author.