Skip to content
English
On this page

Ejercicio: Automatización de Despliegue de Infraestructura Web con Alta Disponibilidad

Objetivo: Crear una infraestructura web automatizada usando AWS CLI y Python, implementando servicios de computación y redes.

Escenario: Desplegar una aplicación web en múltiples zonas de disponibilidad con balanceo de carga, utilizando automatización mediante AWS CLI y scripts de Python.

Tareas:

  1. Configuración Inicial:

    bash
    # Configurar AWS CLI
    aws configure
    AWS Access Key ID: [TU_ACCESS_KEY]
    AWS Secret Access Key: [TU_SECRET_KEY]
    Default region name: us-east-1
    Default output format: json
  2. Script de Python para Crear VPC y Subredes:

python
import boto3
import json

def create_network_infrastructure():
    ec2 = boto3.client('ec2')
    
    # Crear VPC
    vpc = ec2.create_vpc(
        CidrBlock='10.0.0.0/16',
        TagSpecifications=[{
            'ResourceType': 'vpc',
            'Tags': [{'Key': 'Name', 'Value': 'WebAppVPC'}]
        }]
    )
    vpc_id = vpc['Vpc']['VpcId']
    
    # Crear subredes en diferentes AZs
    subnet1 = ec2.create_subnet(
        VpcId=vpc_id,
        CidrBlock='10.0.1.0/24',
        AvailabilityZone='us-east-1a',
        TagSpecifications=[{
            'ResourceType': 'subnet',
            'Tags': [{'Key': 'Name', 'Value': 'WebApp-Subnet-1'}]
        }]
    )
    
    subnet2 = ec2.create_subnet(
        VpcId=vpc_id,
        CidrBlock='10.0.2.0/24',
        AvailabilityZone='us-east-1b',
        TagSpecifications=[{
            'ResourceType': 'subnet',
            'Tags': [{'Key': 'Name', 'Value': 'WebApp-Subnet-2'}]
        }]
    )
    
    return {
        'vpc_id': vpc_id,
        'subnet1_id': subnet1['Subnet']['SubnetId'],
        'subnet2_id': subnet2['Subnet']['SubnetId']
    }

if __name__ == "__main__":
    network_info = create_network_infrastructure()
    print(json.dumps(network_info, indent=2))
  1. Script de Configuración de Seguridad:
python
import boto3

def create_security_groups(vpc_id):
    ec2 = boto3.client('ec2')
    
    # Crear Security Group para ALB
    alb_sg = ec2.create_security_group(
        GroupName='ALB-SG',
        Description='Security group for Application Load Balancer',
        VpcId=vpc_id
    )
    
    ec2.authorize_security_group_ingress(
        GroupId=alb_sg['GroupId'],
        IpPermissions=[
            {
                'IpProtocol': 'tcp',
                'FromPort': 80,
                'ToPort': 80,
                'IpRanges': [{'CidrIp': '0.0.0.0/0'}]
            }
        ]
    )
    
    # Crear Security Group para EC2
    ec2_sg = ec2.create_security_group(
        GroupName='WebServer-SG',
        Description='Security group for Web Servers',
        VpcId=vpc_id
    )
    
    ec2.authorize_security_group_ingress(
        GroupId=ec2_sg['GroupId'],
        IpPermissions=[
            {
                'IpProtocol': 'tcp',
                'FromPort': 80,
                'ToPort': 80,
                'UserIdGroupPairs': [{'GroupId': alb_sg['GroupId']}]
            }
        ]
    )
    
    return {
        'alb_sg_id': alb_sg['GroupId'],
        'ec2_sg_id': ec2_sg['GroupId']
    }
  1. Script de Despliegue de EC2:
python
def deploy_ec2_instances(subnet_ids, security_group_id):
    ec2 = boto3.client('ec2')
    
    user_data = '''#!/bin/bash
    yum update -y
    yum install httpd -y
    systemctl start httpd
    systemctl enable httpd
    echo "<h1>Web Server - $(hostname -f)</h1>" > /var/www/html/index.html
    '''
    
    instances = []
    for subnet_id in subnet_ids:
        instance = ec2.run_instances(
            ImageId='ami-0cff7528ff583bf9a',  # Amazon Linux 2
            InstanceType='t2.micro',
            MaxCount=1,
            MinCount=1,
            UserData=user_data,
            NetworkInterfaces=[{
                'SubnetId': subnet_id,
                'DeviceIndex': 0,
                'AssociatePublicIpAddress': True,
                'Groups': [security_group_id]
            }],
            TagSpecifications=[{
                'ResourceType': 'instance',
                'Tags': [{'Key': 'Name', 'Value': f'WebServer-{subnet_id[-3:]}'}]
            }]
        )
        instances.append(instance['Instances'][0]['InstanceId'])
    
    return instances
  1. Script para Crear Load Balancer:
python
def create_load_balancer(subnet_ids, security_group_id):
    elb = boto3.client('elbv2')
    
    # Crear Application Load Balancer
    alb = elb.create_load_balancer(
        Name='WebApp-ALB',
        Subnets=subnet_ids,
        SecurityGroups=[security_group_id],
        Scheme='internet-facing',
        Tags=[{'Key': 'Name', 'Value': 'WebApp-ALB'}]
    )
    
    # Crear Target Group
    target_group = elb.create_target_group(
        Name='WebApp-TG',
        Protocol='HTTP',
        Port=80,
        VpcId=vpc_id,
        HealthCheckProtocol='HTTP',
        HealthCheckPath='/',
        TargetType='instance'
    )
    
    # Crear Listener
    elb.create_listener(
        LoadBalancerArn=alb['LoadBalancers'][0]['LoadBalancerArn'],
        Protocol='HTTP',
        Port=80,
        DefaultActions=[{
            'Type': 'forward',
            'TargetGroupArn': target_group['TargetGroups'][0]['TargetGroupArn']
        }]
    )
    
    return {
        'alb_arn': alb['LoadBalancers'][0]['LoadBalancerArn'],
        'target_group_arn': target_group['TargetGroups'][0]['TargetGroupArn']
    }
  1. Script Principal de Despliegue:
python
def main():
    # Crear infraestructura de red
    network_info = create_network_infrastructure()
    print("Red creada:", network_info)
    
    # Crear grupos de seguridad
    security_info = create_security_groups(network_info['vpc_id'])
    print("Grupos de seguridad creados:", security_info)
    
    # Desplegar instancias EC2
    instances = deploy_ec2_instances(
        [network_info['subnet1_id'], network_info['subnet2_id']],
        security_info['ec2_sg_id']
    )
    print("Instancias creadas:", instances)
    
    # Crear Load Balancer
    lb_info = create_load_balancer(
        [network_info['subnet1_id'], network_info['subnet2_id']],
        security_info['alb_sg_id']
    )
    print("Load Balancer creado:", lb_info)

if __name__ == "__main__":
    main()

Instrucciones de Uso:

  1. Guardar cada script en archivos separados.
  2. Instalar las dependencias necesarias:
bash
pip install boto3
  1. Ejecutar el script principal:
bash
python main.py
  1. Verificar la infraestructura:
bash
# Listar VPCs
aws ec2 describe-vpcs --filters "Name=tag:Name,Values=WebAppVPC"

# Listar instancias
aws ec2 describe-instances --filters "Name=tag:Name,Values=WebServer*"

# Listar Load Balancers
aws elbv2 describe-load-balancers --names WebApp-ALB

Ejercicio de Extensión:

  1. Agregar Auto Scaling Group
  2. Implementar monitoreo con CloudWatch
  3. Agregar respaldos automáticos
  4. Implementar un pipeline de CI/CD

Este ejercicio proporciona experiencia práctica con:

  • AWS CLI y SDK (boto3)
  • Servicios de computación (EC2)
  • Servicios de red (VPC, subredes, security groups)
  • Balanceo de carga (ALB)
  • Automatización con Python
  • Mejores prácticas de alta disponibilidad