Ansible - 仅在一台主机上根据结果查找最大值并运行操作 [英] Ansible - Find max value and run action based on a result only on one host

查看:25
本文介绍了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.

原来主机变量将整数转换回字符串,因此对它们的比较给出了意想不到的结果.为 max 过滤器内的每个主机变量引用重新应用 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 - 仅在一台主机上根据结果查找最大值并运行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆