How yo print API request and response with Ansible uri module? - ansible

I tried to find a way to print both an API request and response to a log file. But Ansible URI module does not provide the request data.
Does anyone know any mechanism to print the request and response to file in Ansible?
example:
name: update cms
uri:
url: '{{ cms_api.msg }}'
method: POST
body_format: json
body:
api_password: "{{ api_password }}"
name: "{{ item.Name }}"
ip_address: "{{ item.IPAddress }}"
subnet_mask: "{{ item.SubnetMask }}"
router: "{{ item.Router }}"
ip_range: "{{ item.IPAddresses }}"
options: "{{ item.Options }}"
pool_name: "{{ item.PoolName}}"
validate_certs: no
return_content: yes
register: dhcp_subnet_response
loop: "{{ ip_addrs_1.list }}"
delegate_to: localhost
I need to print above request and response both to a file. Since this api calling as a loop, I need to print request|response both for each request.

Since your post contains several different questions you may have a look into the general documentation first
Registering Variables
Return Values - Common
uri module – Interacts with webservices - Return Values and their Examples
After reading and regarding
But Ansible URI module not providing request data.
you may then have a look into the following example playbook
---
- hosts: localhost
become: false
gather_facts: false
tasks:
- name: Get response with 'uri' module
uri:
url: "https://example.com"
method: GET
body_format: raw # default
return_content: true # default 'false'
status_code: 200
register: result
- name: Show result
debug:
var: result
resulting into the content of https://example.com, an IANA-managed Reserved Domain.
Does anyone know any mechanism to print ...
The page content itself is accessible via
- name: Show content
debug:
msg: "{{ result.content }}"
print ... to file in Ansible?
and you can Write variable to a file in Ansible or Ansible - Save registered variable to file.

Related

Iterating through Ansible Tower APIs with multiple pages

I need to take all related jobs for a job template. API can only return up to 200 results per page.
Has anyone handled API pagination with the URI module?
How can I simply iterate over the number of pages with a variable named page_number?
below my code:
- name: List related jobs for job template
uri:
url: http://localhost{{ api_for_job_template.json.related.jobs }}?page_size=200&page={{ page_number }}
force_basic_auth: yes
user: "{{ user }}"
password: "{{ password }}"
body_format: json
register: jobs_info
Ok, I found a way how to get all pages.
In one task I'm taking count of jobs from API and dividing it by number of records returned per page. Next in uri iterate page by page with "with_sequence". Just needed to round up it and convert to int.
- name: List related jobs for job template
uri:
url: http://localhost{{ api_for_job_template.json.related.jobs }}?page_size={{ page_size }}&page={{ item }}
force_basic_auth: yes
user: "{{ user }}"
password: "{{ password }}"
body_format: json
register: jobs_info
with_sequence: start=1 end="{{ end_at }}"
vars:
- end_at: "{{ ((jobs_count.json.count / 20) | round(0,'ceil')) | int }}"

ansible is trowing a Syntax Error while loading YAML. did not find expected key

my yml looks like:
---
# YAML documents begin with the document separator ---
# The minus in YAML this indicates a list item. The playbook contains a list
# of plays, with each play being a dictionary
-
# Hosts: where our play will run and options it will run with
hosts: localhost
gather_facts: false
# Vars: variables that will apply to the play, on all target systems
vars:
DDVE_public_IP : 34.107.103.175
destination_port: 3009
Instance_id : 8529834022607504819
S3_bucket_name : bucket_for_ddve_6
# Tasks: the list of tasks that will be executed within the playbook
tasks:
- name: login access token
uri:
url: https://{{ DDVE_public_IP }}:{{ destination_port }}/{{ resource_path }}
method: POST
headers:
Content-Type: application/json
body_format: json
body:
username: sysadmin
password: {{ Instance_id }}
return_content: yes
ignore_errors: yes
register: rest_post
vars:
resource_path: rest/v1.0/auth
- name: DEBUG / GOT INFO
debug:
msg: "{{ rest_post.json }}"
when: rest_post.status == 201
# Handlers: the list of handlers that are executed as a notify key from a task
# Roles: list of roles to be imported into the play
# Three dots indicate the end of a YAML document
...
ansible-playbook ddve6-post-deploy-object-store.yml
[WARNING]: No inventory was parsed, only implicit localhost is available.
[WARNING]: provided hosts list is empty, only localhost is available. Note that
the implicit localhost does not match 'all'.
ERROR! We were unable to read either as JSON nor YAML, these are the errors we got from each:
JSON: Expecting value: line 1 column 1 (char 0)
Syntax Error while loading YAML.
did not find expected key
The error appears to be in '/Users/juergen/Documents/DPSCodeAcademy/Ansible/#dev/ddve/ddve6-post-deploy-object-store.yml': line 30, column 9, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
password: {{ Instance_id }}
return_content: yes
^ here
I have no idea where that error is coming as I can't find the responding problem here.
You just have some indentation errors in that YAML document. Pick an indentation level (e.g., 2 spaces for every level) and stick with it consistently. Many editors have plugins that will syntax check your YAML documents while you write them.
The following validates correctly:
---
- hosts: localhost
gather_facts: false
vars:
DDVE_public_IP: 34.107.103.175
destination_port: 3009
Instance_id: 8529834022607504819
S3_bucket_name: bucket_for_ddve_6
tasks:
- name: login access token
uri:
url: https://{{ DDVE_public_IP }}:{{ destination_port }}/{{ resource_path }}
method: POST
headers:
Content-Type: application/json
body_format: json
body:
username: sysadmin
password: "{{ Instance_id }}"
return_content: true
ignore_errors: true
register: rest_post
vars:
resource_path: rest/v1.0/auth
- name: DEBUG / GOT INFO
debug:
msg: "{{ rest_post.json }}"
when: rest_post.status == 201
Note that it is highly uncommon to terminate your YAML documents with the ... marker.

Ansible: How to loop set_fact varaibles

i have a ansible-playbook that generates all elements output from remote server, and being saved into variables using set_fact.
i want to try and write each output into separate files using copy module with loop.
set_fact works to store the content but i am struggling to get them specified under copy module using loop.
- name: Playbook to get element details from server
uri:
url: https://10.10.10.19/rest/v1.1/nucli?SetType={{ item }}
body_format: raw
method: GET
headers:
Content-Type: application/xml
Accept: application/xml
Authorization: Bearer password
return_content: yes
register: fileout
with_items:
- My_var1
- My_var2
- My_var3
- My_var4
- set_fact:
My_var1: "{{ fileout.results[0].content }}"
My_var2: "{{ fileout.results[1].content }}"
My_var3: "{{ fileout.results[2].content }}"
My_var4: "{{ fileout.results[3].content }}"
- copy:
content: {{ item }}
dest: "/users/ansible/vars/{{ item }}.txt"
delegate_to: localhost
loop:
- My_var1
- My_var2
- My_var3
- My_var4
Playbook execution:
all steps executed successfully. but in copy module content: {{ item }} is not using set_fact variables, instead they are just copying string My_var1... etc.
Could anyone help me how to use loop for set_fact variable names? So that i can store the content that i have saved from set_fact (example - My_var1: "{{ fileout.results[0].content }}" )
Thanks in advance.

Ansible how to select a nested list in a attribut of list

Hi I would like to known how I can select a list nested in an attibut of a list. I've done a research on my F5 BIG IP and it give me a list of the attibutes of the virtuals servers like that:
"/Common/vs_portailopal_wi_https_virtual_server": {
"last_hop_pool": "",
"name": "vs_portailopal_wi_https_virtual_server",
"nat64_state": "STATE_DISABLED",
"object_status": {
"availability_status": "AVAILABILITY_STATUS_RED",
"enabled_status": "ENABLED_STATUS_DISABLED",
"status_description": "The children pool member(s) are down"
},
"profile": [
{
"profile_context": "PROFILE_CONTEXT_TYPE_CLIENT",
"profile_name": "/Common/vs_portailopal_wi_clientssl_profile",
"profile_type": "PROFILE_TYPE_CLIENT_SSL"
},
{
"profile_context": "PROFILE_CONTEXT_TYPE_ALL",
"profile_name": "/Common/vs_portailopal_wi_http_profile",
"profile_type": "PROFILE_TYPE_HTTP"
},
{
"profile_context": "PROFILE_CONTEXT_TYPE_ALL",
"profile_name": "/Common/vs_portailopal_wi_http_profile-cache",
"profile_type": "PROFILE_TYPE_WEBACCELERATION"
},]
},
},
So I would like to compare the name of the virtual serveur and the name of each profile. I can select the name of the vitual server but I can't enter in the list of profile to select the name because it's a nested list in an attribute
This is I doing:
---
- name: Search
hosts: F5
gather_facts: no
connection: local
vars:
username: '{{ cpt_username }}'
password: '{{ cpt_password }}'
tasks:
- name: Get virtual-servers
bigip_facts:
include:
- virtual_server
server: '{{ inventory_hostname }}'
user: '{{ username }}'
password: '{{ password }}'
validate_certs: no
- name: filter on VIP_nommage when VIP_partition is OK
lineinfile:
line:
- "{{ inventory_hostname }} Virtual Server : {{ item.key }} => POOL: {{ item.value.profile.name }}"
dest: "xxxxx/file.csv"
state: present
with_dict: "{{ virtual_server }}"
I want to store in file all profiles name per virtual serveur and in other task filter on their names.
I am not familiar with the bigip Ansible modules, and I definitely don't have any F5 kit to test against :) Before saying anything else, a big note is that the docs say that 'bigip_facts' is now deprecated, and you should be using 'bigip_device_facts'. But if you want to use this module, can you do a couple of things:
1) Edit your original question to add the detail you posted in your reply. It is better to keep editing your original question with additional information, rather than add answers, as it makes it easier to understand your entire situation.
2) Create a new playbook that contains:
---
- hosts: F5
gather_facts: no
connection: local
vars:
username: '{{ cpt_username }}'
password: '{{ cpt_password }}'
tasks:
- name: Get virtual-servers
bigip_facts:
include:
- virtual_server
server: '{{ inventory_hostname }}'
user: '{{ username }}'
password: '{{ password }}'
validate_certs: no
register: bigip_facts_data
- name: Display collected data
debug:
var: bigip_facts_data
This will show us the data that Ansible is actually working with. Paste the output into your original reply, in place the of the JSON that you originally pasted. It may look like this:
"/Common/vs_portailopal_wi_https_virtual_server":
last_hop_pool: ''
name: vs_portailopal_wi_https_virtual_server
nat64_state: STATE_DISABLED
object_status:
availability_status: AVAILABILITY_STATUS_RED
enabled_status: ENABLED_STATUS_DISABLED
status_description: The children pool member(s) are down
profile:
- profile_context: PROFILE_CONTEXT_TYPE_CLIENT
profile_name: "/Common/vs_portailopal_wi_clientssl_profile"
profile_type: PROFILE_TYPE_CLIENT_SSL
- profile_context: PROFILE_CONTEXT_TYPE_ALL
profile_name: "/Common/vs_portailopal_wi_http_profile"
profile_type: PROFILE_TYPE_HTTP
- profile_context: PROFILE_CONTEXT_TYPE_ALL
profile_name: "/Common/vs_portailopal_wi_http_profile-cache"
profile_type: PROFILE_TYPE_WEBACCELERATION
If it does, then this may produce the output you need (tho I am still not clear I fully understand what you require - hopefully we are closer):
- name: filter on VIP_nommage when VIP_partition is OK
lineinfile:
line:
- "{{ inventory_hostname }} Virtual Server : {{ item.0.name }} => POOL: {{ item.1.profile_name }}"
dest: "xxxxx/file.csv"
state: present
with_subelements:
- "{{ bigip_fact_data }}"
- profile
Really, 'with_subelements' is deprecated now along with the other 'with_' constructs, but if you are using 'bigip_facts' I guess you are using an older version of Ansible.

Ansible: is it possible to Jinja2 filter the content picked up by lookup()?

I'm sending a REST API query using Ansible uri module. The body content is picked up from a file:
body: "{{ lookup('file',mp_config_path + item.file) }}"
There are some variables in my file - is it possible to tell ansible to run Jinja2 filters on it before sending it to the uri module?
And how about using template lookup?
body: "{{ lookup('template',mp_config_path + item.file) }}"
or:
- uri:
body: "{{ item }}"
# other parameters
with_template: "{{ mp_config_path + item.file }}"

Resources