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

时间:2017-11-02 10:17:40

标签: ansible ansible-vault

我正在尝试将我的group_vars拆分为未加密的" vars"并加密"金库"。由于官方文档非常简短,我在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确实找到了所有加密的变量。但它声称​​常规未定义。以下是debug命令的输出,其中调试输出中缺少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"
            }
        }
    }
}

我非常感谢任何暗示我必须做的事情!或者我想做一件不可能的事情?

1 个答案:

答案 0 :(得分:1)

加密变量的行为与未加密变量的行为相同。在您的情况下,您只需从带有# set user to a user with permission to run the scripts (root is overkill) user=root case "$1" in start) sudo -u ${user} /home/script.sh ${1} >> /home/scriptlog.log ;; 的普通变量文件覆盖vhosts var来自拱形变量。

这将有效:

vhosts

或者这个:

---
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