'Ansible playbook to fetch JSON file from an API via 'uri'
I wrote an Ansible playbook intend to fetch the list from an API as JSON file using uri module as below.
- name: API check
gather_facts: no
tasks:
- name : "Get the list as JSON"
uri:
url: http://sampleapitest.com/api
user: test
password: test
force_basic_auth: yes
status_code: 200
body_format: json
dest: "/home/peterw/list.json"
But when I am running the Playbook it is showing that the Playbook needs Hosts file. But I have access only to the URL, not to the SSH port 22.
ERROR! the field 'hosts' is required but was not set
I am new to Ansible. Can anyone please help me to fetch the details from the API as JSON file?
Solution 1:[1]
you have lot of ways to resolve your problem
either you have hosts defined, and you want to use an ansible module only on localhost, so you add delegate_to: localhost and run_once: true to signify i just want to play this task only one time.
- hosts: listohhosts
tasks:
- name: what does the task
moduleusing:
param1:
:
delegate_to: localhost
run_once: true
either you add hosts: localhost
Solution 2:[2]
It is possible to write tasks like
- name: Gather stored entitlement from repository service
local_action:
module: uri
url: "https://{{ REPOSITORY_URL }}/api/system/security/certificates"
method: GET
url_username: "{{ ansible_user }}"
url_password: "{{ ansible_password }}"
validate_certs: yes
return_content: yes
status_code: 200
body_format: json
check_mode: false
register: result
- name: Show result
debug:
msg: "{{ result.json }}"
check_mode: false
which in example gather installed certificates from a JFrog Artifactory repository service via REST API call, as well
- name: Gather stored entitlement from repository service
action:
module: uri
...
local_actionSame as action but also impliesdelegate_to: localhost
for Controlling where tasks run: delegation and local actions.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Frenchy |
| Solution 2 | U880D |
