Infrastructure as Code (IaC) es la práctica de gestionar y aprovisionar infraestructura de computación a través de archivos de configuración en lugar de procesos manuales.
¿Qué es IaC? IaC es el proceso de gestionar y aprovisionar infraestructura de computación a través de archivos de configuración que pueden ser versionados, reutilizados y compartidos.
Beneficios de IaC Automatización Despliegue automatizado : Infraestructura desplegada automáticamenteConsistencia : Configuración consistente entre entornosReproducibilidad : Misma infraestructura en diferentes entornosEficiencia : Reducción de tiempo de despliegueControl de Versiones Versionado : Control de versiones de infraestructuraRollback : Capacidad de revertir cambiosHistorial : Trazabilidad de cambiosColaboración : Múltiples desarrolladores trabajando juntosSeguridad Configuración segura : Configuración segura por defectoAuditoría : Trazabilidad de cambiosCompliance : Cumplimiento normativoValidación : Validación de configuraciónHerramientas de IaC Multi-cloud : Soporte para múltiples proveedoresEstado : Gestión de estado de infraestructuraPlan : Planificación de cambiosApply : Aplicación de cambiosAnsible Agentless : No requiere agentesYAML : Configuración en YAMLIdempotencia : Ejecución idempotenteOrquestación : Orquestación de tareasAWS nativo : Servicio nativo de AWSJSON/YAML : Configuración en JSON o YAMLStacks : Gestión de stacksDrift detection : Detección de desviacionesPulumi Multi-language : Múltiples lenguajes de programaciónReal-time : Actualizaciones en tiempo realTesting : Capacidades de testingCI/CD : Integración con CI/CDConfiguración Básica 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
# main.tf
provider "aws" {
region = "us-west-2"
}
resource "aws_instance" "web_server" {
ami = "ami-0c55b159cbfafe1d0"
instance_type = "t3.micro"
tags = {
Name = "Web Server"
Environment = "production"
}
}
resource "aws_security_group" "web_sg" {
name_prefix = "web-"
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0" ]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0" ]
}
}
Módulos 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
# modules/web-server/main.tf
variable "instance_type" {
description = "EC2 instance type"
type = string
default = "t3.micro"
}
variable "environment" {
description = "Environment name"
type = string
}
resource "aws_instance" "web" {
ami = data .aws_ami .ubuntu .id
instance_type = var .instance_type
tags = {
Name = "Web Server"
Environment = var .environment
}
}
# modules/web-server/outputs.tf
output "instance_id" {
description = "ID of the EC2 instance"
value = aws_instance .web .id
}
Uso de Módulos 1
2
3
4
5
6
7
# main.tf
module "web_server" {
source = "./modules/web-server"
instance_type = "t3.small"
environment = "production"
}
Ejemplo con Ansible Playbook Básico 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
# playbook.yml
---
- name : Configure web server
hosts : web_servers
become : yes
vars :
nginx_port : 80
tasks :
- name : Install nginx
package :
name : nginx
state : present
- name : Start nginx
service :
name : nginx
state : started
enabled : yes
- name : Configure nginx
template :
src : nginx.conf.j2
dest : /etc/nginx/nginx.conf
notify : restart nginx
handlers :
- name : restart nginx
service :
name : nginx
state : restarted
Inventario 1
2
3
4
5
6
7
# inventory.ini
[web_servers]
web1 ansible_host = 10.0.1.10
web2 ansible_host = 10.0.1.11
[db_servers]
db1 ansible_host = 10.0.2.10
Seguridad en IaC Configuración Segura 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Configuración segura de S3
resource "aws_s3_bucket" "secure_bucket" {
bucket = "my-secure-bucket"
versioning {
enabled = true
}
server_side_encryption_configuration {
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "AES256"
}
}
}
public_access_block {
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
}
Gestión de Secretos 1
2
3
4
5
6
7
8
9
10
# Uso de secretos
resource "aws_db_instance" "database" {
identifier = "my-database"
engine = "mysql"
username = var .db_username
password = var .db_password
vpc_security_group_ids = [aws_security_group .db .id ]
}
Validación 1
2
3
4
5
6
7
8
9
10
# Validación de entrada
variable "instance_type" {
description = "EC2 instance type"
type = string
validation {
condition = contains (["t3.micro", "t3.small", "t3.medium" ], var .instance_type )
error_message = "Instance type must be t3.micro, t3.small, or t3.medium."
}
}
Mejores Prácticas Estructura de Proyecto project/
├── main.tf
├── variables.tf
├── outputs.tf
├── terraform.tfvars
├── modules/
│ └── web-server/
│ ├── main.tf
│ ├── variables.tf
│ └── outputs.tf
└── environments/
├── dev/
├── staging/
└── production/Versionado Git : Usar Git para control de versionesTags : Etiquetar versionesBranches : Usar ramas para diferentes entornosCommits : Mensajes de commit descriptivosTesting Unit tests : Pruebas unitariasIntegration tests : Pruebas de integraciónSecurity tests : Pruebas de seguridadCompliance tests : Pruebas de cumplimientoCI/CD 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# .github/workflows/terraform.yml
name : Terraform
on :
push :
branches : [main]
jobs :
terraform :
runs-on : ubuntu-latest
steps :
- uses : actions/checkout@v2
- name : Setup Terraform
uses : hashicorp/setup-terraform@v1
- name : Terraform Init
run : terraform init
- name : Terraform Plan
run : terraform plan
- name : Terraform Apply
run : terraform apply -auto-approve
Monitoreo y Auditoría Logs Terraform logs : Logs de ejecuciónCloud logs : Logs de proveedores cloudApplication logs : Logs de aplicacionesSecurity logs : Logs de seguridadMétricas Deployment time : Tiempo de despliegueSuccess rate : Tasa de éxitoError rate : Tasa de erroresResource usage : Uso de recursosAlertas Deployment failures : Fallos de despliegueConfiguration drift : Desviaciones de configuraciónSecurity issues : Problemas de seguridadPerformance issues : Problemas de rendimientoConceptos Relacionados DevOps - Metodología que incluye IaCSecOps - Operaciones de seguridad con IaCCloud Security - Seguridad en la nube con IaCGitLab - Plataforma que gestiona IaCContainer Management - Gestión de contenedores con IaCCSPM - Gestión de postura de seguridad en la nubeSIEM - Monitoreo de infraestructura IaCSOAR - Automatización de IaCRegistros - Logs de infraestructura IaCDashboards - Visualización de infraestructura IaCMétricas - Medición de infraestructura IaCCISO - Rol que supervisa IaCReferencias