Ansible playbook中的迭代

  • 在指定目录下遍历创建多个目录,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 %}

执行成功后查看文件:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

QYHuiiQ

听说打赏的人工资翻倍~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值