如何将变量放入Ansible中的变量中?

时间:2019-02-12 08:45:14

标签: ansible

我有一个带有数据库凭据的JSON文件,并且想要创建带有外部参数的剧本来在数据库之间进行迁移。

首先,我得到JSON数据。另外,我有2个变量,例如潜在的外部参数。


    vars:
       db_credentials: "{{ lookup('file','/etc/ansible-configs/config/db-migration/db-credentials.json') | from_json }}"
       db_from: "{{ _db_from }}"
       db_to: "{{ _db_to }}"

接下来,我将通过最近解析的JSON的键值来获得价值。


    - name: "Test"
      debug:
        msg: "{{ lookup('dict', db_credentials.project_1.dev_1) | selectattr('key', 'defined') | map (attribute='value') | first }}"

JSON:


    {
      "project_1": {
        "dev_1": {
          "server": "172.31.40.208",
          "port": "5432",
          "db": "db_dev_1",
          "login": "login",
          "password": "passw0rd"
        },
        "project_2": {
          "server": "172.31.40.208",
          "port": "5432",
          "db": "db_uat_1",
          "login": "login",
          "password": "passw0rd"
        }
      }
    }

问题是我想传递诸如project_1.dev_1之类的参数。


    # ansible-playbook playbooks/migrate-db.yml -e '{"db_from":"project_1.dev_1"}'

如何在代码中使用它?

我想要这样的东西:


    msg: "{{ lookup('dict', db_credentials.{{ db_from }}) | selectattr('key', 'defined') | map (attribute='value') | first }}"

但这不起作用。

1 个答案:

答案 0 :(得分:2)

对于您的特定情况,您可以简单地使用json_query过滤器,因为project_1.dev_1是有效的JMESPath查询:

- debug:
    msg: "{{ db_credentials | json_query(db_from) }}"

会给您:

{
    "server": "172.31.40.208",
    "port": "5432",
    "db": "db_dev_1",
    "login": "login",
    "password": "passw0rd"
}