ansible playbook中的循环(四)---(with_sequence 和 with_random_choice)

1.with_sequence

现在我有一个需求,我需要使用ansible在目标主机中创建5个目录,这5个目录的名字是test2、test4、test6、test8、test10,我该怎么办呢?当然,我可以使用shell模块执行一条命令去完成,但是我们现在正在总结"循环"的使用方法,所以,我要用循环完成这个需求,使用循环完成这个任务很简单,我们只需要借助一个循环的关键字,它就是"with_sequence",放开刚才的需求不说,我们先来看一个"with_sequence"的小示例,示例playbook如下:

[root@server4 ~]# vim xh14.yml 
[root@server4 ~]# cat xh14.yml 
---
- hosts: testB
  remote_user: root
  gather_facts: no
  tasks:
  - debug:
      msg: "{{item}}"
    with_sequence: start=1 end=5 stride=1

我们先不用纠结上例的"with_sequence"设置是什么意思,我们先来看一下上例的执行效果,先执上述playbook后,debug模块的输出结果如下

[root@server4 ~]# ansible-playbook xh14.yml

在这里插入图片描述
如输出信息所示,debug模块被循环调用了5次,msg的值从1一直输出到了5,值的大小每次增加1,没错,这正是"with_sequence"关键字的作用,“with_sequence"可以帮助我们按照顺序生成数字序列,上例的playbook中,with_sequence的设置是"start=1 end=5 stride=1”,其中start=1表示从1开始,end=5表示到5结束, stride=1表示步长为1,即从1到5每次增加1。

我们也可以换一种书写格式,如下格式如上例中的格式效果相同

with_sequence:
  start=1
  end=5
  stride=1

其实,还有一种更简单的写法,能够生成连续的数字序列,写法如下:

[root@server4 ~]# vim xh15.yml 
[root@server4 ~]# cat xh15.yml 
---
- hosts: testB
  remote_user: root
  gather_facts: no
  tasks:
  - debug:
      msg: "{{item}}"
    with_sequence: count=5
[root@server4 ~]# ansible-playbook xh15.yml 

在这里插入图片描述
上例中count=5表示数字序列默认从1开始,到5结束,默认步长为1,与上述两种写法的效果相同。

当我们不指定stride的值时,stride的值默认为1,但是,当end的值小于start的值时,则必须指定stride的值,而且stride的值必须是负数,示例如下:

[root@server4 ~]# vim xh16.yml 
[root@server4 ~]# cat xh16.yml 
---
- hosts: testB
  remote_user: root
  gather_facts: no
  tasks:
  - debug:
      msg: "{{item}}"
    with_sequence: start=6 end=2 stride=-2

上例中start的值为6,end的值为2,stride的值为-2,表示从6开始,每次减2,到2结束,上例playbook的执行结果如下:

[root@server4 ~]# ansible-playbook xh16.yml 

在这里插入图片描述
看完上述总结,我们可以使用"with_sequence"完成上述创建目录的需求,示例playbook如下:

[root@server4 ~]# vim xh17.yml 
[root@server4 ~]# cat xh17.yml 
---
- hosts: testB
  remote_user: root
  gather_facts: no
  tasks:
  - file:
      path: "/westos{{item}}"
      state: directory
    with_sequence: start=2 end=10 stride=2

在这里插入图片描述
在这里插入图片描述

2.with_random_choice

"with_random_choice"的用法非常简单,使用"with_random_choice"可以从列表的多个值中随机返回一个值,先来看一个小示例,playbook如下:

[root@server4 ~]# vim xh18.yml
[root@server4 ~]# cat xh18.yml 
---
- hosts: testB
  remote_user: root
  gather_facts: no
  tasks:
  - debug:
      msg: "{{item}}"
    with_random_choice:
    - 1
    - 2
    - 3
    - 4
    - 5

[root@server4 ~]# ansible-playbook xh18.yml 

如上例所示,我们定义了一个列表,列表中有5个值,我们使用"with_random_choice"处理这个列表。

连续执行上例playbook,可以看出每次返回的结果是从列表中随机选中的一个:
在这里插入图片描述
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值