首页 > 解决方案 > 如何从 Ansible 的输出中查找缺失的数字

问题描述

我的播放列表包含以下内容

- set_fact:
    missnu={{out.stdout_lines}}
  register: missnu

- debug: msg={{missnu}}

我得到低于输出,

TASK [debug] **********************
ok: [192.168.0.10] => {
"msg": [
    "1 2 3 4"
]
}

这是预期的结果,但是我想找到其中缺少的数字。意思是如果结果是"1 2 4"OR"2 3 4"或者"2 4"我将如何得到那些缺失的数字?

标签: ansible

解决方案


您正在从某个命令打印标准输出,但我假设您知道预期结果并将其存储在某个变量中。为此,我会使用difference过滤器。

- hosts: localhost
  vars:
    sample_out_ml: [ 1, 2, 3, 4 ]
    sample_out_sl: "1 2 3 4"
    expected: [ 1, 2, 3 ,4 ,5 ]
  tasks:

  - name: Show difference when cmd outputs multi-line
    debug:
      msg: "{{ expected | difference(sample_out_ml) }}"

  - name: Show difference when cmd outputs on single line
    debug:
      msg: "{{ expected | difference(sample_out_sl.split(' ') | map('int') ) }}"

编辑根据您的评论,我提供了一个更强大的示例来说明您如何执行此操作。如果你要全神贯注于 Ansible,你应该尽量避免使用这些command模块。希望这可以帮助。


推荐阅读