Terraform/04-variables-local-exec
2023-07-04 19:02:30 +02:00
..
2023-07-04 19:02:30 +02:00

%title: Terraform %author: Hubert

Terraform : Variables et Local-Exec


  • utilisation de provisioner sur ces resources (passer des commandes)

    provisioner remote-exec : exécution sur la machine distante provisioner local-exec : exécution sur la machine terraform


  • type de variables :
    • string
    • list
    • map

exemple string :

variable "str" {
  type = string
  default = "127.0.0.1 gitlab.test"
}
resource "null_resource" "node1" {
 provisioner "local-exec" {
  command = "echo '${var.str}' > hosts.txt"
 }
}

Terraform : Variables et Local-Exec


  • map
variable "hosts" {
  default     = {
    "127.0.0.1" = "localhost"
    "10.0.4.52" = "git.tips-of-mine.local"
    "10.0.4.105" = "prometheus.tips-of-mine.local"
  }
}
resource "null_resource" "hosts" {
 for_each = var.hosts
 provisioner "local-exec" {
  command = "echo '${each.key} ${each.value}' >> hosts.txt"
 }
}

  • trigger
resource "null_resource" "hosts" {
 for_each = var.hosts
 triggers = {
   foo = each.value
 }
...

Remarque : boucle for préférable


Terraform : Variables et Local-Exec


  • parcourir une liste
variable "hosts" {
  default     = ["127.0.0.1 localhost","10.0.4.133 gitlab.test"]
}
resource "null_resource" "hosts" {
 count = "${length(var.hosts)}"
 provisioner "local-exec" {
  command = "echo '${element(var.hosts, count.index)}' >> hosts.txt"
 }
}

  • avec le trigger
variable "hosts" {
  default     = ["11","2","3"]
}
resource "null_resource" "hosts" {
 count = "${length(var.hosts)}"
 triggers = {
   foo = element(var.hosts, count.index)
 }
 provisioner "local-exec" {
  command = "echo '${element(var.hosts, count.index)}' >> hosts.txt"
 }
}