-
Ansible Loops是什么?以及实际例子
就是循环语句。让我们看看这个创建Playbook的示例。要使用用户模块在系统中创建用户,在本例中, 我们只创建一个用户。但是如果我们有多个用户呢?name: Create users hosts: localhost tasks: - user: name= george state=present一种方法是根据需要多次复制这些行
name: Create users hosts: localhost tasks: - user: name= george state=present - user: name= ravi state=present - user: name= mani state=present - user: name= kiran state=present - user: name= jazlan state=present - user: name= emaan state=present - user: name= mazin state=present - user: name= izaan state=present - user: name=mike state=present - user: name= menaal state=present - user: name= shoeb state=present - user: name=rani state=present但这并不是很优雅,因为有很多重复。一个更好的方法是在所有用户上建立一个任务循环。这就是我们使用循环的地方。
Loop是一个循环指令,它多次执行相同的任务。每次运行时, 它都会将循环中每个项的值存储在名为“item”的变量中。因此, 可以简单地替换用户名,如下所示。这会使行动手册更有条理,并减少重复。

上面的写法,可以转换成下面的写法,方便理解loop,loop相当于创建了多个task,然后每个task都第一了变量item,如下。执行行动手册时, 它将以这种方式运行。这里只是方便理解loop,不建议这么写。

所以任何时候你遇到一本可能是别人写的Playbook,而loop部分很混乱, 我会建议你像这样可视化它。
在上面的例子中, 循环是一个字符串值数组,只有用户名。但是如果我也想指定用户id呢?这意味着循环中的每一项都必须有两个值;用户名和用户ID。但是如何在一个数组中传递两个值,而不是通过循环传递一个字符串数组。
传入一个字典数组。每个字典将有两个键值对。键是name是每个用户的id。
循环中每个任务内的item变量都是一个字典,因此, 在每个任务中, 要获取用户名,我可以执行item.name。要获取用户ID, 我可以执行item.uid。
对于字典数组, 可以简单地使用字典中的item.属性名来获取列表中每个字典中的一个项。
上面的例子可以可视化为如下,没一个task都有一个item字典变量,里面包含name和uid两个属性。使用的时候可以使用item.属性名的方式

还要注意, 字典数组也可以用json格式表示,如上上图所示。 -
With_*
我们刚才看到的loop指令用于创建简单的循环,这些循环迭代许多项。在Playbook中创建循环还有另一种方法。这就是使用带下划线的指令。
我们开发的这个Playbook也可以像下面这样使用with_items指令来编写。

实际上,loop指令是Ansible中新添加的。在过去, 我们只有with_items指令。在这种情况下, 两个Playbook产生相同的结果,两者之间没有太大的区别。对于像我们正在处理的那些简单循环,建议使用loop指令本身。然而, 在一些较旧的剧本中,可能会遇到with_items指令, 因此当您看到它时, 您应该理解它的含义。现在, 让我们看看
with指示词的优点。With_items只是遍历一个项目列表。我们还有其他的指令, 比如,with_files可以遍历多个文件,with_url可以连接多个url,with_mongodb可以连接多个mongodb数据库。这些只是其中的一部分。

with_*指令有很多。类型属于查找插件(lookup)

-
例子:下面的例子只会输出一个
Apple,请使用with_items让它输出所有的fruits?- name: 'Print list of fruits' hosts: localhost vars: fruits: - Apple - Banana - Grapes - Orange tasks: - command: 'echo "{{ item }}"'答案:
- name: 'Print list of fruits' hosts: localhost vars: fruits: - Apple - Banana - Grapes - Orange tasks: - command: 'echo "{{ item }}"' with_items: '{{ fruits }}'还可以不使用变量,如下:
- name: 'Print list of fruits' hosts: localhost tasks: - command: 'echo "{{ item }}"' with_items: - Apple - Banana - Grapes - Orange下面的例子,只会安装一个
package,改写它,让它能安装所有的package: - name: 'Install required packages' hosts: localhost become: yes vars: packages: - httpd - make - vim tasks: - yum: name: vim state: present答案:
- name: 'Install required packages' hosts: localhost become: yes vars: packages: - httpd - make - vim tasks: - yum: name: '{{ item }}' state: present with_items: '{{ packages }}'更多关于
Ansible的文章,请参考我的Ansible专栏:https://blog.csdn.net/u011069294/category_12331290.html


















