Ansible 动态清单脚本的玩具示例?

Toy example of an Ansible dynamic inventory script?

为了调试我的 'proper' 脚本 - 我尝试了一个玩具示例 - 但它也不起作用。

 echo {\"admin\": \"foo\", \"datacenter\": \"bar\"}

运行 它直接按预期运行:

%: ./test_inv --host blah
{"admin": "foo", "datacenter": "bar"}

但是:

%: ansible blah -i test_inv
ERROR: The file test_inv is marked as executable, but failed to execute correctly. If this is not supposed to be an executable script, correct this with `chmod -x test_inv`.

(我假设我不需要为这个玩具测试支持 --list,因为我从不以这种方式调用它)

编辑:这个问题最初的引用不正确,因此是这个初始答案。修复引用后问题仍然存在。

当您查看输出时,您会看到引号已从 echo 中删除。我认为 Ansible 只是以非常特殊的方式抱怨无效 JSON 数据。尝试像这样转义引号:

echo {\"admin\": \"Bob Smith\", \"datacenter\": 1}

编辑:基本上是您在问题中编辑的内容。它是这样工作的吗?

I'm assuming that I don't need to support --list for this toy test as I'm never invoking it in that way

这是你的问题。你知道他们怎么说假设,对吧?这里有一个快速测试供您尝试:

像这样创建清单文件:

#!/bin/bash

echo "Called as: $*" >> log

if [ "" == "--list" ] ; then
  echo '{ "localhost" : [ "localhost" ] }'
else
  echo '{ "some_variable": "some value" }'
fi

现在 运行 ansible 是这样的:

$ ansible -i ./hosts -m setup localhost

它应该 运行 没有错误并显示本地主机的所有事实。一旦完成:

$ cat log
Called as: --list
Called as: --host localhost

因此 ansible 调用可执行主机文件两次,一次使用 --list 参数,一次使用 --host <hostname>。 (如果您使用主机列表或包含多个主机的组调用 ansible,则将使用 --host 参数为每​​个主机调用一次脚本)。

由于您的清单脚本没有 return 有效主机列表 运行 它与 --list 参数一起抛出错误。