Saltar al contenido principal

Clase 08 — JSON en DevOps

JSON en Docker

# Inspeccionar un contenedor
docker inspect mi-contenedor | jq '.[0].State'
docker inspect mi-contenedor | jq '.[0].NetworkSettings.IPAddress'
docker inspect mi-contenedor | jq '.[0].Config.Env'

# Variables de entorno como objeto
docker inspect mi-contenedor | jq '
.[0].Config.Env | map(split("=") | {(.[0]): .[1]}) | add'

# Estado de todos los contenedores
docker ps -a --format '{{json .}}' | jq -s '
map({nombre: .Names, imagen: .Image, estado: .Status, puertos: .Ports})'

# Uso de recursos en formato JSON
docker stats --no-stream --format '{{json .}}' | jq -s '
map({contenedor: .Name, cpu: .CPUPerc, memoria: .MemUsage})'

JSON en AWS CLI

# Listar instancias con campos específicos
aws ec2 describe-instances --output json | jq '
.Reservations[].Instances[] | {
id: .InstanceId, tipo: .InstanceType, estado: .State.Name,
ip_publica: (.PublicIpAddress // "N/A"),
nombre: (.Tags // [] | map(select(.Key == "Name")) | .[0].Value // "sin-nombre")
}'

# Tabla formateada
aws ec2 describe-instances --output json | jq -r '
.Reservations[].Instances[] |
[.InstanceId, .InstanceType, .State.Name, (.PublicIpAddress // "N/A")] | @tsv' | column -t

# S3 — Listar buckets
aws s3api list-buckets --output json | jq '.Buckets[] | {nombre: .Name, creado: .CreationDate}'

# S3 — Tamaño de un bucket
aws s3api list-objects-v2 --bucket mi-bucket --output json | jq '{
total_objetos: .KeyCount,
tamaño_mb: ([.Contents[].Size] | add / 1048576 | floor)
}'

# IAM Policies (son JSON)
cat <<'EOF' > politica.json
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject"],
"Resource": "arn:aws:s3:::mi-bucket/*"
}]
}
EOF
aws iam create-policy --policy-name MiPolitica --policy-document file://politica.json

# CloudFormation outputs
aws cloudformation describe-stacks --stack-name mi-stack --output json | jq '
.Stacks[0].Outputs | map({(.OutputKey): .OutputValue}) | add'

JSON en Terraform

# Outputs en JSON
terraform output -json | jq '.'
terraform output -json | jq -r '.instance_ip.value'

# Generar inventario para Ansible
terraform output -json | jq -r '
.instances.value | to_entries[] |
"\(.value.ip) ansible_host=\(.value.ip) ansible_user=ubuntu"'

# Estado actual como JSON
terraform show -json | jq '.values.root_module.resources[] | {
tipo: .type, nombre: .name, valores: .values | {id, tags}
}'

# Tabla de instancias desde Terraform output
jq -r '.instances.value | to_entries[] | [.key, .value.ip, .value.type] | @tsv' /tmp/tf-output.json

JSON en Kubernetes

# Pods con jq
kubectl get pods -o json | jq '
.items[] | {
nombre: .metadata.name, namespace: .metadata.namespace,
estado: .status.phase, ip: .status.podIP,
reinicios: ([.status.containerStatuses[]?.restartCount] | add // 0)
}'

# Pods con problemas
kubectl get pods -A -o json | jq '
[.items[] | select(.status.phase != "Running" and .status.phase != "Succeeded") | {
nombre: .metadata.name, namespace: .metadata.namespace, estado: .status.phase
}]'

# Patch de un recurso
kubectl patch deployment mi-app -p '{"spec":{"replicas":5}}'

# Patch JSON
kubectl patch deployment mi-app --type='json' \
-p '[{"op":"replace","path":"/spec/replicas","value":3}]'

JSON en GitHub Actions

Matrix strategy con JSON dinámico

jobs:
setup:
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
steps:
- id: set-matrix
run: |
MATRIX=$(jq -c '.' <<'EOF'
{"include": [
{"env": "staging", "url": "https://staging.app.com"},
{"env": "production", "url": "https://app.com"}
]}
EOF
)
echo "matrix=$MATRIX" >> "$GITHUB_OUTPUT"

deploy:
needs: setup
strategy:
matrix: ${{ fromJSON(needs.setup.outputs.matrix) }}
runs-on: ubuntu-latest
steps:
- run: echo "Deploying to ${{ matrix.env }}"

JSON vs YAML — Conversión

# YAML a JSON
python3 -c "
import yaml, json, sys
data = yaml.safe_load(open(sys.argv[1]))
print(json.dumps(data, indent=2))
" config.yaml > config.json

# JSON a YAML
python3 -c "
import yaml, json, sys
data = json.load(open(sys.argv[1]))
print(yaml.dump(data, default_flow_style=False))
" config.json > config.yaml

# Con yq (si está instalado)
yq -o json config.yaml > config.json
yq -P config.json > config.yaml

Script: Reporte de infraestructura

#!/bin/bash
generar_reporte() {
jq -n \
--arg fecha "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
--arg hostname "$(hostname)" \
--arg os "$(uname -s)" \
--arg kernel "$(uname -r)" \
'{
reporte: {
fecha: $fecha,
sistema: { hostname: $hostname, os: $os, kernel: $kernel }
}
}'
}
generar_reporte | jq '.' > reporte-infra.json