【问题标题】:ansible : how to use the variable ${item} from with_items in notify?ansible:如何在通知中使用 with_items 中的变量 ${item}?
【发布时间】:2013-08-21 21:59:10
【问题描述】:

我是 Ansible 的新手,我正在尝试创建多个虚拟环境(每个项目一个,项目列表在变量中定义)。

任务运行良好,我得到了所有文件夹,但是处理程序不起作用,它没有使用虚拟环境初始化每个文件夹。处理程序中的 ${item} 变量不起作用。 使用 with_items 时如何使用处理程序?

  tasks:    
    - name: create virtual env for all projects ${projects}
      file: state=directory path=${virtualenvs_dir}/${item}
      with_items: ${projects}
      notify: deploy virtual env

  handlers:
    - name: deploy virtual env
      command: virtualenv ${virtualenvs_dir}/${item}

【问题讨论】:

    标签: ansible


    【解决方案1】:

    一旦任何(逐项子)任务请求处理程序(已更改:结果中为是),处理程序就会被“标记”以执行。 那个时候handlers就像一个next常规任务,不知道itemized loop。

    可能的解决方案不是使用处理程序,而是使用额外任务 + 条件

    类似

    - hosts: all 
      gather_facts: false
      tasks:
      - action: shell echo {{item}}
        with_items:
        - 1 
        - 2 
        - 3 
        - 4 
        - 5 
        register: task
      - debug: msg="{{item.item}}"
        with_items: task.results
        when: item.changed == True
    

    【讨论】:

    • 这行得通!但是迭代字典列表会产生丑陋的输出。太糟糕了 with_items 不支持 python 表达式
    • 您也可以创建一个通知处理程序并将“with_items: task.results”放在那里。如果您担心丑陋的输出,您可以控制传递给“with_items:”子句的内容,如下所示:“with_items: task.results | selectattr('changed') | map(attribute='item') | list" (并且不要忘记在“debug: msg=...”中将“item.item”更改为“item”)
    【解决方案2】:

    总结前面的讨论,为现代 Ansible 做调整...

    - hosts: localhost,
      gather_facts: false
    
      tasks:
      - action: shell echo {{item}} && exit {{item}}
        with_items:
        - 1
        - 2
        - 3
        - 4
        - 5
        register: task
        changed_when: task.rc == 3
        failed_when: no
        notify: update service
    
      handlers:
      - name: update service
        debug: msg="updated {{item}}"
        with_items: >
          {{
          task.results
          | selectattr('changed')
          | map(attribute='item')
          | list
          }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      • 2017-07-03
      相关资源
      最近更新 更多