playbook变量(九)for循环

1、for循环简单应用

[root@linux-node1 ansible]# cat testfor.yaml 
---
- hosts: date
  remote_user: root
  vars:
    ports:
      - 81
      - 82
      - 83
  
  tasks:
    - name: copy conf
      template: src=for1.conf.j2 dest=/data1/for1.conf

自定义templates

[root@linux-node1 ansible]# cat templates/for1.conf.j2 
{% for port in ports %}
server{
        listen {{ port }}
}
{% endfor %}

#和shellfor循环类似

playbook变量(九)for循环_第1张图片

 playbook变量(九)for循环_第2张图片

2、剧本中是单个键值对

[root@linux-node1 ansible]# cat testfor1.yaml 
---
- hosts: date
  remote_user: root
  vars:
    ports:
      - listen_port: 81
      - listen_port: 82
      - listen_port: 83
  
  tasks:
    - name: copy conf
      template: src=for2.conf.j2 dest=/data1/for2.conf

自定义templates

[root@linux-node1 ansible]# cat templates/for2.conf.j2 
{% for port in ports %}
server{
        listen {{ port.listen_port }}
}
{% endfor %}

playbook变量(九)for循环_第3张图片

 2、剧本中是多个键值对

[root@linux-node1 ansible]# cat testfor2.yaml 
---
- hosts: date
  remote_user: root
  vars:
    ports:
      - web1:
        port: 81
        name: www.zjy1.con
        rootdir: /data1/zjy1
      - web2:
        port: 82
        name: www.zjy2.con
        rootdir: /data1/zjy2
      - web1:
        port: 83
        name: www.zjy3.con
        rootdir: /data1/zjy3
  
  tasks:
    - name: copy conf
      template: src=for3.conf.j2 dest=/data1/for3.conf

自定义templates

[root@linux-node1 ansible]# cat templates/for3.conf.j2 
{% for p in ports %}
server{
        listen {{ p.port }}
        servername {{ p.name }}
        documentroot {{ p.rootdir }}
}
{% endfor %}

playbook变量(九)for循环_第4张图片

 3、剧本中是多个键值对。加if判断(比如把name注释掉)

[root@linux-node1 ansible]# cat testfor3.yaml 
---
- hosts: date
  remote_user: root
  vars:
    ports:
      - web1:
        port: 81
        #name: www.zjy1.con
        rootdir: /data1/zjy1
      - web2:
        port: 82
        name: www.zjy2.con
        rootdir: /data1/zjy2
      - web1:
        port: 83
        #name: www.zjy3.con
        rootdir: /data1/zjy3
  
  tasks:
    - name: copy conf
      template: src=for4.conf.j2 dest=/data1/for4.conf

判断自定义templates 

[root@linux-node1 ansible]# cat templates/for4.conf.j2 
{% for p in ports %}
server{
        listen {{ p.port }}
{% if  p.name is defined %}
        servername {{ p.name }}
{% endif %}
        documentroot {{ p.rootdir }}
}
{% endfor %}

playbook变量(九)for循环_第5张图片

 

 playbook变量(九)for循环_第6张图片

你可能感兴趣的:(playbook变量(九)for循环)