ansible - Ansible:从库存中检索数据
问题描述
我需要从库存文件中检索 bob_server 的 IP。我不清楚在 , 和 中使用filter
什么lookup
组合when
?根据库存文件bob_server
和alice_server
名称可以更改,但app_type
不会更改。我的剧本逻辑显然是错误的,有人可以指导我获取IP地址的正确方法吗app_type = bob
我当前的库存文件:
---
all:
hosts:
children:
bob_server:
hosts: 10.192.2.6
vars:
app_type: bob
alice_server:
hosts: 10.192.2.53
vars:
app_type: alice
我的剧本
---
- hosts: localhost
name: Retrive data
tasks:
- name: Set Ambari IP
set_fact:
ambariIP: "{{ lookup('hosts', children) }}"
when: "hostvars[app_type] == 'bob'"
解决方案
鉴于库存
shell> cat hosts-01
---
all:
hosts:
children:
bob_server:
hosts: 10.192.2.6
vars:
app_type: bob
alice_server:
hosts: 10.192.2.53
vars:
app_type: alice
简单的选项是使用ansible-inventory
,例如
- hosts: localhost
tasks:
- command: ansible-inventory -i hosts-01 --list
register: result
- set_fact:
my_inventory: "{{ result.stdout|from_yaml }}"
- debug:
var: my_inventory.bob_server.hosts
给
my_inventory.bob_server.hosts:
- 10.192.2.6
如果您想自己解析文件,请将其读入字典并展平路径,例如(安装 ansible.utils ansible-galaxy collection install ansible.utils
)
- include_vars:
file: hosts-01
name: my_hosts
- set_fact:
my_paths: "{{ lookup('ansible.utils.to_paths', my_hosts) }}"
- debug:
var: my_paths
给
my_paths:
all.children.alice_server.hosts: 10.192.2.53
all.children.alice_server.vars.app_type: alice
all.children.bob_server.hosts: 10.192.2.6
all.children.bob_server.vars.app_type: bob
all.hosts: null
现在选择键结束bob_server.hosts
- set_fact:
bob_server_hosts: "{{ my_paths|
dict2items|
selectattr('key', 'match', '^.*bob_server\\.hosts$')|
items2dict }}"
给
bob_server_hosts:
all.children.bob_server.hosts: 10.192.2.6
并选择 IP
- set_fact:
bob_server_ips: "{{ bob_server_hosts.values()|list }}"
给
bob_server_ips:
- 10.192.2.6
清单缺少组的概念。请参阅清单基础:格式、主机和组。通常, 的值children
是一组主机。在此清单中, 的值children
是单个主机。这在概念上是错误的,但仍然有效,例如
- hosts: bob_server
gather_facts: false
tasks:
- debug:
var: inventory_hostname
给
shell> ansible-playbook -i hosts-01 playbook.ym
...
TASK [debug] ****************************************************
ok: [10.192.2.6] =>
inventory_hostname: 10.192.2.6
推荐阅读
- angular - 多次调用 Angular Validator 函数
- java - 在 CorDapp 上本地部署节点时出现异常 - 节点信息生成
- javascript - 猫头鹰旋转木马导航箭头造型
- linux - linux开发VFS时需要内存映射吗
- asp.net-web-api - 使用 webapi-2 查找调用 api 的 url
- regex - 使用正则表达式提取(重复)包含括号的组
- ruby-on-rails - 对订单中的商品进行分组和计数
- python - 在 Python 中为脚本或交互式会话设置日志记录
- google-app-maker - 如何将 AppMaker 应用程序导出为 zip 文件?
- mongodb - 使用 $lookup “填充”字段而不覆盖现有值