这真的让我抓狂:我创建了一个简单的选择来测试 ansible playbook 中 MySQL 安装的结果:
- name: Simple select query to db playground
community.mysql.mysql_query:
login_db: {{ database name }}
login_user: {{ login_user }}
login_password: {{ login_password }}
query: SELECT * FROM equipment;
register: r_query
我将该任务的结果注册到变量中
r_query
。
当我调试此变量的 query_result 时,我得到以下信息:
ok: [db01] => {
"msg": [
[
{
"color": "white",
"id": 2,
"quant": 1,
"type": "shark"
},
{
"color": "grey",
"id": 4,
"quant": 2,
"type": "whale"
}
]
]
}
ok: [db02] => {
"msg": [
[
{
"color": "white",
"id": 2,
"quant": 1,
"type": "shark"
},
{
"color": "grey",
"id": 4,
"quant": 2,
"type": "whale"
}
]
]
}
ok: [db03] => {
"msg": [
[
{
"color": "white",
"id": 2,
"quant": 1,
"type": "shark"
},
{
"color": "grey",
"id": 4,
"quant": 2,
"type": "whale"
}
]
]
}
我已经检查了一些如何提取单个值的解释,但还没有任何效果。
如何获取第一台机器结果的第二个颜色值
db01
?
提前非常感谢
托马斯
让我们创建下面的库存,并将第二种颜色更改为red、green和blue进行测试
shell> cat hosts
all:
hosts:
db01:
r_query:
- - {color: white, id: 2, quant: 1, type: shark}
- {color: red, id: 4, quant: 2, type: whale}
db02:
r_query:
- - {color: white, id: 2, quant: 1, type: shark}
- {color: green, id: 4, quant: 2, type: whale}
db03:
r_query:
- - {color: white, id: 2, quant: 1, type: shark}
- {color: blue, id: 4, quant: 2, type: whale}
请参阅主机变量。该字典保留所有主机的所有变量。例如,
- debug:
var: hostvars[inventory_hostname].r_query.0.1.color
给予
ok: [db01] =>
hostvars[inventory_hostname].r_query.0.1.color: red
ok: [db02] =>
hostvars[inventory_hostname].r_query.0.1.color: green
ok: [db03] =>
hostvars[inventory_hostname].r_query.0.1.color: blue
到“访问第一台机器db01的结果的第二个颜色值”
- debug:
var: hostvars.db01.r_query.0.1.color
给予
ok: [db01] =>
hostvars.db01.r_query.0.1.color: red
ok: [db02] =>
hostvars.db01.r_query.0.1.color: red
ok: [db03] =>
hostvars.db01.r_query.0.1.color: red
当然,主机不需要 hostvars 来访问其变量
- debug:
var: r_query.0.1.color
给予
ok: [db01] =>
r_query.0.1.color: red
ok: [db02] =>
r_query.0.1.color: green
ok: [db03] =>
r_query.0.1.color: blue
用于测试的完整剧本示例
- hosts: all
tasks:
- debug:
var: hostvars[inventory_hostname].r_query.0.1.color
- debug:
var: hostvars.db01.r_query.0.1.color
- debug:
var: r_query.0.1.color