ansible之loops

有时候,你想在一个task进行很多重复的操作,例如创建用户、安装包、或者重复执行一个操作直到某个希望的状态。

Standard Loops 标准循环

为了少打一些字,可以这样写重复的任务:

- name: add several users
  user:
    name: "{{ item }}"
    state: present
    groups: "wheel"
  with_items:
     - testuser1
     - testuser2

如果有定义了yaml格式的list在变量文件中,或变量段落,可以这样做:

with_items: "{{ somelist }}"

上面的例子,等价于:

- name: add user testuser1
  user:
    name: "testuser1"
    state: present
    groups: "wheel"
- name: add user testuser2
  user:
    name: "testuser2"
    state: present
    groups: "wheel"

所以呢,用loops更加灵活。

yum和apt模块可以用with_item来执行较少的包管理事务。

  • 注意
    用with_items来迭代的时候,其值不一定是字符串,还可以是哈希(hashes):
- name: add several users
  user:
    name: "{{ item.name }}"
    state: present
    groups: "{{ item.groups }}"
  with_items:
    - { name: 'testuser1', groups: 'wheel' }
    - { name: 'testuser2', groups: 'root' }

这样会更加灵活。

loops其实是with_<lookup>的组合,所以任何<lookup>都可以当做源来迭代,上面的例子就是用了items这个<lookup>

Looping over Hashes从哈希列表循环

假设我定义了这样一个变量:

---
users:
  alice:
    name: Alice Appleworth
    telephone: 123-456-7890
  bob:
    name: Bob Bananarama
    telephone: 987-654-3210

我现在要打印出名字和电话,可以用with_dict从哈希中取值:

tasks:
  - name: Print phone records
    debug:
      msg: "User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
    with_dict: "{{ users }}"

格式化输出,挺好用的。

Looping over Files 从文件中循环

with_file可以遍历文件列表的内容,item将按顺序设置为每个文件的内容:

---
- hosts: all

  tasks:

    # emit a debug message containing the content of each file.
    - debug:
        msg: "{{ item }}"
      with_file:
        - first_example_file
        - second_example_file

假如第一个文件内容为hello,第二个文件内容为world,那么上面的执行结果如下:

TASK [debug msg={{ item }}] ******************************************************
ok: [localhost] => (item=hello) => {
    "item": "hello",
    "msg": "hello"
}
ok: [localhost] => (item=world) => {
    "item": "world",
    "msg": "world"
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值