Python Ansible 评估任务的输出

标签 python ansible task

我是 Ansible 的新用户,正在尝试了解如何使用 Ansible 执行自动化任务。我想连接到多个服务器并cat一个文件以获取项目列表(list_2)。然后我想检查该项目列表是否在另一个列表(list_1)中。然后我想打印一个表格,显示 list_2 中的哪些项目在 list_1 中?有没有办法通过 Ansible 来完成此任务而不需要推送脚本?

下面收集两个列表并将它们放入寄存器中,但我不确定如何评估 list_2 中的项目是否包含在 list_1 中。

list_1 = 'red, green, yellow, blue, orange, purple'
list_2 = 'green, blue, purple'

hosts: myhost

tasks:
- name: get list 1
  shell: "cat /dir/list_1"
  register: list_1

tasks:
- name: get list 2
  shell: "cat /dir/list_2"
  register: list_2

期望的输出:

list_1  list2inlist1
red     No
green   Yes
blue    Yes
orange  No
purple  Yes

最佳答案

这将接近您想要的输出

- name: print intersection
  debug:
    msg: "{{ item }}"
  with_items: "{{ list_1.stdout.split(', ') }}"
  when: item in list_2.stdout.split(', ')

如果您确实想要与所需输出相同的语法,我认为模板将是最简单的方法。

在您的任务中:

- name: print intersection template
  template:
    src: intersection.j2
    dest: /some_dir/intersection.txt

在intersection.j2中:

list1   list2inlist1
{% for item in list_1.stdout.split(', ') %}
{% if item in list_2.stdout.split(', ') %}
{{ item }}    YES
{% else %}
{{ item }}    NO
{% endif %}
{% endfor %}

关于Python Ansible 评估任务的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45123304/

相关文章:

python - 整列填充在 python 中的列表中

python - 使用 pandas 进行基于 NLTK 的文本处理

json - 使用 Ansible 向 json 文件添加新的键值

loops - 如何在 Ansible 中循环通过通配符标识的主机?

python-3.x - 升级 ansible 以在 Controller 上使用 python3

C#任务多队列节流

python - 如何在自定义 Op 中改变 Tensorflow 变量?

python - 在 Python 中列出问题

scala - 在任务中运行任务并在 sbt 中评估其结果

c# - 'await' 什么时候立即离开方法,什么时候不离开?