Pide tu presupuesto ya!

Mantener Terraform mantenible con Terragrunt

Preparando la estructura del directorio Terragrunt

Imagínese elaborar un plano para la casa de sus sueños. Antes de comenzar a verter los cimientos, necesita un plan sólido. En Terraform y Terragrunt, su estructura de directorios es su modelo, la base sobre la cual su infraestructura como código (IaC) la obra maestra permanecerá en pie.

Para preparar la estructura de su directorio, proceda con lo siguiente:

1. Cree un directorio de proyecto llamado demostración-terragrunt (arbitrario), con subdirectorios llamados/dev, /pinchary /puesta en escena.

2. Dentro de cada subdirectorio, cree archivos vacíos llamados /principal.tf, /terraform.varsy /variables.tf.

En este punto, debería tener una estructura de directorios como la siguiente. En esta estructura de directorios, el principal.tf El archivo se replica para su uso en otros entornos.

Mostrando una estructura de directorios terraform más compleja

3. En tu /desarrollador subdirectorio, abra su /principal.tf archivo con su editor preferido y agregue el siguiente código.

Recuerde reemplazar <YOUR_S3_BUCKET_NAME> y <YOUR_BUCKET_REGION> con el nombre y la región de su depósito S3. Esta configuración completa lo siguiente:

  • Configura Terraform para utilizar un depósito S3 como backend para almacenar archivos de estado.
  • Define un módulo de instancia EC2 con configuraciones específicas para lanzar una instancia EC2 en el entorno de AWS.
# Terraform Backend Configuration
terraform {
  # Specify the backend configuration for storing state files
  backend "s3" {
    # Replace <YOUR_S3_BUCKET_NAME> with the name of your S3 bucket
    bucket         = "<YOUR_S3_BUCKET_NAME>"
    # Specify the path within the S3 bucket where the state file will be stored
    key            = "terragrunt/dev/terraform.tfstate"
    # Replace <YOUR_BUCKET_REGION> with the AWS region where your S3 bucket is located
    region         = "<YOUR_BUCKET_REGION>"
    # Specify the name of the DynamoDB table for state-locking
    dynamodb_table = "my-lock-table"
  }
}

# EC2 Instance Module Configuration
module "ec2_instance" {
  # Specify the source of the module, which is an EC2 instance module provided by terraform-aws-modules
  source = "terraform-aws-modules/ec2-instance/aws"
  
  # Specify the parameters for the EC2 instance
  # Name of the EC2 instance
  name           = "dev-instance"
  # Type of EC2 instance
  instance_type  = "t2.micro"
  # Enable detailed monitoring for the instance
  monitoring     = true
  
  # Specify tags to assign to the EC2 instance
  # Tag indicating that Terraform created the instance
  Terraform   = "true"
  # Tag indicating the environment (in this case, development)
  Environment = "dev"
}

4. Ahora, agregue la siguiente configuración a su /prod/main.tf archivo.

Esta configuración es similar a la principal.tf en tus /desarrollador ambiente pero difiere en algunos valores específicos.

# Terraform Backend Configuration
terraform {
  # Define the backend configuration for storing state files
  backend "s3" {
    # Specify the name of the S3 bucket where state files will be stored
    bucket         = "<YOUR_S3_BUCKET_NAME>"
    # Specify the path within the S3 bucket where the state file will be stored
    key            = "terragrunt/prod/terraform.tfstate"
    # Specify the AWS region where the S3 bucket is located
    region         = "<YOUR_BUCKET_REGION>"
  }
}

# EC2 Instance Module Configuration
module "ec2_instance" {
  # Define the source of the module, which is an EC2 instance module provided by terraform-aws-modules
  source = "terraform-aws-modules/ec2-instance/aws"

  # Specify the parameters for the EC2 instance
  # Name of the EC2 instance
  name                   = "prod-instance"
  # AMI ID for the EC2 instance
  ami                    = "ami-06aa3f7caf3a30282"
  # Type of EC2 instance
  instance_type          = "t2.micro"
  # Specify the availability zone for the instance
  availability_zone      = "us-east-1"
  # Enable detailed monitoring for the instance
  monitoring             = true

  # Specify tags to assign to the EC2 instance
  tags = {
    # Tag indicating that Terraform created the instance
    Terraform   = "true"
    # Tag indicating the environment (in this case, production)
    Environment = "prod"
  }
}

El backend La configuración se repite en otros entornos, como /desarrollador y /pinchar, con ligeros cambios solo en valores de entrada específicos. Este método de configurar el backend es propenso a errores y puede causar problemas como anular un archivo de estado existente.

Algunas de las variables de entrada para el ec2_instance El módulo está duplicado. En escenarios donde las configuraciones son sencillas, la duplicación de variables de entrada no crea mucha confusión ni gastos generales. Es posible que el problema no se considere una preocupación importante en estos casos.

Pero, a medida que las configuraciones se vuelven más intrincadas y complejas, gestionar dicha duplicación se vuelve cada vez más difícil y problemático. Esta forma de gestionar las configuraciones va en contra No te repitas (SECO) principios.

5. Por último, navegue hasta su /desarrollador entorno y ejecute los siguientes comandos para aplicar el /principal.tf configuración.

# Initializes Terraform working directory
terraform init

# Previews changes Terraform will make to the infrastructure
terraform plan

# Applies changes to the infrastructure
terraform apply

Obtendrá un resultado similar, como se muestra a continuación, una vez que la configuración de terraform se haya aplicado a su infraestructura.

Aplicar configuraciones de Terraform a la infraestructura /dev
Aplicar configuraciones de Terraform al /desarrollador infraestructura
Written by

Leave a comment