Ansible:如何在 group_vars 中使用字典中的常规变量和加密变量?

Ansible: How to use regular and encrypted variables from dictionaries in group_vars?

我正在尝试将我的 group_vars 拆分为未加密的 "vars" 和加密的 "vault"。由于官方文档很短,我遵循了一个非常详尽的教程 here。通过他们的示例设置,我可以让它工作。 vars 文件引用拱形部分,如下所示:

mysql_port: 3306
mysql_host: 10.0.0.3
mysql_user: fred
mysql_password: "{{ vault_mysql_password }}"

现在我的真实用例在这些文件中有字典,如下所示:

---
vhosts:
    vhost1:
      mysql_user: fred
      mysql_password: "{{ vault_mysql_password }}"
    vhost2:
      mysql_user: frida
      mysql_password: "{{ vault_mysql_password }}"

我的保管库文件以类似的方式组织,但这是行不通的:

---
vhosts:
    vhost1:
      vault_mysql_password: secret1
    vhost2:
      vault_mysql_password: secret2

我得到的结果是:Ansible 确实找到了所有 encrypted 变量。但它声称 regular 未定义。这是调试命令的输出,其中调试输出中缺少 mysql_user:

ansible --ask-vault-pass -m debug -a 'var=hostvars[inventory_hostname]' database
Vault password: 
localhost | SUCCESS => {
    "hostvars[inventory_hostname]": {
        "ansible_check_mode": false, 
        "ansible_connection": "local", 
        "ansible_playbook_python": "/usr/bin/python", 
        "ansible_version": {
            "full": "2.4.1.0", 
            "major": 2, 
            "minor": 4, 
            "revision": 1, 
            "string": "2.4.1.0"
        }, 
        "group_names": [
            "database"
        ], 
        "groups": {
            "all": [
                "localhost"
            ], 
            "database": [
                "localhost"
            ], 
            "ungrouped": []
        }, 
        "inventory_dir": "/home/user/ansible/vault-test", 
        "inventory_file": "/home/user/ansible/vault-test/hosts", 
        "inventory_hostname": "localhost", 
        "inventory_hostname_short": "localhost", 
        "omit": "__omit_place_holder__2aa3b7d59a4009e07f27cf11ffabda560533de17", 
        "playbook_dir": "/home/user/ansible/vault-test", 
        "vhosts": {
            "vhost1": {
                "vault_mysql_password": "secret1"
            }, 
            "vhost2": {
                "vault_mysql_password": "secret2"
            }
        }
    }
}

非常感谢任何提示我必须做什么!还是我想做一件不可能的事?

加密变量的行为方式与未加密变量相同。在您的情况下,您只需使用来自拱形文件的 vhosts 覆盖普通 vars 文件中的 vhosts var。

这将起作用:

---
vhosts:
    vhost1:
      mysql_user: fred
      mysql_password: "{{ vault_vhosts.host1.vault_mysql_password }}"
    vhost2:
      mysql_user: frida
      mysql_password: "{{ vault_vhosts.host2.vault_mysql_password }}"

---
vault_vhosts:
    vhost1:
      vault_mysql_password: secret1
    vhost2:
      vault_mysql_password: secret2

或者这样:

---
vhosts:
    vhost1:
      mysql_user: fred
      mysql_password: "{{ vault_vhost1_mysql_password }}"
    vhost2:
      mysql_user: frida
      mysql_password: "{{ vault_vhost2_mysql_password }}"

---
vault_vhost1_mysql_password: secret1
vault_vhost2_mysql_password: secret2