Verificar certificados con OpenSSL

Jugar con Terraform en local con LocalStack

localstack

¿Alguna vez te has sentido frustrado por tener que esperar a que se apliquen cambios en AWS solo para probar una pequeña modificación? ¿O te preocupa el coste de hacer pruebas en la nube real mientras estás desarrollando? Si la respuesta es sí, LocalStack puede ser tu aliado.

Vamos paso a paso, desde la instalación hasta desplegar un bucket S3 y subir un archivo. Todo explicado con ejemplos, comandos y algún que otro truco útil. Así que si estás trabajando con AWS y quieres un entorno de pruebas que funcione como en producción, pero sin complicarte la vida, sigue leyendo.

¿Qué es LocalStack?

LocalStack es un emulador de servicios en la nube que se ejecuta en un único contenedor en tu portátil o en tu entorno de integración continua (CI). Podrás ejecutar tus aplicaciones de AWS o Lambdas completamente en tu máquina local sin conectarte a un proveedor de nube remoto. Ya sea que estés probando aplicaciones complejas con CDK o configuraciones de Terraform, o simplemente comenzando a aprender sobre los servicios de AWS, Esto te puede ayudar a acelerar y simplificar tu flujo de trabajo de desarrollo y pruebas.

LocalStack admite muchos servicios de AWS

La información es volátil en la edición comunitaria de LocalStack. La persistencia está disponible en la edición profesional.

Crear una carpeta de prueba:

$ mkdir -p terraform-test
$ cd terraform-test

Paso a paso

Crear un entorno virtual

$ python -m venv venv

Activar el entorno virtual

$ source venv/bin/activate

Instalar awslocal y tflocal

$ pip install awslocal
$ pip install tflocal

Ejecutar LocalStack con Docker

$ docker run --rm -it -p 4566:4566 -p 4510-4559:4510-4559 localstack/localstack

Crear el archivo `provider.tf` y configurar los endpoints

provider "aws" {
  access_key                  = "fake-access-key"
  secret_key                  = "fake-secret-key"
  region                      = "us-east-1"
  skip_credentials_validation = true
  skip_metadata_api_check     = true
  skip_requesting_account_id  = true
  s3_use_path_style           = true

  endpoints {
    apigateway     = "http://localhost:4566"
    apigatewayv2   = "http://localhost:4566"
    cloudformation = "http://localhost:4566"
    cloudwatch     = "http://localhost:4566"
    dynamodb       = "http://localhost:4566"
    ec2            = "http://localhost:4566"
    es             = "http://localhost:4566"
    elasticache    = "http://localhost:4566"
    firehose       = "http://localhost:4566"
    iam            = "http://localhost:4566"
    kinesis        = "http://localhost:4566"
    keyspaces      = "http://localhost:4566"
    lambda         = "http://localhost:4566"
    rds            = "http://localhost:4566"
    redshift       = "http://localhost:4566"
    route53        = "http://localhost:4566"
    s3             = "http://localhost:4566"
    s3api          = "http://localhost:4566"
    secretsmanager = "http://localhost:4566"
    ses            = "http://localhost:4566"
    sns            = "http://localhost:4566"
    sqs            = "http://localhost:4566"
    ssm            = "http://localhost:4566"
    stepfunctions  = "http://localhost:4566"
    sts            = "http://localhost:4566"
    events         = "http://localhost:4566"
    scheduler      = "http://localhost:4566"
    opensearch     = "http://localhost:4566"
  }
}

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.47.0"
    }
  }
}

Crear un recurso de bucket S3 en bucket.tf:

resource "aws_s3_bucket" "bucket" {
  bucket = "your-bucket-name"

  tags = merge({
    Name        = "Your bucket name"
    Project     = "My example project"
    Environment = "Dev"
  })
}

Inicializar Terraform

$ tflocal init

Output:

Initializing the backend...

Initializing provider plugins...
- Finding hashicorp/aws versions matching "~> 5.47.0"...
- Installing hashicorp/aws v5.47.0...
- Installed hashicorp/aws v5.47.0 (signed by HashiCorp)

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

Validar la configuración

$ tflocal validate

Output:

Success! The configuration is valid.

Planificar la infraestructura

$ tflocal plan

Output:

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # aws_s3_bucket.bucket will be created
  + resource "aws_s3_bucket" "bucket" {
      + acceleration_status         = (known after apply)
      + acl                         = (known after apply)
      + arn                         = (known after apply)
      + bucket                      = "my-test-bucket"
      + bucket_domain_name          = (known after apply)
      + bucket_prefix               = (known after apply)
      + bucket_regional_domain_name = (known after apply)
      + force_destroy               = false
      + hosted_zone_id              = (known after apply)
      + id                          = (known after apply)
      + region                     = (known after apply)
      + request_payer              = (known after apply)
      + tags_all                   = (known after apply)
      + website_domain             = (known after apply)
      + website_endpoint           = (known after apply)

      + tags = {
          + "Environment" = "Dev"
          + "Name"        = "Your bucket name"
          + "Project"     = "My example project"
        }
      }
Plan: 1 to add, 0 to change, 0 to destroy.
╷
│ Warning: Invalid Attribute Combination
│ 
│ with provider["registry.terraform.io/hashicorp/aws"],
│ on provider.tf line 1, in provider "aws":
│ 1: provider "aws" {
│ 
│ Only one of the following attributes should be set: "endpoints[0].s3", "endpoints[0].s3api"
│ 
│ This will be an error in a future release.
╵
╷
│ Warning: AWS account ID not found for provider
│ 
│ with provider["registry.terraform.io/hashicorp/aws"],
│ on provider.tf line 1, in provider "aws":
│ 1: provider "aws" {
│ 
│ See https://registry.terraform.io/providers/hashicorp/aws/latest/docs#skip_requesting_account_id for implications.
╵

─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply"
now.

Aplicar la infraestructura:

$ tflocal apply

Output:

....
  Enter a value: yes

aws_s3_bucket.bucket: Creating...
aws_s3_bucket.bucket: Creation complete after 0s [id=my-test-bucket]
╷
│ Warning: Invalid Attribute Combination
│ 
│ with provider["registry.terraform.io/hashicorp/aws"],
│ on provider.tf line 1, in provider "aws":
│ 1: provider "aws" {
│ 
│ Only one of the following attributes should be set: "endpoints[0].s3", "endpoints[0].s3api"
│ 
│ This will be an error in a future release.
╵
╷
│ Warning: AWS account ID not found for provider
│ 
│ with provider["registry.terraform.io/hashicorp/aws"],
│ on provider.tf line 1, in provider "aws":
│ 1: provider "aws" {
│ 
│ See https://registry.terraform.io/providers/hashicorp/aws/latest/docs#skip_requesting_account_id for implications.
╵

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Comprobar que el bucket se ha creado

$ awslocal s3 ls

output

2022-02-11 11:39:31 my-test-bucket

Subir un fichero

Crear fichero

touch file-test.txt

Subir fichero

awslocal s3 cp file-test.txt s3://my-test-bucket/

Output

upload: ./file-test.txt to s3://my-test-bucket/file-test.txt

Comprobar fichero en el bucket

awslocal s3 ls s3://my-test-bucket/

output

2022-02-11 11:40:11 0 file-test.txt

Truco

Puedes ver los archivos en el bucket, abre tu navegador y escribe la siguiente URL:
http://localhost:4566/my-test-bucket/file-test.txt

Nota: Revisa los servicios compatibles en la edición comunitaria de LocalStack. Por ejemplo, no puedes crear un Network Balancer 😔.

Más apuntes

Invítame a un café con bitcoins:
1QESjZDPxWtZ9sj3v5tvgfFn3ks13AxWVZ

Bitcoins para café
También puedes invitarme a algo para mojar...

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Rellena este campo
Rellena este campo
Por favor, introduce una dirección de correo electrónico válida.
Tienes que aprobar los términos para continuar