Ansible playbook中的迭代

142 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第20天,点击查看活动详情

  •  在指定目录下遍历创建多个目录,with_items中指定要迭代的元素列表,遍历引用的变量名必须是item:
[root@localhost ansible]# cat test0907.yml
---
- hosts: wyh-test
  remote_user: root

  tasks:
    - name: create mutiple files
      file: path=/usr/local/wyh/{{ item }} state=touch
      when: ansible_distribution_major_version == "7"
      with_items:
        - 0907file1.txt
        - 0907file2.txt
        - 0907file3.txt
        - 0907file4.txt

执行成功之后,查看文件是否创建成功:

  •  迭代嵌套子变量
#遍历创建3个group,然后遍历创建三个user并将其对应放到3个group中

[root@localhost ansible]# cat test0907-2.yml
---
- hosts: wyh-test
  remote_user: root

  tasks:
    - name: create groups
      group: name={{ item }} state=present
      with_items:
        - group1
        - group2
        - group3
    - name: create users
      user: name={{ item.username }} group={{ item.groupname }}
      with_items:
        - {username: 'user1', groupname: 'group1'}
        - {username: 'user2', groupname: 'group2'}
        - {username: 'user3', groupname: 'group3'}

执行成功后,验证是否成功创建group和user:

[root@localhost ansible]# ansible wyh-test -m shell -a 'getent group'

[root@localhost ansible]# ansible wyh-test -m shell -a 'getent passwd'

 

可以看到user分别对应着三个group。

  • 在template中使用for循环
#编写playbook
[root@localhost ansible]# cat test0908.yml
---
- hosts: wyh-test
  remote_user: root
  vars:                     #定义变量
    ports:                  #变量列表
      - 81
      - 82
      - 83

  tasks:
    - name: copy conf file
      template: src=test0908.conf.j2 dest=/usr/local/wyh/test0908.conf     #src如果写相对路径,必须将文件放在templates目录下,并以j2作为文件名结尾
#编写模板文件
[root@localhost templates]# cat test0908.conf.j2
{% for port in ports %}
server{
        listen {{ port }}
}
{% endfor %}


#for循环必须是以{%开头,以%}结尾,并且整个循环体是以for和endfor作为整体

执行成功后查看生成的文件:

  • template循环时也可以使用字典变量 
#编写playbook
[root@localhost ansible]# cat test09082.yml
---
- hosts: wyh-test
  remote_user: root
  vars:
    ports:
      - port: 81
        name: website1
      - port: 82
        name: website2
      - port: 83
        name: website3
  tasks:
    - name: copy conf file
      template: src=test09082.conf.j2 dest=/usr/local/wyh/test09082.conf
#模板文件中引用字典变量进行循环
[root@localhost templates]# cat test09082.conf.j2
{% for element in ports %}
server{
        listen {{ element.port }}
        webname {{ element.name }}
}
{% endfor %}

执行成功后查看文件: