【问题标题】:Taking an ansible variable as a json one liner?将 ansible 变量作为 json 单衬里?
【发布时间】:2020-07-05 15:25:44
【问题描述】:

我想使用 Ansible 和模板模块填充配置文件。我将从另一个系统接收 json 有效负载,作为这种格式的一个衬里..

[
    {
        "customer": "customer_name",
        "license_type": "eval",
        "customFields": {
            "test": 1234
        }
    },
    {
        "customer": "customer_name",
        "license_type": "eval",
        "customFields": {
            "test": 123
        }
    }
]

压缩为单行:

[ { "customer": "customer_name", "license_type": "eval", "customFields": { "test": 1234 } }, { "customer": "customer_name", "license_type": "eval", "customFields": { "test": 123 } } ]

在我的 ansible 中,我将一个变量 (entire_lic) 设置为整个单行,然后在模板模块中我有一个名为 license.conf 的模板:

{{ entire_lic }}

这可行,但它不是很好地打印成可读的 json。无论如何我可以做到这一点吗?我试过了

{{ entire_lic | to_nice_json }}

但这似乎不起作用。任何帮助将不胜感激!

【问题讨论】:

  • 查看调试模块并使用var属性。

标签: json ansible jinja2


【解决方案1】:

问:“打印出来的 JSON 格式不美观,可读性好。有什么办法可以做到这一点吗?”

A:下面的剧本可以完成这项工作

shell> cat play.yml
- hosts: localhost
  vars:
    entire_lic: [{"customer": "customer_name", "license_type": "eval", "customFields": {"test": 1234}}, {"customer": "customer_name", "license_type": "eval", "customFields": {"test": 123}}]
  tasks:
    - debug:
        var: entire_lic
    - template:
        src: license.conf.j2
        dest: license.conf
shell> cat license.conf.j2 
{{ entire_lic | to_nice_json }}

给予

PLAY [localhost] ***

TASK [debug] ***
ok: [localhost] => {
    "entire_lic": [
        {
            "customFields": {
                "test": 1234
            }, 
            "customer": "customer_name", 
            "license_type": "eval"
        }, 
        {
            "customFields": {
                "test": 123
            }, 
            "customer": "customer_name", 
            "license_type": "eval"
        }
    ]
}

TASK [template] ***
changed: [localhost]

PLAY RECAP ***
localhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
shell> cat license.conf
[
    {
        "customFields": {
            "test": 1234
        },
        "customer": "customer_name",
        "license_type": "eval"
    },
    {
        "customFields": {
            "test": 123
        },
        "customer": "customer_name",
        "license_type": "eval"
    }
]

【讨论】:

  • 感谢弗拉基米尔,这行得通。你能帮我用ansible把整个json作为命令行变量传递吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-10
  • 1970-01-01
  • 2023-02-07
  • 1970-01-01
  • 1970-01-01
  • 2019-06-20
相关资源
最近更新 更多