[英]Unable to fit the ansible code in playbook
This is a log file stored in Yaml Format. 这是以Yaml格式存储的日志文件。
My job is to find out the hostname which belongs to hostclass ess, which in this case the answer is host002. 我的工作是找出属于主机类ess的主机名,在这种情况下,答案是host002。
hostinfo:
'host001':
ip: 192.168.43.10
hostclass: 'puppet'
'host002':
ip: 192.168.43.11
hostclass: 'ess'
'host003':
ip: 192.168.43.21
hostclass: 'mdb'
i got one solution from some friend, but i am unable to fit it my ansible playbook. 我从一个朋友那里得到了一个解决方案,但是我无法适应我的烦人的剧本。
- debug:
msg: "{{ hostinfo|dictsort|selectattr('1.hostclass', 'equalto', 'ess')|first|first }}"
My playbook i am writing, It is wrong but i am not able to figure out how to fit the code in my playbook. 我正在写我的剧本,这是错误的,但我无法弄清楚如何将代码放入我的剧本中。 Can anyone help me in modifying the code of mine.
谁能帮我修改我的代码。
---
- hosts: somehost
gather_facts: no
vars_files:
file: sometext.yaml
name: sometext
- debug:
msg: "{{ hostinfo|dictsort|selectattr('1.hostclass', 'equalto', 'ess')|first|first }}"
You are using Ansible in a wrong way. 您以错误的方式使用Ansible。 It's possible to write a complicated query (You can use json_query filter for that), but it will be extremely hard to read and maintain.
可以编写一个复杂的查询(您可以使用json_query过滤器),但是它很难阅读和维护。
What you need to do: Instead of using hostclass: something
, use groups. 您需要执行的操作:代替使用
hostclass: something
,使用组。 Groups are designed for that. 组是为此目的而设计的。
Your inventory should look like this: 您的库存应如下所示:
[puppet]
host001 ip=192.168.43.10
[ess]
host002 ip=192.168.43.11
[mdb]
host003 ip=192.168.43.21
[hostinfo:children]
puppet
ess
mdb
After that it's trivial to query groups if you need them ( groups.puppet
for example), and it's easy to access their variables: (hostvars[groups.puppet][0]).ip
之后,如果需要查询组(例如
groups.puppet
),这很简单,而且很容易访问它们的变量: (hostvars[groups.puppet][0]).ip
Here's the code you've been looking for: 这是您一直在寻找的代码:
(on top of the query, you also have a problem with vars_files
) (在查询之上,您还遇到了
vars_files
的问题)
tasks:
- include_vars:
file: ./sometext.yaml
name: sometext
- debug:
msg: "{{ sometext.hostinfo | dict2items | json_query('[?value.hostclass==`ess`] | [0].key') }}"
The last filter in the query returns a single string, if there are multiple hosts with hostclass
equal to ess
, you need to change it and it will generate a list. 查询中的最后一个过滤器返回一个字符串,如果有多个主机
hostclass
等于ess
主机, hostclass
需要对其进行更改,它将生成一个列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.