如何使用ansible读取json文件

时间:2016-02-15 07:33:33

标签: ansible ansible-playbook ansible-2.x

我的ansible脚本所在的目录中有一个json文件。以下是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.

3 个答案:

答案 0 :(得分:18)

您必须在查找后添加from_json jinja2过滤器:

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

答案 1 :(得分:4)

如果您需要阅读JSON格式的文本并将其存储为变量,则include_vars也可以处理它。

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

    - debug: var=variable

答案 2 :(得分:0)

对于将来的访问者,如果您正在寻找读取的远程json文件。这行不通 因为ansible查找是在本地执行的

您应该使用类似Slurp

的模块