Skip to content
English
On this page

Guía de Configuración de AWS CloudFormation CLI

1. Requisitos Previos

1.1 Requerimientos Base

bash
# Python 3.6 o superior
python --version

# AWS CLI instalado y configurado
aws --version
aws configure list

# pip instalado
pip --version

1.2 Permisos AWS Necesarios

json
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "cloudformation:*",
                "s3:*",
                "iam:PassRole",
                "sts:GetCallerIdentity"
            ],
            "Resource": "*"
        }
    ]
}

2. Instalación

2.1 Instalación con pip

bash
# Instalar CloudFormation CLI
pip install --user aws-cloudformation-cli

# Instalar plugins adicionales
pip install --user aws-cloudformation-cli-json-schema
pip install --user aws-cloudformation-cli-python-plugin

# Verificar instalación
cfn --version

2.2 Configuración Inicial

bash
# Verificar configuración
cfn --help

# Inicializar proyecto
mkdir mi-proyecto-cfn
cd mi-proyecto-cfn
cfn init

3. Estructura del Proyecto

3.1 Estructura Básica

mi-proyecto-cfn/
├── templates/
│   ├── main.yaml
│   ├── network.yaml
│   └── database.yaml
├── parameters/
│   ├── dev.json
│   └── prod.json
├── macros/
│   └── custom-macros.yaml
├── hooks/
│   └── pre-deploy.sh
└── tests/
    └── test_templates.py

3.2 Template Base

yaml
# templates/main.yaml
AWSTemplateFormatVersion: '2010-09-09'
Description: 'Plantilla principal de infraestructura'

Parameters:
  Environment:
    Type: String
    AllowedValues: [dev, prod]
    Default: dev

Resources:
  VPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
      EnableDnsHostnames: true
      EnableDnsSupport: true
      Tags:
        - Key: Name
          Value: !Sub ${AWS::StackName}-vpc

Outputs:
  VpcId:
    Description: ID de la VPC
    Value: !Ref VPC
    Export:
      Name: !Sub ${AWS::StackName}-VpcId

4. Comandos Principales

4.1 Validación de Templates

bash
# Validar template
cfn validate -t templates/main.yaml

# Linting de template
cfn lint templates/main.yaml

# Verificar política de IAM
cfn validate-policy templates/main.yaml

4.2 Gestión de Stacks

bash
# Crear stack
cfn create-stack \
    --stack-name mi-stack \
    --template-body file://templates/main.yaml \
    --parameters file://parameters/dev.json

# Actualizar stack
cfn update-stack \
    --stack-name mi-stack \
    --template-body file://templates/main.yaml

# Eliminar stack
cfn delete-stack --stack-name mi-stack

5. Configuración Avanzada

5.1 Parámetros

json
// parameters/dev.json
{
    "Parameters": {
        "Environment": "dev",
        "VpcCidrBlock": "10.0.0.0/16",
        "DatabaseInstanceType": "db.t3.micro"
    },
    "Tags": {
        "Environment": "dev",
        "Project": "MiProyecto"
    }
}

5.2 Stack Sets

bash
# Crear StackSet
cfn create-stack-set \
    --stack-set-name mi-stack-set \
    --template-body file://templates/main.yaml \
    --parameters file://parameters/prod.json

# Desplegar instancias
cfn create-stack-instances \
    --stack-set-name mi-stack-set \
    --regions us-east-1 us-west-2 \
    --accounts 123456789012

6. Testing y Validación

6.1 Test Unitarios

python
# tests/test_templates.py
import unittest
import cfnlint.core

class TestTemplates(unittest.TestCase):
    def test_main_template(self):
        template_file = 'templates/main.yaml'
        rules = cfnlint.core.get_rules()
        matches = cfnlint.core.run_checks(template_file, rules)
        self.assertEqual(len(matches), 0)

6.2 Scripts de Validación

bash
#!/bin/bash
# scripts/validate.sh

set -e

for template in templates/*.yaml; do
    echo "Validando $template..."
    cfn validate -t $template
    cfn lint $template
done

7. Macros y Transformaciones

7.1 Definición de Macro

yaml
# macros/custom-macros.yaml
Transform: AWS::Serverless-2016-10-31

Resources:
  MacroFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: python3.8
      InlineCode: |
        def handler(event, context):
            # Lógica de transformación
            return {
                "requestId": event["requestId"],
                "status": "success",
                "fragment": event["fragment"]
            }

7.2 Uso de Macro

yaml
Transform: 
  - CustomMacro
  - AWS::Serverless-2016-10-31

Resources:
  MyResource:
    Type: Custom::Resource
    Properties:
      CustomProperty: Value

8. Gestión de Cambios

8.1 Change Sets

bash
# Crear change set
cfn create-change-set \
    --stack-name mi-stack \
    --change-set-name cambios-nuevos \
    --template-body file://templates/main.yaml

# Listar cambios
cfn describe-change-set \
    --stack-name mi-stack \
    --change-set-name cambios-nuevos

# Ejecutar change set
cfn execute-change-set \
    --stack-name mi-stack \
    --change-set-name cambios-nuevos

8.2 Rollback

bash
# Configurar rollback
cfn update-stack \
    --stack-name mi-stack \
    --template-body file://templates/main.yaml \
    --rollback-configuration Monitoring={AlarmIds=[alarm-id]}

9. Integración con CI/CD

9.1 GitHub Actions

yaml
# .github/workflows/cfn-deploy.yml
name: Deploy CloudFormation

on:
  push:
    branches: [ main ]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      
      - name: Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@v1
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: us-east-1
          
      - name: Deploy CloudFormation stack
        run: |
          cfn validate -t templates/main.yaml
          cfn create-stack \
            --stack-name mi-stack-${{ github.sha }} \
            --template-body file://templates/main.yaml \
            --parameters file://parameters/dev.json

9.2 AWS CodePipeline

yaml
# pipeline/pipeline.yaml
Resources:
  Pipeline:
    Type: AWS::CodePipeline::Pipeline
    Properties:
      Stages:
        - Name: Source
          Actions:
            - Name: Source
              ActionTypeId:
                Category: Source
                Provider: CodeCommit
        - Name: Deploy
          Actions:
            - Name: CreateChangeSet
              ActionTypeId:
                Category: Deploy
                Provider: CloudFormation

10. Monitoreo y Logs

10.1 Monitoreo de Stacks

bash
# Monitorear eventos
cfn describe-stack-events \
    --stack-name mi-stack

# Verificar recursos
cfn list-stack-resources \
    --stack-name mi-stack

# Obtener outputs
cfn describe-stacks \
    --stack-name mi-stack \
    --query 'Stacks[0].Outputs'

10.2 Configuración de Logs

yaml
# templates/logging.yaml
Resources:
  LogGroup:
    Type: AWS::Logs::LogGroup
    Properties:
      LogGroupName: !Sub /aws/cloudformation/${AWS::StackName}
      RetentionInDays: 30

11. Seguridad

11.1 IAM Roles

yaml
# templates/iam.yaml
Resources:
  CFNRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: cloudformation.amazonaws.com
            Action: sts:AssumeRole

11.2 Políticas de Stack

yaml
# templates/stack-policy.json
{
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "Update:*",
      "Principal": "*",
      "Resource": "*"
    },
    {
      "Effect": "Deny",
      "Action": "Update:Delete",
      "Principal": "*",
      "Resource": "LogicalResourceId/CriticalResource"
    }
  ]
}

12. Comandos Útiles Adicionales

bash
# Exportar template
cfn get-template \
    --stack-name mi-stack \
    --output text > template-export.yaml

# Estimar costos
cfn estimate-template-cost \
    --template-body file://templates/main.yaml

# Listar stacks
cfn list-stacks \
    --stack-status-filter CREATE_COMPLETE UPDATE_COMPLETE

# Verificar drift
cfn detect-stack-drift \
    --stack-name mi-stack

Esta guía proporciona una base sólida para trabajar con AWS CloudFormation CLI. Recuerda mantener actualizadas las herramientas y seguir las mejores prácticas de seguridad de AWS.