在 ansible/jinja2 变量文件中将变量设置为命令输出

Setting Variable to Command Output in ansible/jinja2 Variable file

我正在根据不同部署环境的 jinja2 模板在 ansible 中创建一个配置文件。为此,我为每个环境准备了一个 yaml 文件,如下所示:

Serverip: 127.0.0.1
Login:
  Username: Rudolf
  Password: rudolfssecret

现在,对于某些环境,我想将某些变量放入库中并使用命令行工具(如 this one)提取它们。

这可以通过从 vault 中获取值并将它们与变量 File 以某种方式组合来完成。但是通过这种方式,秘密变量将从变量文件中完全删除。看到文件的人可能会认为这些变量丢失或不存在。

我更喜欢这样的东西:

Serverip: 127.0.0.1
Login:
  Username: Rudolf
  Password: {{shell: keepass-cli extract-value -f keepassfile -name Password}}

因此,当 ansible 从文件加载变量时,它会使用 shell 命令的输出来填充该值。

这可能吗?

你可以参考 Playbook Best Practices – Variables and Vaults 这件事。

...create two files named vars and vault. Inside of the vars file, define all of the variables needed, including any sensitive ones. Next, copy all of the sensitive variables over to the vault file and prefix these variables with vault_. You should adjust the variables in the vars file to point to the matching vault_ variables and ensure that the vault file is vault encrypted.

如果您更喜欢外部密码管理工具而不是保管库,您仍然可以遵循此建议。
在您的情况下,按如下方式定义 vars 文件:

Serverip: 127.0.0.1
Login:
  Username: Rudolf
  Password: "{{ encrypted_password }}"

并且在 playbook 执行期间确保从您的密码管理工具中获取 encrypted_password