21

I have a json file in the same directory where my ansible script is. Following is the content of json file:

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

I am trying to to download these packages using get_url. Following is the approach:

---
- 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

The first task is printing the content of the file correctly but in the second task, I am getting the following error:

[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.
Shasha99
  • 1,746
  • 2
  • 16
  • 30

3 Answers3

39

You have to add a from_json jinja2 filter after the lookup:

version_file: "{{ lookup('file','/home/shasha/devOps/tests/packageFile.json') | from_json }}"
Strahinja Kustudic
  • 4,175
  • 1
  • 24
  • 18
16

In case if you need to read a JSON formatted text and store it as a variable, it can be also handled by include_vars .

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

    - debug: var=variable
Akif
  • 6,018
  • 3
  • 41
  • 44
7

for future visitors , if you are looking for a remote json file read. this won't work as ansible lookups are executed in the local

you should use a module like Slurp

EnzoR
  • 3,107
  • 2
  • 22
  • 25
Arjun Dandagi
  • 160
  • 3
  • 14