如何使用 vault 在 ansible 中为一组主机提供 SSH 用户密码

Gab*_*vay 4 ansible ansible-vault ansible-inventory

考虑以下 Ansiblehosts文件:

[webservers]        
server1.example.com ansible_ssh_pass=1234567
server2.example.com ansible_ssh_pass=2345678
server3.example.com ansible_ssh_pass=3456789
Run Code Online (Sandbox Code Playgroud)

我想从保管库文件中包含这些密码值,并有一个hosts类似的文件(我的意图是有一个ini库存格式):

[webservers]        
server1.example.com ansible_ssh_pass={{ ssh_pass }}
server2.example.com ansible_ssh_pass={{ ssh_pass }}
server3.example.com ansible_ssh_pass={{ ssh_pass }}
Run Code Online (Sandbox Code Playgroud)

其中sss_pass变量来自文件host_vars夹中定义的拱形文件。

相关的 ansible 文件夹结构如下所示:

playbook.yml
inventories/
  atlanta/
    group_vars/
    hosts
    host_vars/
      server1.example.com
      server2.example.com
      server3.example.com
Run Code Online (Sandbox Code Playgroud)

但 ansible 正在抱怨:

[WARNING]:  * Failed to parse /root/hsm-ansible-deploy/inventories/atlanta/hosts with ini plugin: /root/hsm-ansible-deploy/inventories/atlanta/hosts:18: Expected key=value host variable assignment, got: ssh_pass
Run Code Online (Sandbox Code Playgroud)
  • 为什么我收到错误?
  • 如何将密码导入hosts文件?

Gab*_*vay 5

正如@techraf 所指出的,这只是一个语法问题。inihosts文件的正确写法是:

[webservers]        
server1.example.com ansible_ssh_pass="{{ ssh_pass }}"
server2.example.com ansible_ssh_pass="{{ ssh_pass }}"
server3.example.com ansible_ssh_pass="{{ ssh_pass }}"
Run Code Online (Sandbox Code Playgroud)

但我也找到了一个更优雅的解决方案,其中hosts文件更优雅,根本不提供ansible_ssh_pass变量hosts

[webservers]        
server1.example.com
server2.example.com
server3.example.com
Run Code Online (Sandbox Code Playgroud)

并使用group_vars/all来定义此变量:

---
ansible_ssh_pass: "{{ vault_ansible_ssh_pass }}"
Run Code Online (Sandbox Code Playgroud)

其中vault_ansible_ssh_pass在每个主机秘密定义的拱形文件喜欢host_vars/server1.example.com

---
vault_ansible_ssh_pass: "my secret password"
Run Code Online (Sandbox Code Playgroud)

然后使用以下方法加密这些文件ansible-vault

ansible-vault encrypt inventories/atlanta/host_vars/server*/vault --vault-password-file ~/.vault_pass.txt
Run Code Online (Sandbox Code Playgroud)

其中~/.vault_pass.txt以明文形式包含 ansible 保险库密码。