ansible - 使用 ansible 动态添加子组
问题描述
我想动态重现以下静态库存:
novaclient ansible_connection=local
[masters]
192.168.13.236
[nodes]
192.168.13.201
192.168.13.237
[cluster:children]
masters
nodes
阅读 ansible 文档,该add_host
模块似乎是正确的候选者,因为它旨在将主机(或者一个组)添加到 ansible-playbook in-memory inventory。这是我的剧本:
- hosts: all
connection: local
vars:
ips_per_group:
- ["masters", "192.168.13.236"]
- ["nodes" , "192.168.13.201"]
- ["nodes" , "192.168.13.237"]
tasks:
- name: add host dynamically
add_host:
name: "{{ item[1] }}"
groups: "{{ item[0] }}"
loop: "{{ ips_per_group }}"
- name: add masters and nodes groups to cluster group
add_host:
name: "{{ item[0] }}"
groups: "cluster"
loop: "{{ ips_per_group }}"
- name: test
debug:
var: groups
运行该剧本会触发以下警告:
[WARNING]: Found both group and host with same name: masters
[WARNING]: Found both group and host with same name: nodes
据我了解,这些警告来自这样一个事实,masters
并且nodes
尚未被宣布children
为该cluster
组的成员。尝试以下语法:
- name: add masters and nodes groups to cluster group
add_host:
name: "{{ item }}"
groups: "cluster:children"
loop:
- masters
由于groups
名称中的冒号触发以下警告:
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
你有什么想法在没有任何警告的情况下这样做吗?
谢谢
解决方案
可以使用group_by – 根据事实创建 Ansible 组。使用修改后的数据结构,使示例更简单,下面的剧本展示了它是如何工作的。
- name: 1.Create my_groups
hosts: localhost
gather_facts: false
vars:
ips_per_group:
192.168.13.236:
my_groups: ['masters']
my_children_group: 'cluster'
192.168.13.201:
my_groups: ['nodes']
my_children_group: 'cluster'
192.168.13.237:
my_groups: ['nodes']
my_children_group: 'cluster'
tasks:
- name: add host dynamically
add_host:
name: "{{ item.key }}"
groups: "{{ item.value.my_groups }}"
group_children: "{{ item.value.my_children_group }}"
loop: "{{ ips_per_group|dict2items }}"
- debug:
var: groups
- name: 2.Create children for group masters
hosts: masters
gather_facts: false
tasks:
- name: add hosts to children groups
group_by:
key: "{{ group_children }}"
- debug:
var: groups
- name: 3.Create children for group nodes
hosts: nodes
gather_facts: false
tasks:
- name: add hosts to children groups
group_by:
key: "{{ group_children }}"
- debug:
var: groups
- name: 4.Test group cluster
hosts: cluster
gather_facts: false
tasks:
- debug:
var: group_children
- debug:
var: groups
- name: 5.Print groups
hosts: localhost
tasks:
- debug:
var: groups
播放“5.Print groups”给出
"groups": {
"all": [
"192.168.13.201",
"192.168.13.236",
"192.168.13.237"
],
"cluster": [
"192.168.13.236",
"192.168.13.201",
"192.168.13.237"
],
"masters": [
"192.168.13.236"
],
"nodes": [
"192.168.13.201",
"192.168.13.237"
],
"ungrouped": []
}
推荐阅读
- python - 图:从边缘列表更改为邻接列表表示的时间和空间复杂度,反之亦然
- web-services - 如果不公开 s3 存储桶,我们如何托管网站
- javascript - 无法弄清楚为什么我的 phantomJS 脚本没有显示状态并为页面拍照
- regex - 如何使用正则表达式处理某些字符的拆分
- r - 将双重响应分成不同的因子水平
- rest - 在 Safari 或 Firefox 中,缺少尾随空格会破坏对带有 axios 的服务器的请求
- php - Bash 在运行“pecl install ibm_db2”时拒绝转义字符串
- python - Python 继承的类行为
- python - 条件 (a*a + b*b = c*c) 在使用 python 的列表中满足
- python - 只导入我的一列的最大值