Terraform : utilisation de yamldecode()

Posted by

Petit exemple d’utilisation d’un fichier YAML contenant des règles de flux importées en tant que NSG dans Azure :

Fichier nsg-www.yml :

nsg-www:
  rules:
    - name: Allow HTTP
      access: "Allow"
      direction: "Inbound"
      priority: 200
      protocol: "Tcp"
      source_port_range: "*"
      source_address_prefix: "*"
      destination_port_range: "80"
      destination_address_prefix: "*"
    - name: Allow HTTPS
      access: "Allow"
      direction: "Inbound"
      priority: 210
      protocol: "Tcp"
      source_port_range: "*"
      source_address_prefix: "*"
      destination_port_range: "443"
      destination_address_prefix: "*"

Utilisation au sein d’un bloc dynamique :

locals {
  wwwnsg = yamldecode(file("nsg-www.yml"))
}

resource "azurerm_network_security_group" "nsg-www" {
  for_each = local.wwwnsg
  name     = each.key

  location            = azurerm_resource_group.rg-dev.location
  resource_group_name = azurerm_resource_group.rg-dev.name

  dynamic "security_rule" {
    for_each = each.value.rules[*]
    content {
      access                     = security_rule.value.access
      direction                  = security_rule.value.direction
      name                       = security_rule.value.name
      priority                   = security_rule.value.priority
      protocol                   = security_rule.value.protocol
      source_port_range          = security_rule.value.source_port_range
      source_address_prefix      = security_rule.value.source_address_prefix
      destination_port_range     = security_rule.value.destination_port_range
      destination_address_prefix = security_rule.value.destination_address_prefix
    }
  }
}

resource "azurerm_network_interface_security_group_association" "nsgassoc2-azvm01" {
  network_interface_id      = azurerm_network_interface.nic-azvm01.id
  network_security_group_id = azurerm_network_security_group.nsg-linuxserver.id
}

Leave a Reply

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *