本文介绍了Ansible-仅根据一台主机上的结果查找最大值并执行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组名为"db"的主机,其节点数可能有所不同.每个节点都有一个事实("seqno"),它是一个整数.

I have a group of hosts named "db" with number of nodes that may vary. Each node has a fact ("seqno") which is an integer number.

我需要在所有主机之间比较这一事实并选择最大值,然后在具有该最大值的一台(并且只有一台)主机上运行一些操作.如果多个节点具有相同的值,则应选择第一个节点.

I need to compare this fact among all hosts and choose maximum value, then run some actions on one (and only one) host that has this maximum value. In case of multiple nodes having the same value, first node should be chosen.

我尝试过这种方法:

- name: find max seqno value
  set_fact: seqno_max={{ [hostvars[groups['db'][0]]['seqno'], hostvars[groups['db'][1]]['seqno']] | max }}

- name: find single hostname to use as a node with max seqno
  set_fact: seqno_max_host={{ hostvars[item]['inventory_hostname'] }}
  with_items: groups['db'][::-1] # reverse list. if two nodes have the same seqno, use first node as starting point.
  when: hostvars[item]['seqno'] == seqno_max

- name: Some actions based on a result of previous tasks
  action: # Run some actions
  when:  seqno_max_host == inventory_hostname

但是由于某些原因,"max"运算符总是返回第二个值.同样,这种方法仅在具有任意指定数量的主机的情况下才有效-我想有一种适用于任意数量的主机的解决方案.

But for some reason "max" operator always return the second value. Also this approach is valid only if you have arbitrary specified number of hosts - I would like to have a solution that works for any number of hosts.

原来,hostvars将整数转换回字符串,因此,对它们进行比较会得出意外的结果.为 max 过滤器中的每个hostvars引用重新应用 int 过滤器有帮助.尽管如此,仍然存在问题,如何在上面修复代码以使其可用于任意数量的主机-是否有可能无需编写自定义过滤器或创建临时模板?

It turned out that hostvars converted integer back to string, so comparison of them gave unexpected results. Reapplying int filter for each hostvars reference inside max filter helped. Still, questions remains how to fix code above to make it work for any number of hosts - is it possible without writing custom filters or creating temporary templates?

推荐答案

我最终得到的解决方案虽然不漂亮,但却可以解决问题.

I ended up with a solution which is not beautiful, but works.

- shell: "if [ {{ hostvars[inventory_hostname]['seqno'] }} -lt {{ hostvars[item]['seqno'] }} ]; then echo {{ hostvars[item]['seqno'] }}; fi"
  with_items: groups['db']
  register: result_c

- set_fact: seqno_max={{ hostvars[inventory_hostname]['seqno'] }}
  when: result_c.results | map(attribute='stdout') | join('') == ""

这篇关于Ansible-仅根据一台主机上的结果查找最大值并执行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 18:37