【问题标题】:ansible with_items stdout_lines filteransible with_items stdout_lines 过滤器
【发布时间】:2018-11-06 17:53:02
【问题描述】:

我在一个变量中有一个列表,我需要对它执行一个 shell 命令。

   - name: Set Percentage value to "yes" to all disks for NFS SERVERS
    shell: |
      NUM=$(cat -n {{ cdm_path }} |\
            sed -n "/<disk>/,/<\/disk>/p" |\
            sed -n "/<alarm>/,/<\/alarm>/p" |\
            sed -n "/<fixed>/,/<\/fixed>/p" |\
            sed -n "/<{{ item }}>/,/<\/{{ item }}>/p" |\
            awk '/ percent = no/ {printf "%d", $1}')"s";
      if [ "${NUM}" != "s" ]; then
          sed -i "${NUM}/no/yes/g" {{ cdm_path }};
          echo "file_was_changed" ;
      fi
    with_items: "{{ result.stdout_lines }}"
    register: percent_nfs
    when: ansible_hostname == "nfs01" or
          ansible_hostname == "nfs02"
    changed_when: '"file_was_changed" in percent_nfs.stdout'

结果包含如下内容:

#
#boot
#emc#dest#admin
#emc#dest#dbdata
#emc#dest#dbbackups
#emc#dest#lsgdev
#emc#dest#lsgdev_dev
#emc#dest#lsgdev_stage
#emc#dest#lsglegacy

我在 ansible_hostname == nfs01 或 nfs02 时运行此代码

我需要为多个设备保持“结果”相同,但我只想使用名称中不包含 *lsg* 的项目执行 shell 命令。

如何进一步过滤 with_items 行以仅使用过滤后的项目?

【问题讨论】:

  • 你不能只使用将and "lsg" not in item 添加到when: 条件吗?

标签: ansible


【解决方案1】:

对于从result.stdout_lines 中排除项目的问题,可能有一个更优雅的解决方案,其中不包含子字符串lsg

但是,一种可能的解决方案是结合使用 Ansible difference set theory filter 和 Jinja2 select 过滤器(类似于下面的 answer)来过滤您的项目,如下所示:

...
with_items: "{{ result.stdout_lines|difference(result.stdout_lines|select('search','lsg')|list) }}"
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 1970-01-01
    相关资源
    最近更新 更多