Ansible循环与判断

本文详细介绍了Ansible中如何进行循环操作,包括with_items、with_dict、with_fileglob等多种方式,并展示了如何结合过滤器使用loop。同时,文章还探讨了Ansible的判断条件,如When运算符和各种tests,以及在实际场景中如何处理错误和异常,例如创建逻辑卷的条件判断和错误提示。
摘要由CSDN通过智能技术生成

ansible循环和判断


一、循环


1、with_items迭代列表

比如Linux中依次需要安装多个软件包时,我们可以使用with_items迭代功能进行实现
例如:
安装httpd、samba、samba-client软件包时

[student@ansible ansible]$  vim b.yml
- name: install packages
  hosts: node1
  tasks:
    - name: yum_repo1
      yum_repository:
        file: server
        name: baseos
        description: rhel8
        baseurl: file:///mnt/BaseOS
        enabled: yes
        gpgcheck: no
 
    - name: yum_repo2
      yum_repository:
        file: server
        name: appstream
        description: appstream
        baseurl: file:///mnt/AppStream
        enabled: yes
        gpgcheck: no
 
    - name: mount cdrom
mount:
        src: /dev/cdrom
        path: /mnt
        fstype: iso9660
        state: mounted
 
    - name: install pks
      yum:
        name: "{
  {item}}"
        state: present
      with_items:
        - httpd
        - samba
        - samba-client

2 、with_dict迭代字典

item.key对应着是字典的键,item.value对应着字典的值

[student@ansible ansible]$  vim c.yml
---
- name: test
  hosts: node1
  tasks:
    - name: debug
      debug:
        msg: "{
  {item.key}} & {
  {item.value}}"
      with_dict:
        address: 1
        netmask: 2
        gateway: 3

3、with_fileglob迭代文件

比如拷贝多个文件到受控主机上时,可以使用

[student@ansible ansible]$ vim d.yml
---
- name: test
  hosts: node1
  tasks:
    - name: cp file
      copy:
        src: "{
  {item}}"
        dest: /tmp/
      with_fileglob:
        - /tmp/*.sh
        - /tmp/*.py

4、with_lines迭代行

With_lines可以将命令行的输出结果按行迭代

[student@ansible ansible]$  vim e.yml
---
- name: test
  hosts: node1
  tasks:
    - name: cp file
      copy:
        src: "{
  {item}}"
        dest: /tmp/
      with_lines:
        - find  /etc/ansible  -name  "*.yml"

5、with_nested嵌套迭代

a和b分别与1、2、3连接组合

[student@ansible ansible]$ vim f.yml
---
- name: test
  hosts: node1
  tasks:
    - name: debug
      debug:
        msg: "{
  {item[0]}} & {
  {item[1]}}"
      with_nested:
        - [a,b]
        - [1,2,3]

6、with_sequence 排序列(start是从什么开始,end结束 stride每隔多少)

[student@ansible ansible]$ vim g.yml
---
- name: test
  hosts: node1
  tasks:
    - name: debug
      debug:
        msg: "{
  {item}}"
      with_sequence:
        start=1
        end=5
        stride=1

7、with_random_choice 随机获得列表中的一个值

---
- name: test
  hosts: node1
  tasks:
    - name: debug
      debug:
        msg: "{
  {item}}"
      with_random_choice:
        - 1
        - 2
        - a
        - b
        - c

8、loop

现在loop已经替代了with,更多的是loop配合过滤器进行使用
过滤器:
常用字符串有关的过滤器

---
- name: test
  hosts: node1
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值