ansible-循环

在使用ansible的过程中,我们经常需要处理一些返回信息,而这些返回信息中,通常可能不是单独的一条返回信息,而是一个信息列表,如果我们想要循环的处理信息列表中的每一条信息,我们该怎么办呢?这样空口白话的描述有些费力,不如通过一些小示例,结合场景来描述。

假设,我的清单配置如下

test3 ansible_ssh_host=192.168.245.111 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass=123456
test2 ansible_ssh_host=192.168.245.112 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass=123456

如果我想要获取到清单中所有未分组的主机的主机名,则可以执行如下命令

ansible test3 -m debug  -a "msg={{groups.ungrouped}}"


[root@test1 a]# ansible test3 -m debug  -a "msg={{groups.ungrouped}}"
test3 | SUCCESS => {
    "msg": [
        "test3"
        "test2"
    ]
}

我们通常不能确定返回信息有几条,我们可能需要循环的处理返回信息中的每一条信息,那么怎么才能循环处理返回信息中的每一条信息呢?示例playbook如下

---
- hosts: test3
  tasks:
  - debug:
     msg: "{{item}}"
    with_items: "{{groups.ungrouped}}"

我们重复的书写了file模块4次,其实每次只是改变了file模块的path参数的值而已,如果使用循环,上例的playbook则可以改写成如下

---
- hosts: test3
  vars:
   txt:
   - "/tmp/sb"
   - "/tmp/ssb"
  tasks:
  - name: touchfile
    file:    
      path: "{{item}}"
      state: touch
    with_items: "{{vars}}"

嵌套的列表

---
- hosts: test70
  remote_user: root
  gather_facts: no
  tasks:
  - debug:
      msg: "{{item}}"
    with_items:
    - [ 1, 2, 3 ]
    - [ a, b ]

假设,现在我有一个需求,我需要在目标主机的测试目录中创建a、b、c三个目录,这三个目录都有相同的子目录,它们都有test1和test2两个子目录

---
- hosts: test3
  tasks:
  - name: directory
    file:
      path: "/tmp/{{item.0}}/{{item.1}}"
      state: directory
    with_cartesian:
    - [a,b,c]
    - [test1,test2]

使用

with_cartesian:
    - [a,b,c]
    - [test1,test2]

结果

[root@test3 tmp]# tree /tmp
/tmp
├── a
│   ├── test1
│   └── test2
├── b
│   ├── test1
│   └── test2
└── c
    ├── test1
    └── test2

with_indexed_items 带序列号的索引循环

---
- hosts: test3
  remote_user: root
  gather_facts: no
  tasks:
  - debug:
      msg: "{{ item }}"
    with_indexed_items:
    - test1
    - test2
    - test3

with_sequence

需要使用ansible在目标主机中创建5个目录,这5个目录的名字是test2、test4、test6、test8、test10

使用with_sequence关键字

---
- hosts: test3
  remote_user: root
  gather_facts: no
  tasks:
  - file:
      path: "/tmp/test{{item}}"
      state: directory
    with_sequence: start=2 end=10 stride=2

结果

[root@test3 tmp]# tree /tmp
/tmp
├── test10
├── test2
├── test4
├── test6
└── test8

with_random_choice 随意选择一个值

- hosts: test3
  remote_user: root
  gather_facts: no
  tasks:
  - file:
      path: "/tmp/test{{item}}"
      state: directory
    with_random_choice: 
    - 1
    - 2
    - 3
    - 4
    - 5

with_dict
with_subelements
with_file
with_fileglob

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容