如何使用ansible读取json文件

Sha*_*a99 16 ansible ansible-playbook ansible-2.x

我的ansible脚本所在的目录中有一个json文件.以下是json文件的内容:

{ "resources":[
           {"name":"package1", "downloadURL":"path-to-file1" },
           {"name":"package2", "downloadURL": "path-to-file2"}
   ]
}
Run Code Online (Sandbox Code Playgroud)

我试图使用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
Run Code Online (Sandbox Code Playgroud)

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

[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.
Run Code Online (Sandbox Code Playgroud)

Str*_*dic 23

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

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


Arj*_*agi 9

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

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


Aki*_*kif 7

如果您需要阅读JSON格式化的文本并将其存储为变量,也可以使用进行处理include_vars

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

    - debug: var=variable
Run Code Online (Sandbox Code Playgroud)