You have to both set the X-XSRF-TOKEN and the cookie in the header. Here is a working example:
- name: Request token
ansible.builtin.uri:
url: "{{ nsx_url }}/api/session/create"
method: POST
timeout: 60
validate_certs: no
return_content: no
headers:
Content-Type: application/x-www-form-urlencoded
body: "j_username={{ nsx_user }}&j_password={{ nsx_pass }}"
register: token_request
- name: Set header
set_fact:
header:
Content-Type: application/json
X-XSRF-TOKEN: "{{ token_request.x_xsrf_token }}"
Cookie: "{{ token_request.cookies_string }}"
- name: Get DHCP servers
ansible.builtin.uri:
url: "{{ nsx_url }}/api/v1/dhcp/servers/"
method: GET
timeout: 60
validate_certs: no
return_content: no
headers: "{{ header }}"
register: binding
- debug: var=binding
- name: Delete token
ansible.builtin.uri:
url: "{{ nsx_url }}/api/session/destroy"
method: POST
timeout: 60
validate_certs: no
return_content: no
headers: "{{ header }}"