Loop "for"
New on ASYD 1.2.0
For loops are structures created for iterating with hashed-form variables (i.e. var[one][two]
).
You can think on this as the "foreach" function some programming languages have.
Usage:
For loops can be used both in deploy definition files and configuration files. Like the conditional blocks, "for" loops can be concatenated and inner levels can access parent variables.
For loop on "def" files:
You can iterate over hashed variables inside "def", "def.sudo", "undeploy" and "undeploy.sudo" files using the followins syntax:
for newvar in <%VAR:myvar[*]%>
[...]
endfor
Example:
Suppose you have the following variables defined:
hosts[host1][ip] = 192.168.0.5
hosts[host1][hostname] = host1.example.com
hosts[host2][ip] = 192.168.0.10
hosts[host2][hostname] = host2.example.com
You can iterate over those variables doing the following:
for host in <%VAR:hosts[*]%>
exec: echo <%VAR:host[ip]%> <%VAR:host[hostname]%> >> /etc/hosts
endfor
The execution of that deploy will result on appending the lines
192.168.0.5 host1.example.com
192.168.0.10 host2.example.com
to the /etc/hosts
file.
For loop on configuration files:
The "for" loop can be used also inside configuration files. The usage is the same as for the "def" files, just adding the "<% %>" tag notation.
Syntax:
<%for newvar in <%VAR:myvar[*]%>%>
[...]
<%endfor%>
Example:
Using the same defined variables as for the previous example, you can define the following
configs/hosts
configuration file:
127.0.0.1 localhost.localdomain localhost
<%for host in <%VAR:hosts[*]%>%>
<%VAR:host[ip]%> <%VAR:host[hostname]%>
<%endfor%>
Which, after uploading the file executing config file: hosts, /etc/hosts
would result in:
127.0.0.1 localhost.localdomain localhost
192.168.0.5 host1.example.com
192.168.0.10 host2.example.com