Ansible - 找到主机变量的最大值和该主机的名称
Ansible - find the maximum value of a hostvar and the name of that host
我有一个 hostvar 增加的清单:
[nodes]
node_0 id=0
node_1 id=1
我想找到 id
的最大值和拥有它的主机。我找到了使用 for 循环 () 在节点上进行搜索的另一个答案,但我需要能够将此作为本地操作执行,因为我正在为 ec2 上的节点引导选择值。
我的解决方案:
- name: Find max id host
set_fact: id_max_host={{ groups['nodes'] | sort('id' | int) | last }}
- name: Find max id
set_fact: id_max={{ hostvars[id_max_host]['id'] }}
它获取组节点中的主机列表,按 hostvar 'id' 排序(它转换为 int,因为它们通常是字符串),然后只选择排序列表的最后一个。请注意,如果有多个相同的值,它会选择最后一个,而不是第一个。我用的是唯一ID,所以没问题。
这给了我最大的 ID 号和拥有它的主机的名称。它适用于本地和远程任务。我可以使用在远程主机上发现的事实来查看该主机是否应该 运行 分配给最大 ID 的任务:
- name: Some actions based on a result of previous tasks
action: # Run some actions
when: id_max_host == inventory_hostname
或者我可以使用它来确保我所有新启动的实例都在 ec2 上被标记为 ID 从 id_max + 1
开始并增加:
- name: tag instances
ec2_tag: region="{{ aws_region }}" resource="{{ item.id }}" aws_access_key="{{ aws_access_key }}" aws_secret_key="{{ aws_secret_key }}"
args:
tags:
Name: "node_{{ item.ami_launch_index | int + id_max | int + 1 }}"
id: "{{ item.ami_launch_index | int + id_max | int + 1 }}"
with_items: ec2Create.instances
我有一个 hostvar 增加的清单:
[nodes]
node_0 id=0
node_1 id=1
我想找到 id
的最大值和拥有它的主机。我找到了使用 for 循环 (
我的解决方案:
- name: Find max id host
set_fact: id_max_host={{ groups['nodes'] | sort('id' | int) | last }}
- name: Find max id
set_fact: id_max={{ hostvars[id_max_host]['id'] }}
它获取组节点中的主机列表,按 hostvar 'id' 排序(它转换为 int,因为它们通常是字符串),然后只选择排序列表的最后一个。请注意,如果有多个相同的值,它会选择最后一个,而不是第一个。我用的是唯一ID,所以没问题。
这给了我最大的 ID 号和拥有它的主机的名称。它适用于本地和远程任务。我可以使用在远程主机上发现的事实来查看该主机是否应该 运行 分配给最大 ID 的任务:
- name: Some actions based on a result of previous tasks
action: # Run some actions
when: id_max_host == inventory_hostname
或者我可以使用它来确保我所有新启动的实例都在 ec2 上被标记为 ID 从 id_max + 1
开始并增加:
- name: tag instances
ec2_tag: region="{{ aws_region }}" resource="{{ item.id }}" aws_access_key="{{ aws_access_key }}" aws_secret_key="{{ aws_secret_key }}"
args:
tags:
Name: "node_{{ item.ami_launch_index | int + id_max | int + 1 }}"
id: "{{ item.ami_launch_index | int + id_max | int + 1 }}"
with_items: ec2Create.instances