RousselTMLEARNING

Artículo · Terraform: del descubrimiento a la maestría

El lenguaje HCL

Este artículo está disponible en francés.

1. Les blocs #

La structure d'une configuration.

Exemple #

Blocs Terraform
L'ordre des fichiers et des blocs n'a pas d'importance.
terraform {
  required_version = ">= 1.7"
  required_providers { aws = { source = "hashicorp/aws", version = "~> 5.0" } }
}

provider "aws" { region = var.region }

variable "region" {
  type    = string
  default = "eu-west-3"
}

variable "environnement" {
  type = string
  validation {
    condition     = contains(["recette", "prod"], var.environnement)
    error_message = "recette ou prod uniquement."
  }
}

locals {
  etiquettes = { environnement = var.environnement, gere_par = "terraform" }
}

data "aws_availability_zones" "zones" { state = "available" }

resource "aws_s3_bucket" "rapports" {
  bucket = "rapports-${var.environnement}-${random_id.suffixe.hex}"
  tags   = local.etiquettes
}

resource "random_id" "suffixe" { byte_length = 4 }

output "bucket" { value = aws_s3_bucket.rapports.bucket }

2. Répéter des ressources #

count, for_each, dynamic.

count ou for_each ? #

Méta-argumentQuand l'utiliser
countN copies identiques ; adressées par index (fragile si on retire un élément du milieu)
for_eachUne ressource par clé d'une map ou d'un set : adresses stables
variable "files" { default = { facturation = 3, expedition = 5 } }

resource "aws_sqs_queue" "file" {
  for_each                   = var.files
  name                       = "commandes-${each.key}"
  visibility_timeout_seconds = each.value * 10
}

resource "aws_security_group" "web" {
  name = "web"
  dynamic "ingress" {
    for_each = [80, 443]
    content {
      from_port   = ingress.value
      to_port     = ingress.value
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    }
  }
}

3. Expressions et fonctions #

Calculer des valeurs.

Utiles #

BesoinExemple
Conditionnellevar.env == "prod" ? 3 : 1
Boucle for[for z in data.aws_availability_zones.zones.names : upper(z)]
Fusion de mapsmerge(local.etiquettes, { role = "web" })
Encodagejsonencode({...}), yamldecode(file("x.yaml"))
Modèle de fichiertemplatefile("init.sh.tftpl", { port = 8080 })
terraform console
> cidrsubnet("10.0.0.0/16", 8, 2)
"10.0.2.0/24"
> [for i in range(3) : "web-${i}"]

📄 Le langage HCL : ressources, variables, sorties, données et expressions →

Mi seguimiento

  • ⏱ Duración estimada : ≈ 9 min

Inicia sesión para seguir tu progreso y tomar notas. Iniciar sesión

⭐ Valorar esta lección

5,0 valoración inicial del equipo docente

Inicia sesión para valorar esta lección →

💬 Preguntas sobre esta lección

Todavía no hay preguntas: sé el primero en pedir ayuda o compartir tu configuración.

Hacer una pregunta sobre esta lección →

Artículos recomendados

Infrastructure as Code et GitOps : Terraform, Ansible et Argo CD

Gérer l'infrastructure comme du code : déclaratif ou impératif, Terraform (providers, état, plan,...

Infrastructure as Code sur Azure : Bicep, Terraform, Cost Management et Well-Architected

Décrire et déployer Azure en code avec Bicep (modules, paramètres, what-if, déploiements par pipe...

Infrastructure as Code sur AWS : CloudFormation, CDK, Terraform et Well-Architected

Décrire et déployer son infrastructure AWS en code avec CloudFormation, le CDK ou Terraform, auto...

Ansible : gérer son infrastructure avec des playbooks (Infrastructure as Code)

Écrire des playbooks de production : structure d'un projet, plays, handlers, tags, strategy seria...

Automatisation et infrastructure as code pour Elasticsearch : API, Terraform, Ansible et CI/CD

Automatiser l'administration d'Elasticsearch : API REST et clients, fournisseur Terraform elastic...

Exploiter OVHcloud : Terraform, supervision, sécurité, coûts et souveraineté

Exploiter OVHcloud en production : infrastructure as code avec les fournisseurs Terraform ovh et ...

Configuration de Grafana Alloy : syntaxe, ports et premiers composants

Dans le cadre d'une formation Grafana ou formation observabilité, maîtrisez la syntaxe déclarativ...

Exploiter Google Cloud : observabilité, sécurité, infrastructure as code et coûts

Exploiter Google Cloud : Cloud Monitoring, Cloud Logging et Cloud Trace (Google Cloud Observabili...

Bonnes pratiques DevOps : culture, CI/CD, infrastructure as code et mesure

Bonnes pratiques DevOps : culture et collaboration, intégration et livraison continues, trunk-bas...

Apoyar

♥ APOYAR

Apoya RousselTM Learning

Los cursos, artículos, prácticas y certificados siguen siendo gratuitos y sin publicidad intrusiva. Una contribución libre, por el importe que elijas, financia el alojamiento, los entornos de prácticas y nuevos contenidos.

Contribuir con PayPal Importe libre · tarjeta o cuenta PayPalMás información
QR code PayPal
O escanea este código QR con tu teléfono

¡Gracias, cada contribución cuenta!