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循环类似
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 %}
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 %}
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 %}