Skip to content

DevOps

Git Workflows: GitFlow vs GitHub Flow vs Trunk-Based vs Release Flow

Resumen

Existen múltiples estrategias de branching Git para gestionar el desarrollo de software: GitFlow (modelo complejo con develop/feature/release/hotfix branches para equipos grandes), GitHub Flow (minimalista con feature branches + main + deploy before merge), GitLab Flow (híbrido con environment branches staging/production para control deployment), Trunk-Based Development (commits directos a main con short-lived branches <24h, usado por Google/Facebook), Release Flow (trunk-based + release branches sin merge back, usado por Microsoft Azure), OneFlow (GitFlow simplificado eliminando develop branch), y Feature Branch Workflow (básico con feature branches + pull requests). Cada estrategia se adapta a diferentes tamaños de equipo, frecuencia de releases, madurez CI/CD y control de environments.

Terraform: Uso de Variables y Secrets de GitHub

Resumen

Cómo usar variables y secrets de GitHub en despliegues con Terraform para Azure. Ejemplo práctico y buenas prácticas para admins y DevOps que quieren CI/CD seguro y reproducible.

¿Qué problema resuelve?

Permite gestionar credenciales y parámetros sensibles (como client secrets, IDs, claves) de forma segura en pipelines de GitHub Actions, evitando exponerlos en el código fuente.

¿Qué es y cómo funciona?

  • Secrets: Valores cifrados almacenados en GitHub (por repo o por entorno). Ej: credenciales Azure, claves API.
  • Variables de configuración: Valores no sensibles, útiles para parámetros de entorno, nombres, ubicaciones, flags, etc. Se gestionan en Settings → Secrets and variables → Actions → Variables.
  • Los workflows de GitHub Actions pueden acceder a estos valores como variables de entorno.
  • Terraform puede consumirlos usando la sintaxis ${{ secrets.SECRET_NAME }} para secrets y ${{ vars.VAR_NAME }} para variables de configuración en el workflow.

Ejemplo sencillo: despliegue de Azure Resource Group con variables y secrets

1. Añadir secrets en GitHub

  • Ve a tu repo → Settings → Secrets and variables → Actions
  • Añade los secrets:
  • AZURE_CLIENT_ID
  • AZURE_TENANT_ID
  • AZURE_SUBSCRIPTION_ID

2. Añadir variables de configuración (no sensibles)

  • Ejemplo: RG_NAME, LOCATION

3. Workflow de GitHub Actions (.github/workflows/terraform.yml)

name: 'Terraform Azure'
on:
  push:
    branches: [ main ]

---
  deploy:
    runs-on: ubuntu-latest
    env:
      # Recomendado: Federated Identity (OIDC) - no uses client secret
      ARM_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
      ARM_SUBSCRIPTION_ID: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
      ARM_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
      TF_VAR_rg_name: ${{ vars.RG_NAME }}
      TF_VAR_location: ${{ vars.LOCATION }}
    steps:
      - uses: actions/checkout@v4
      - name: Setup Terraform
        uses: hashicorp/setup-terraform@v3
      - name: Terraform Init
        run: terraform init
      - name: Terraform Plan
        run: terraform plan
      - name: Terraform Apply
        run: terraform apply -auto-approve

En este ejemplo, RG_NAME y LOCATION son variables de configuración definidas en GitHub (no secrets) y se pasan automáticamente como variables de entrada a Terraform usando el prefijo TF_VAR_.

4. Código Terraform (main.tf)

provider "azurerm" {
  features {}
}

variable "rg_name" {
  description = "Nombre del resource group"
  type        = string
}

variable "location" {
  description = "Ubicación Azure"
  type        = string
}

resource "azurerm_resource_group" "ejemplo" {
  name     = var.rg_name
  location = var.location
}

Objetos complejos y versiones recientes de Terraform

Desde Terraform 1.3 en adelante, puedes pasar mapas y listas directamente como variables de entorno usando el prefijo TF_VAR_, sin necesidad de jsonencode/jsondecode. Terraform los interpreta automáticamente si el valor es un JSON válido.

Ejemplo directo (Terraform >= 1.3)

env:
  TF_VAR_tags: '{"env":"prod","owner":"devops"}'
variable "tags" {
  type = map(string)
}

resource "azurerm_resource_group" "ejemplo" {
  name     = var.rg_name
  location = var.location
  tags     = var.tags
}
No necesitas usar jsondecode() si la variable ya es del tipo adecuado y el valor es JSON válido.

¿Y si necesitas un objeto complejo y usas versiones antiguas?

Si necesitas pasar un objeto complejo (por ejemplo, un mapa o lista de objetos) y tu versión de Terraform es anterior a 1.3, lo más habitual es usar un secret o variable en formato JSON y parsearlo en Terraform.

env:
  TF_VAR_tags_json: ${{ secrets.TAGS_JSON }}
variable "tags_json" {
  description = "Tags en formato JSON"
  type        = string
}

locals {
  tags = jsondecode(var.tags_json)
}

resource "azurerm_resource_group" "ejemplo" {
  name     = var.rg_name
  location = var.location
  tags     = local.tags
}
Así puedes pasar cualquier estructura compleja (mapas, listas, objetos anidados) como string JSON y usar jsondecode() en Terraform para convertirlo a un tipo nativo. draft: false date: 2025-10-23 authors:

  • rfernandezdo categories:

  • DevOps

  • Terraform
  • GitHub Actions tags:

  • Terraform

  • GitHub Secrets
  • Azure

Buenas prácticas

  • Usa federated identity (OIDC) siempre que sea posible, evita client secrets.
  • Nunca subas secrets al repo ni los hardcodees en el código.
  • Usa GitHub Environments para separar prod/dev y limitar acceso a secrets.
  • Usa variables para parámetros no sensibles (ej: nombres, ubicaciones).
  • Valida siempre con terraform validate antes de aplicar.
  • Rota los secrets periódicamente si usas client secrets legacy.

Referencias

Cómo Resolver Divergencias en Git: Sincronizando Ramas Local y Remota

El Problema

Al intentar hacer git pull, te encuentras con el siguiente error:

hint: You have divergent branches and need to specify how to reconcile them.
hint: You can do so by running one of the following commands sometime before
hint: your next pull:
hint:
hint:   git config pull.rebase false  # merge
hint:   git config pull.rebase true   # rebase
hint:   git config pull.ff only       # fast-forward only

Este mensaje indica que tu rama local y la rama remota han divergido: ambas tienen commits únicos que la otra no tiene. Git necesita que decidas cómo combinar estos cambios.

¿Por Qué Ocurre?

La divergencia sucede cuando:

  1. Trabajas localmente y realizas commits en tu rama main
  2. Mientras tanto, cambios se fusionan en el remoto (por ejemplo, a través de Pull Requests)
  3. Ambas ramas tienen commits exclusivos que la otra no posee

Ejemplo visual:

Local:   A---B---C---L1
                      ^(tu commit local)
Remote:  A---B---C---R1---R2---R3
                      ^(commits del remoto vía PR)

Análisis: Identificar la Divergencia

Antes de resolver, es crucial entender qué ha divergido.

Paso 1: Sincronizar con el Remoto

git fetch origin main --tags

Este comando descarga los cambios del remoto sin fusionarlos.

Paso 2: Comparar Commits

Verifica qué commits están únicamente en cada lado:

# Commits que tienes localmente pero no están en el remoto
git log origin/main..main --oneline

# Commits que están en el remoto pero no tienes localmente
git log main..origin/main --oneline

Paso 3: Revisar los HEADs

# Ver el commit actual local
git rev-parse HEAD

# Ver el commit actual remoto
git rev-parse origin/main

Ejemplo Real

En nuestro caso, obtuvimos:

--- Commits en local, no en remoto ---
81e3b93 feat: add new feature for data processing

--- Commits en remoto, no en local ---
9d3e3e9 Merge pull request #42 from team/feature/update-docs
285a538 Complete documentation review - all documents validated
000b9cb Fix configuration and add new parameters
a7694d3 Initial implementation plan

Interpretación: El remoto tiene un PR fusionado con 4 commits que no tenemos localmente, y nosotros tenemos 1 commit local que el remoto no tiene.

Estrategias de Resolución

Existen tres estrategias principales:

1. Merge (Recomendado para Trabajo Colaborativo)

Cuándo usarlo: Cuando trabajas con un equipo y quieres preservar toda la historia, incluyendo los merge commits de PRs.

Ventajas:

  • ✅ Preserva la historia completa (incluidos merge commits)
  • ✅ Muestra claramente cuándo se integraron features
  • ✅ Más seguro: no reescribe historia

Desventajas:

  • ⚠️ Crea un commit de merge adicional
  • ⚠️ Historia no completamente lineal

Comando:

git merge origin/main --no-edit

Si prefieres revisar/editar el mensaje de merge:

git merge origin/main

2. Rebase (Para Historia Lineal)

Cuándo usarlo: Cuando trabajas solo o en una feature branch que aún no has compartido públicamente.

Ventajas:

  • ✅ Historia completamente lineal
  • ✅ Más limpia para revisar con git log

Desventajas:

  • ⚠️ Reescribe commits locales (cambian sus SHAs)
  • ⚠️ Puede causar problemas si ya compartiste estos commits
  • ⚠️ Pierdes el contexto de cuándo se integró el PR remoto

Comando:

git rebase origin/main

3. Fast-Forward Only (Restrictivo)

Cuándo usarlo: Cuando quieres asegurarte de que solo hagas pull si no hay divergencia.

Comando:

git config pull.ff only
git pull

Si hay divergencia, fallará y tendrás que decidir merge o rebase manualmente.

Solución Paso a Paso (Merge)

1. Analizar la Situación

# Sincronizar con remoto
git fetch origin main --tags

# Ver divergencias
echo "--- Commits locales únicos ---"
git log origin/main..main --oneline

echo "--- Commits remotos únicos ---"
git log main..origin/main --oneline

2. Decidir Estrategia

Para equipos colaborativos con PRs, merge es la opción más segura:

git merge origin/main --no-edit

3. Resolver Conflictos (Si Ocurren)

Si hay conflictos, Git te lo indicará:

Auto-merging some-file.md
CONFLICT (content): Merge conflict in some-file.md
Automatic merge failed; fix conflicts and then commit the result.

Pasos para resolver:

a) Abre el archivo con conflictos:

<<<<<<< HEAD
Tu versión local
=======
Versión del remoto
>>>>>>> origin/main

b) Edita manualmente para quedarte con el contenido correcto

c) Marca como resuelto:

git add some-file.md

d) Completa el merge:

git commit -m "Merge origin/main into main"

4. Verificar el Resultado

# Ver el log reciente
git log --oneline --graph -10

Deberías ver algo como:

*   3e1ed57 (HEAD -> main) Merge remote-tracking branch 'origin/main' into main
|\
| * 9d3e3e9 (origin/main) Merge pull request #42
| * 285a538 Complete documentation review
| * 000b9cb Fix configuration parameters
| * a7694d3 Initial implementation plan
* | 81e3b93 feat: add new feature for data processing
|/
* d140dce feat: improved monthly workflow

5. Empujar los Cambios

git push origin main

Salida esperada:

Enumerating objects: 15, done.
Counting objects: 100% (12/12), done.
Delta compression using up to 8 threads
Compressing objects: 100% (7/7), done.
Writing objects: 100% (7/7), 1.08 KiB | 1.08 MiB/s, done.
Total 7 (delta 5), reused 0 (delta 0)
remote: Resolving deltas: 100% (5/5), completed with 4 local objects.
To https://github.com/tu-usuario/tu-repositorio.git
   9d3e3e9..3e1ed57  main -> main

Verificación Post-Merge

Comprobar Archivos Críticos

Si tienes workflows de CI/CD u otros archivos críticos, verifica su integridad:

# Buscar un patrón específico en un archivo
grep -n "specific_pattern" .github/workflows/deploy.yml

# O leer el archivo completo
cat .github/workflows/deploy.yml

Confirmar Sincronización

# Ambos deberían apuntar al mismo commit ahora
git rev-parse HEAD
git rev-parse origin/main

Configuración Permanente

Si quieres establecer una estrategia por defecto para futuros git pull:

Para Merge (Recomendado)

git config pull.rebase false

Para Rebase

git config pull.rebase true

Global (Todos tus Repos)

Añade --global:

git config --global pull.rebase false

Mejores Prácticas

✅ Hacer Fetch Frecuentemente

# Ejecutar cada mañana o antes de empezar a trabajar
git fetch origin

Esto te mantiene informado de cambios remotos sin afectar tu trabajo local.

✅ Trabajar en Feature Branches

En lugar de trabajar directamente en main:

git checkout -b feature/my-feature
# ... hacer commits ...
git push origin feature/my-feature
# Abrir PR en GitHub

Esto evita divergencias en main.

✅ Pull Antes de Push

git fetch origin
git status
# Si hay cambios remotos, decide merge o rebase
git pull
# Ahora puedes pushear
git push

⚠️ Evitar Force Push en Ramas Compartidas

# ❌ NUNCA en main compartido
git push --force origin main

# ✅ OK solo en tus feature branches
git push --force origin feature/my-feature

Casos Especiales

Si Hiciste Rebase por Error y Quieres Revertir

# Ver el reflog (historial de cambios de HEAD)
git reflog

# Volver a un estado anterior
git reset --hard HEAD@{2}

Si Quieres Descartar Tus Commits Locales

# ⚠️ CUIDADO: Esto descarta tus commits locales permanentemente
git reset --hard origin/main

Si Quieres Preservar Cambios Locales Sin Commit

# Guardar cambios temporalmente
git stash

# Sincronizar con remoto
git pull

# Recuperar tus cambios
git stash pop

Resumen: Checklist Rápido

  • Fetch: git fetch origin main --tags
  • Analizar: git log origin/main..main --oneline y git log main..origin/main --oneline
  • Decidir: Merge (preservar historia) vs Rebase (lineal)
  • Ejecutar: git merge origin/main o git rebase origin/main
  • Resolver: Conflictos si los hay
  • Verificar: git log --graph --oneline -10
  • Push: git push origin main
  • Confirmar: Archivos críticos intactos

Conclusión

La divergencia de ramas es un escenario común en equipos colaborativos. La clave está en:

  1. Entender qué ha divergido (análisis con git log)
  2. Elegir la estrategia correcta (merge para equipos, rebase para trabajo local)
  3. Verificar el resultado antes de hacer push

En entornos colaborativos con Pull Requests, merge es generalmente la opción más segura ya que preserva la historia completa y evita reescribir commits que otros pueden estar usando como base.


Referencias

Azure Bicep avanzado: testing, linting y despliegue seguro multi-entorno

Resumen

Bicep permite IaC declarativo en Azure, pero en producción necesitas testing, linting y despliegue seguro por entorno. Este post va al grano: cómo testear plantillas, usar linting, parametrizar para dev/prod y evitar errores comunes.

¿Qué es Bicep avanzado?

  • Modularización y reutilización
  • Testing de plantillas antes de deploy
  • Linting para calidad y seguridad
  • Parametrización por entorno (dev, prod, test)
  • Integración con pipelines CI/CD

Arquitectura / Cómo funciona

flowchart LR
    Dev[Dev] --> CI[CI Pipeline]
    CI --> Lint[Lint]
    CI --> Test[Test]
    CI --> Deploy[Deploy]
    Deploy --> Azure[Azure]
    Azure --> RG1[Resource Group Dev]
    Azure --> RG2[Resource Group Prod]

Testing de plantillas Bicep

  1. Validar sintaxis:
    bicep build main.bicep
    
  2. Test de despliegue (dry-run):
    az deployment sub validate \
      --location westeurope \
      --template-file main.bicep \
      --parameters environment="dev"
    
  3. Test unitario con PSRule for Azure:
    pwsh -c "Invoke-PSRule -Path ./main.bicep"
    

Linting y calidad

  • Usar bicep linter:
    bicep build main.bicep
    bicep linter main.bicep
    
  • Reglas custom en .bicepconfig.json:
    {
      "analyzers": {
        "core": {
          "rules": {
            "no-hardcoded-secrets": "warning",
            "secure-parameters": "error"
          }
        }
      }
    }
    

Parametrización multi-entorno

  • Usar parámetros y archivos por entorno:
    az deployment group create \
      --resource-group rg-dev \
      --template-file main.bicep \
      --parameters @dev.parameters.json
    az deployment group create \
      --resource-group rg-prod \
      --template-file main.bicep \
      --parameters @prod.parameters.json
    
  • Ejemplo de parámetros:
    {
      "environment": {"value": "dev"},
      "adminPassword": {"value": "SuperSecret123!"}
    }
    

Integración CI/CD

  • Pipeline YAML ejemplo:
    trigger:
      - main
    pool:
      vmImage: 'ubuntu-latest'
    steps:
      - script: bicep build main.bicep
        displayName: 'Build Bicep'
      - script: bicep linter main.bicep
        displayName: 'Lint Bicep'
      - script: pwsh -c "Invoke-PSRule -Path ./main.bicep"
        displayName: 'Test Bicep'
      - script: az deployment group create --resource-group rg-dev --template-file main.bicep --parameters @dev.parameters.json
        displayName: 'Deploy Dev'
    

Buenas prácticas

  • Nunca hardcodear secretos en plantillas
  • Usar Key Vault para parámetros sensibles
  • Validar y testear antes de cada despliegue
  • Mantener módulos reutilizables y versionados
  • Revisar resultados de linting y testing en cada PR

Costes

  • Bicep: gratis
  • PSRule: gratis
  • Azure DevOps: desde $0 (hasta 1,800 min/mes)

Referencias

Azure DevOps: YAML templates reutilizables

Resumen

Templates eliminan código duplicado en pipelines. template parameters, extends y multistage.

Introducción

[Contenido técnico detallado a desarrollar]

Configuración básica

# Comandos de ejemplo
RG="my-rg"
LOCATION="westeurope"

# Comandos Azure CLI
az group create --name $RG --location $LOCATION

Casos de uso

  • Caso 1: [Descripción]
  • Caso 2: [Descripción]
  • Caso 3: [Descripción]

Buenas prácticas

  • Práctica 1: Descripción
  • Práctica 2: Descripción
  • Práctica 3: Descripción

Monitoreo y troubleshooting

# Comandos de diagnóstico
az monitor metrics list --resource ...

Referencias

GitHub Actions: Deploy a Azure con Workload Identity Federation

Resumen

Olv

ídate de guardar service principal secrets en GitHub. Con Workload Identity Federation, GitHub Actions se autentica a Azure sin credenciales almacenadas. Más seguro y cero rotación de secrets.

¿Qué es Workload Identity Federation?

Permite que GitHub Actions obtenga un access token de Azure usando OIDC (OpenID Connect). Azure confía en los tokens de GitHub basándose en: - Repositorio específico - Branch específico - Environment específico

Setup completo

1. Crear service principal

# Variables
APP_NAME="github-actions-federation"
RG="my-rg"
SUBSCRIPTION_ID=$(az account show --query id -o tsv)

# Crear app registration
APP_ID=$(az ad app create \
  --display-name $APP_NAME \
  --query appId -o tsv)

# Crear service principal
az ad sp create --id $APP_ID

SP_OBJECT_ID=$(az ad sp show --id $APP_ID --query id -o tsv)

# Asignar rol Contributor
az role assignment create \
  --role Contributor \
  --assignee $APP_ID \
  --scope /subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RG

2. Configurar Federated Credential

# Para branch main
az ad app federated-credential create \
  --id $APP_ID \
  --parameters '{
    "name": "github-main-branch",
    "issuer": "https://token.actions.githubusercontent.com",
    "subject": "repo:myorg/myrepo:ref:refs/heads/main",
    "description": "GitHub Actions - main branch",
    "audiences": ["api://AzureADTokenExchange"]
  }'

# Para environment production
az ad app federated-credential create \
  --id $APP_ID \
  --parameters '{
    "name": "github-prod-environment",
    "issuer": "https://token.actions.githubusercontent.com",
    "subject": "repo:myorg/myrepo:environment:production",
    "description": "GitHub Actions - production environment",
    "audiences": ["api://AzureADTokenExchange"]
  }'

# Para pull requests
az ad app federated-credential create \
  --id $APP_ID \
  --parameters '{
    "name": "github-pull-requests",
    "issuer": "https://token.actions.githubusercontent.com",
    "subject": "repo:myorg/myrepo:pull_request",
    "description": "GitHub Actions - pull requests",
    "audiences": ["api://AzureADTokenExchange"]
  }'

3. Configurar GitHub Secrets

En tu repositorio → Settings → Secrets:

AZURE_CLIENT_ID = {APP_ID}
AZURE_TENANT_ID = {TENANT_ID}
AZURE_SUBSCRIPTION_ID = {SUBSCRIPTION_ID}

4. GitHub Actions Workflow

.github/workflows/deploy.yml:

name: Deploy to Azure

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

permissions:
  id-token: write  # Required for OIDC
  contents: read

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: production  # Si usas federated credential por environment

    steps:
      - uses: actions/checkout@v4

      - name: Azure Login with OIDC
        uses: azure/login@v1
        with:
          client-id: ${{ secrets.AZURE_CLIENT_ID }}
          tenant-id: ${{ secrets.AZURE_TENANT_ID }}
          subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}

      - name: Deploy to Azure Web App
        uses: azure/webapps-deploy@v2
        with:
          app-name: my-web-app
          package: ./dist

      - name: Azure CLI commands
        run: |
          az group list
          az webapp list --resource-group ${{ env.RG }}

Ventajas vs Service Principal Secrets

Aspecto Service Principal Secret Workload Identity
Secrets en GitHub Sí (password) No (solo IDs)
Rotación Manual cada 90 días Automática
Scope Amplio Granular (repo/branch/env)
Audit trail Limitado Completo (OIDC claims)
Expiración Hasta 2 años Token expira en minutos

Debugging

- name: Debug OIDC Token
  run: |
    curl -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
         "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=api://AzureADTokenExchange" \
         | jq -R 'split(".") | .[1] | @base64d | fromjson'

Claims del token:

{
  "iss": "https://token.actions.githubusercontent.com",
  "sub": "repo:myorg/myrepo:ref:refs/heads/main",
  "aud": "api://AzureADTokenExchange",
  "ref": "refs/heads/main",
  "sha": "abc123...",
  "repository": "myorg/myrepo",
  "repository_owner": "myorg",
  "run_id": "123456789",
  "workflow": "Deploy to Azure"
}

Buenas prácticas

  • Usa environments: Requiere aprobaciones manuales para producción
  • Scope mínimo: Asigna roles solo al resource group necesario
  • Multiple credentials: Diferentes para dev/staging/prod
  • Branch protection: Solo permite deploy desde branches protegidos
  • Audit logs: Revisa sign-in logs en Azure AD regularmente

Referencias

Terraform Backend en Azure Storage: Setup completo

Resumen

Guardar el estado de Terraform en local es peligroso y no escala. Azure Storage con state locking es la solución estándar para equipos. Aquí el setup completo en 5 minutos.

¿Por qué usar remote backend?

Problemas con backend local: - ❌ Estado se pierde si borras tu laptop - ❌ Imposible colaborar en equipo - ❌ No hay locking → corrupciones en despliegues simultáneos - ❌ Secretos en plaintext en disco local

Ventajas con Azure Storage: - ✅ Estado centralizado y versionado - ✅ Locking automático con blob lease - ✅ Encriptación at-rest - ✅ Acceso controlado con RBAC

Setup del backend

1. Crear Storage Account

# Variables
RG="terraform-state-rg"
LOCATION="westeurope"
STORAGE_ACCOUNT="tfstate$(date +%s)"  # Nombre único
CONTAINER="tfstate"

# Crear resource group
az group create \
  --name $RG \
  --location $LOCATION

# Crear storage account
az storage account create \
  --name $STORAGE_ACCOUNT \
  --resource-group $RG \
  --location $LOCATION \
  --sku Standard_LRS \
  --encryption-services blob \
  --min-tls-version TLS1_2

# Crear container
az storage container create \
  --name $CONTAINER \
  --account-name $STORAGE_ACCOUNT \
  --auth-mode login

Naming convention

Storage account solo acepta lowercase y números, máximo 24 caracteres. Usa un sufijo único para evitar colisiones.

2. Configurar backend en Terraform

backend.tf:

terraform {
  backend "azurerm" {
    resource_group_name  = "terraform-state-rg"
    storage_account_name = "tfstate1234567890"
    container_name       = "tfstate"
    key                  = "prod.terraform.tfstate"
  }
}

3. Inicializar

# Login a Azure
az login

# Inicializar backend
terraform init

# Migrar estado existente (si aplica)
terraform init -migrate-state

State locking

Azure usa blob leases para locking automático:

# Ver si hay lock activo
az storage blob show \
  --container-name $CONTAINER \
  --name prod.terraform.tfstate \
  --account-name $STORAGE_ACCOUNT \
  --query "properties.lease.status"

Si alguien está ejecutando terraform apply, verás:

"locked"

Multi-entorno con workspaces

# Crear workspace por entorno
terraform workspace new dev
terraform workspace new staging  
terraform workspace new prod

# Listar workspaces
terraform workspace list

# Cambiar entre entornos
terraform workspace select prod

Cada workspace crea su propio state file:

prod.terraform.tfstate
dev.terraform.tfstate
staging.terraform.tfstate

Seguridad: Managed Identity

Evita usar access keys en pipelines:

# Crear managed identity
az identity create \
  --resource-group $RG \
  --name terraform-identity

# Asignar rol Storage Blob Data Contributor
IDENTITY_ID=$(az identity show \
  --resource-group $RG \
  --name terraform-identity \
  --query principalId -o tsv)

az role assignment create \
  --role "Storage Blob Data Contributor" \
  --assignee $IDENTITY_ID \
  --scope /subscriptions/{sub-id}/resourceGroups/$RG/providers/Microsoft.Storage/storageAccounts/$STORAGE_ACCOUNT

Backend config con managed identity:

terraform {
  backend "azurerm" {
    resource_group_name  = "terraform-state-rg"
    storage_account_name = "tfstate1234567890"
    container_name       = "tfstate"
    key                  = "prod.terraform.tfstate"
    use_msi              = true
    subscription_id      = "00000000-0000-0000-0000-000000000000"
    tenant_id            = "00000000-0000-0000-0000-000000000000"
  }
}

Versionado del estado

# Habilitar versioning en el container
az storage blob service-properties update \
  --account-name $STORAGE_ACCOUNT \
  --enable-versioning true

# Ver versiones anteriores
az storage blob list \
  --container-name $CONTAINER \
  --account-name $STORAGE_ACCOUNT \
  --include v \
  --query "[?name=='prod.terraform.tfstate'].{Version:versionId, LastModified:properties.lastModified}"

Pipeline CI/CD con Azure DevOps

azure-pipelines.yml:

trigger:
  - main

pool:
  vmImage: 'ubuntu-latest'

variables:
  - group: terraform-variables

stages:
  - stage: Plan
    jobs:
      - job: TerraformPlan
        steps:
          - task: AzureCLI@2
            displayName: 'Terraform Init & Plan'
            inputs:
              azureSubscription: 'Azure Service Connection'
              scriptType: 'bash'
              scriptLocation: 'inlineScript'
              inlineScript: |
                terraform init
                terraform plan -out=tfplan

          - publish: '$(System.DefaultWorkingDirectory)/tfplan'
            artifact: tfplan

  - stage: Apply
    dependsOn: Plan
    condition: succeeded()
    jobs:
      - deployment: TerraformApply
        environment: 'production'
        strategy:
          runOnce:
            deploy:
              steps:
                - download: current
                  artifact: tfplan

                - task: AzureCLI@2
                  displayName: 'Terraform Apply'
                  inputs:
                    azureSubscription: 'Azure Service Connection'
                    scriptType: 'bash'
                    scriptLocation: 'inlineScript'
                    inlineScript: |
                      terraform init
                      terraform apply tfplan

Troubleshooting

Error: "Failed to lock state"

# Forzar unlock (solo si estás seguro)
terraform force-unlock <LOCK_ID>

# O romper lease manualmente
az storage blob lease break \
  --container-name $CONTAINER \
  --blob-name prod.terraform.tfstate \
  --account-name $STORAGE_ACCOUNT

Error: "storage account not found"

# Verificar permisos
az storage account show \
  --name $STORAGE_ACCOUNT \
  --resource-group $RG

Buenas prácticas

  • State file por proyecto: No mezcles infraestructuras diferentes
  • Soft delete: Habilita soft delete en storage account
  • Network security: Restringe acceso desde VNet específicas
  • Audit logs: Habilita diagnostic settings para compliance
  • Backup externo: Exporta estados críticos a otro storage account

Never commit state files

Añade *.tfstate* a .gitignore. El state contiene secretos en plaintext.

Referencias

terraform import block

Sometimes you need to import existing infrastructure into Terraform. This is useful when you have existing resources that you want to manage with Terraform, or when you want to migrate from another tool to Terraform.

Other times, you may need to import resources that were created outside of Terraform, such as manually created resources or resources created by another tool. For example:

"Error: unexpected status 409 (409 Conflict) with error: RoleDefinitionWithSameNameExists: A custom role with the same name already exists in this directory. Use a different name"

In my case, I had to import a custom role that was created outside of Terraform. Here's how I did it:

  1. Create a new Terraform configuration file for the resource you want to import. In my case, I created a new file called custom_role.tf with the following content:
resource "azurerm_role_definition" "custom_role" {
  name        = "CustomRole"
  scope       = "/providers/Microsoft.Management/managementGroups/00000000-0000-0000-0000-000000000000"
  permissions {
    actions     = [
      "Microsoft.Storage/storageAccounts/listKeys/action",
      "Microsoft.Storage/storageAccounts/read"
    ]

    data_actions = []

    not_data_actions = []
  }
  assignable_scopes = [
    "/providers/Microsoft.Management/managementGroups/00000000-0000-0000-0000-000000000000"
  ]
}
  1. Add a import block to the configuration file with the resource type and name you want to import. In my case, I added the following block to the custom_role.tf file:
import {
  to = azurerm_role_definition.custom_role
  id = "/providers/Microsoft.Authorization/roleDefinitions/11111111-1111-1111-1111-111111111111|/providers/Microsoft.Management/managementGroups/00000000-0000-0000-0000-000000000000"

}
  1. Run the terraformplan` command to see the changes that Terraform will make to the resource. In my case, the output looked like this:
.
.
.
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  ~ update in-place
.
.
.
  1. Run the terraform apply command to import the resource into Terraform. In my case, the output looked like this after a long 9 minutes:
...
Apply complete! Resources: 1 imported, 0 added, 1 changed, 0 destroyed.
  1. Verify that the resource was imported successfully by running the terraform show command. In my case, the output looked like this:
terraform show

You can use the terraform import command to import existing infrastructure into Terraform too but I prefer to use the import block because it's more readable and easier to manage.

With terraform import the command would look like this:

terraform import azurerm_role_definition.custom_role "/providers/Microsoft.Authorization/roleDefinitions/11111111-1111-1111-1111-111111111111|/providers/Microsoft.Management/managementGroups/00000000-0000-0000-0000-000000000000"

Conclusion

That's it! You've successfully imported an existing resource into Terraform. Now you can manage it with Terraform just like any other resource.

Happy coding! 🚀

markmap

markmap is a visualisation tool that allows you to create mindmaps from markdown files. It is based on the mermaid library and can be used to create a visual representation of a markdown file.

Installation in mkdocs

To install markmap in mkdocs, you need install the plugin using pip:

pip install mkdocs-markmap

Then, you need to add the following lines to your mkdocs.yml file:

plugins:
  - markmap

Usage

To use markmap, you need to add the following code block to your markdown file:

```markmap  
# Root

## Branch 1

* Branchlet 1a
* Branchlet 1b

## Branch 2

* Branchlet 2a
* Branchlet 2b
```

And this will generate the following mindmap:

alt text

That is for the future, because in my mkdocs not work as expected:

# Root

## Branch 1

* Branchlet 1a
* Branchlet 1b

## Branch 2

* Branchlet 2a
* Branchlet 2b

Visual Studio Code Extension

There is also a Visual Studio Code extension that allows you to create mindmaps from markdown files. You can install it from the Visual Studio Code marketplace.

    Name: Markdown Preview Markmap Support
    Id: phoihos.markdown-markmap
    Description: Visualize Markdown as Mindmap (A.K.A Markmap) to VS Code's built-in markdown preview
    Version: 1.4.6
    Publisher: phoihos
    VS Marketplace Link: https://marketplace.visualstudio.com/items?itemName=phoihos.markdown-markmap
VS Marketplace Link

Conclusion

I don't like too much this plugin because it not work as expected in my mkdocs but it's a good tool for documentation.

References