首页 > 解决方案 > Ansible 2.7 如何遍历用户列表并运行一组任务

问题描述

我有一组任务,我想通过循环重复使用 Ansible 2.7 循环的用户列表。我的简单剧本如下所示:

---
- hosts: localhost
  gather_facts: no
  vars:
    username: "{{ item }}"

  tasks:
    - debug:
        msg: "running as {{ username }}"

    - name: echo the username
      command: "/bin/echo echoing {{ username }}"

      loop:
        - joe
        - fred

我在这里做错了什么?

标签: ansible

解决方案


为了执行一组子任务,尤其是在循环结构下,你会想要include_tasks:,像这样:

- hosts: all
  tasks:
  - include_tasks: the-other-tasks.yml
    with_items:
    - alpha
    - beta

(我使用它是with_items:因为它在这个例子中是最简洁的,但是 AFAIK 这只是loop:它及其loop_var:朋友的合成糖,所以它应该按预期工作)


推荐阅读