我有一个自定义事实,用于我的服务器检索客户数据。这在机器上运行良好并返回有效的 json。我可以将输出写入另一个事实文件,这也可以正常工作。但是当我执行 ansible 设置时,脚本会将所有数据作为一个键中的字符串和一个空值返回,如下所示:
"custom_fact": {
"{data...}": {}
}
这是我的事实脚本:
#!/bin/bash
#{{ ansible_managed }}
### extracting information from moodle instances
cd /home/vhosts/moodle
function getinstances() {
MDL_INSTANCES=`find * -maxdepth 0 -not -name "_*" |xargs echo`
}
getinstanceinfo() {
INSTANCE_ARRAY=()
for i in $MDL_INSTANCES
do
source /home/vhosts/moodle/$i/_update.conf
firstname="$(mysql -u $UM_DBUSER -p$UM_DBPASS -h mysql -e 'SELECT firstname FROM mdl_user WHERE id=2;' $UM_DBNAME)"
firstname=${firstname#firstname}
lastname="$(mysql -u $UM_DBUSER -p$UM_DBPASS -h mysql -e 'SELECT lastname FROM mdl_user WHERE id=2;' $UM_DBNAME)"
lastname=${lastname#lastname}
email="$(mysql -u $UM_DBUSER -p$UM_DBPASS -h mysql -e 'SELECT email FROM mdl_user WHERE id=2;' $UM_DBNAME)"
email=${email#email}
supportemail="$(mysql -u $UM_DBUSER -p$UM_DBPASS -h mysql -e "SELECT value FROM mdl_config WHERE name='supportemail';" $UM_DBNAME)"
supportemail=${supportemail#value}
string="\"domain\":\"$i\",\"firstname\":\"$firstname\",\"lastname\":\"$lastname\",\"email\":\"$email\",\"supportemail\":\"$supportemail\""
string=$(echo $string | tr -d '\n')
INSTANCE_ARRAY+=("$string")
done
}
# creating json for ansible extraction
writetostdout() {
printf '['
for (( i=0; i<${#INSTANCE_ARRAY[@]}-1; i++ ))
do
printf "{ ${INSTANCE_ARRAY[$i]} },"
done
printf "{ ${INSTANCE_ARRAY[-1]} }"
printf ']'
}
getinstances
getinstanceinfo
writetostdout
有人知道为什么这不管用吗?我真的被困住了。谢谢帮助。
答案1
如果我没记错的话,你的 JSON 输出看起来像这样:
[{
"domain": "foo",
...
},{
"domain": "foo",
...
},{
"domain": "foo",
...
}]
所以这是一个列表,它肯定是有效的 JSON,但 Ansible 不知道如何处理这个列表。您需要给它一个密钥,以便 Ansible 知道应该将列表分配给哪个事实:
{
"myList": [{
"domain": "foo",
...
},{
"domain": "foo",
...
},{
"domain": "foo",
...
}]
}