doc_noob
doc_noob

Reputation: 625

for each in terraform - pick values from text file

I have a null_resource in my script as follows and I have a text file in which i get the port no, like below

40000
40001
resource "null_resource" "opsfile" {   
  provisioner "file" {
    source      = "${path.module}/../../configfiles/file1.yaml"
    destination = "/home/file1.yaml"    
    connection {
        type = "ssh"
        user = "newus"        
        host = "var.publicip
        port = // i want to call each port in that text file here
        
      }
      
 }

How can i access the ports one by one and get the script to connect to that port, any help would be appreciated.

Upvotes: 0

Views: 1079

Answers (2)

Guy Keller
Guy Keller

Reputation: 137

As the accepted answer does not work.
I thought that I would share one that does:

locals {
  ports = compact(split("\n", file("${path.module}/ports.txt")))
}

resource "null_resource" "opsfile" {
  for_each = toset(local.ports)

  
  provisioner "file" {
    source      = "${path.module}/../../configfiles/file1.yaml"
    destination = "/home/file1.yaml"    
    connection {
        type = "ssh"
        user = "newus"        
        host = "var.publicip"
        port = each.key
      }

  triggers = {
    port = each.key
  }
      
 }
}

Upvotes: 0

mrexojo
mrexojo

Reputation: 331

Something like this

locals {
  ports = [ split("\n", file("./ports.txt") ) ]
}

resource "null_resource" "opsfile" {
  for_each = toset( [ local.ports] )

  
  provisioner "file" {
    source      = "${path.module}/../../configfiles/file1.yaml"
    destination = "/home/file1.yaml"    
    connection {
        type = "ssh"
        user = "newus"        
        host = "var.publicip"
        port = each.key
      }

  triggers = {
    port = each.key
  }
      
 }
}

--> for_each meta-arguments

Upvotes: 2

Related Questions