Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read json file using ansible

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.
like image 953
Shasha99 Avatar asked Feb 15 '16 07:02

Shasha99


People also ask

Can Ansible read JSON?

The data for these models is exchanged as key/value pairs and encoded using different formats. JSON, which is widely used in Ansible, is one of them.

Can Ansible use JSON format?

By default, an Ansible inventory file uses the INI configuration format. You can also use JSON (JavaScript Object Notation) configuration format for Ansible inventory files as well.

What is JSON Ansible?

April 6, 2021. Parsing structured JSON data in Ansible playbooks is a common task. Nowadays, the JSON format is heavily used by equipment vendors to represent complex objects in a structured way to allow programmatic interaction with devices.

How do you parse Ansible output?

Ansible is a popular automation framework that allows you to configure any number of remote hosts in a declarative and idempotent way. A common use-case is to run a shell command on the remote host, return the STDOUT output, loop through it and parse it.


2 Answers

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

version_file: "{{ lookup('file','/home/shasha/devOps/tests/packageFile.json') | from_json }}"
like image 189
Strahinja Kustudic Avatar answered Oct 08 '22 22:10

Strahinja Kustudic


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
like image 37
Akif Avatar answered Oct 08 '22 23:10

Akif