如何使用Ansible读取JSON文件

23

我有一个JSON文件与我的Ansible脚本在同一目录中。以下是JSON文件的内容:

{ "resources":[
           {"name":"package1", "downloadURL":"path-to-file1" },
           {"name":"package2", "downloadURL": "path-to-file2"}
   ]
}

我正在尝试使用get_url下载这些软件包。以下是我的方法:

---
- hosts: localhost
  vars:
    package_dir: "/var/opt/"
    version_file: "{{lookup('file','/home/shasha/devOps/tests/packageFile.json')}}"

  tasks:
    - name: Printing the file.
      debug: msg="{{version_file}}"

    - name: Downloading the packages.
      get_url: url="{{item.downloadURL}}" dest="{{package_dir}}" mode=0777
      with_items: version_file.resources

第一个任务是正确地打印文件内容,但在第二个任务中,我遇到了以下错误:

[DEPRECATION WARNING]: Skipping task due to undefined attribute, in the future this
will be a fatal error.. This feature will be removed in a future release. Deprecation
warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.

它在我的2.0.0.2版本中可以工作。你使用的Ansible版本是什么? - graphite
版本号为2.1.0。 - Shasha99
看起来 JSON 文件有一些问题。对于一些文件可以工作,但对于另一些文件则不能。 - Shasha99
3个回答

40

在查找后面添加一个名为from_json的jinja2过滤器:

version_file: "{{ lookup('file','/home/shasha/devOps/tests/packageFile.json') | from_json }}"

16

如果您需要读取以JSON格式化的文本并将其存储为变量,则可以使用include_vars来处理。

- hosts: localhost
  tasks:
    - include_vars:
        file: variable-file.json
        name: variable

    - debug: var=variable

9

针对未来的访客,如果你正在寻找远程json文件读取方式。这种方法行不通,因为ansible查询需要在本地执行。

你应该使用像Slurp这样的模块。


谢谢你,这让我省了不少阅读的时间! - Graham Nicholls
用于 slurp.. register: version_file_data 然后 {{ version_file_data['content'] | b64decode | from_json }}。只是为了方便大家,添加了这个。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接