19

我在我的 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.
4

3 回答 3

33

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

version_file: "{{ lookup('file','/home/shasha/devOps/tests/packageFile.json') | from_json }}"
于 2016-04-19T21:58:22.993 回答
14

如果您需要读取JSON格式化文本并将其存储为变量,也可以通过include_vars.

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

    - debug: var=variable
于 2018-06-01T11:30:57.663 回答
4

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

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

于 2020-08-21T04:13:17.003 回答