mwill4321
mwill4321

Reputation: 43

In terraform, how do I add an if condition to a for loop?

I have a terraform template file that has a section like this to fill out host information. I'd like to add logic to it to only fill out this section if another variable, i.e. type = "ocp". So, if $type = "ocp", then run this loop. How would I do this?

ocp_hosts:
%{ for host in host_names }
  - name: ${host}
    device: "eth0"
    management:
      ip: ${ip_addrs[index(host_names, host)]}
%{ endfor }

I first tried adding an "if contains(${type}, "ocp")" to the for loop and I also tried adding in a condition block but I must not be formatting or understanding function correctly because it errors out on me.

Upvotes: 3

Views: 1499

Answers (1)

Derek Williams
Derek Williams

Reputation: 550

I don't work with templates that much, but from the documentation, it seems this might work for you.

%{if type == "ocp" }
ocp_hosts:
%{ for host in host_names }
  - name: ${host}
    device: "eth0"
    management:
      ip: ${ip_addrs[index(host_names, host)]}
%{ endfor }
%{ endif }

Upvotes: 2

Related Questions