IaC en AWS
6.13.4kata 4 de 5

Drift Detection

Detectar cambios manuales en consola y estrategias de recuperación

Drift es la diferencia entre lo que dice tu código IaC y lo que realmente existe en AWS. Ocurre cuando alguien edita un Security Group en la consola, cambia manualmente el tamaño de una instancia, o modifica una política IAM directamente. CloudFormation puede detectar este drift con el comando `detect-stack-drift`, pero no lo repara automáticamente.

El reporte de drift muestra recursos modificados (MODIFIED), eliminados (DELETED), o no gestionados (NOT_CHECKED). Para cada recurso modificado, muestra los campos que difieren: la propiedad esperada según el template vs la propiedad actual en AWS. Esto te da exactamente qué alguien cambió y cuándo (si tienes CloudTrail habilitado).

La estrategia de recuperación de drift siempre es la misma: actualiza el código IaC para reflejar el cambio deseado, luego re-despliega. Nunca al revés (cambiar en consola para que coincida con IaC). Si el cambio manual era correcto, incorpóralo al template y elimina el drift. Si fue un error, reviértelo en consola y redespliega desde IaC.

En Terraform, el equivalente es `terraform plan` después de cambios manuales: el plan mostrará los cambios que Terraform haría para volver al estado deseado. `terraform refresh` actualiza el tfstate con el estado real de AWS sin aplicar cambios, útil para reconciliar.

structure.txt
import boto3
import time
import json

cloudformation = boto3.client('cloudformation')

# Step 1: Trigger drift detection
response = cloudformation.detect_stack_drift(
    StackName='ml-pipeline-prod'
)
drift_detection_id = response['StackDriftDetectionId']

# Step 2: Wait for detection to complete
def wait_for_drift_detection(stack_name, detection_id):
    while True:
        response = cloudformation.describe_stack_drift_detection_status(
            StackDriftDetectionId=detection_id
        )
        status = response['DetectionStatus']
        if status == 'DETECTION_COMPLETE':
            return response['StackDriftStatus']  # DRIFTED or IN_SYNC
        elif status == 'DETECTION_FAILED':
            raise RuntimeError('Drift detection failed')
        time.sleep(5)

drift_status = wait_for_drift_detection('ml-pipeline-prod', drift_detection_id)
print(f'Stack drift status: {drift_status}')

# Step 3: If drifted, get details
if drift_status == 'DRIFTED':
    resources = cloudformation.describe_stack_resource_drifts(
        StackName='ml-pipeline-prod',
        StackResourceDriftStatusFilters=['MODIFIED', 'DELETED']
    )
    for resource in resources['StackResourceDrifts']:
        print(f'Resource: {resource["LogicalResourceId"]}')
        print(f'  Type: {resource["ResourceType"]}')
        print(f'  Status: {resource["StackResourceDriftStatus"]}')
        if 'PropertyDifferences' in resource:
            for diff in resource['PropertyDifferences']:
                print(f'  Property: {diff["PropertyPath"]}')
                print(f'    Expected: {diff["ExpectedValue"]}')
                print(f'    Actual: {diff["ActualValue"]}')

# Step 4: Recovery strategy
# Option A: The change was CORRECT — incorporate into template:
# 1. Update template.yaml to reflect the actual state
# 2. Deploy: aws cloudformation deploy --stack-name ml-pipeline-prod
# 3. Verify drift is now IN_SYNC

# Option B: The change was INCORRECT — revert in console:
# 1. Manually revert the change in AWS console
# 2. Run detect-stack-drift again to verify IN_SYNC

# Terraform equivalent:
# terraform plan (shows drift as changes to apply)
# terraform refresh (sync tfstate with AWS reality, no changes applied)
# terraform apply (reapply IaC state, reverting manual changes)

Debugging lab

Detecta y corrige el error en el código.

0/3 tests passing0%
  1. 01

    # Someone added an inbound rule to a Security Group in the console # CloudFormation template still has the old rules # Solution: manually revert in console (wrong approach)

  2. 02

    # Terraform: resource modified manually, terraform plan shows changes # Developer runs terraform apply to 'fix' drift # But the manual change was a critical hotfix! terraform apply # would revert the hotfix

  3. 03

    # No automated drift detection — drift discovered weeks later # 12 resources have drifted, unclear what's safe to revert aws cloudformation detect-stack-drift --stack-name ml-prod # Too many drifts accumulated