uri post to avoid duplicate

23 views
Skip to first unread message

Veera

unread,
Aug 17, 2023, 4:18:48 AM8/17/23
to Ansible Project
Hi ,

I have the below uri module to post the details inside the web api

- name: REST POST Example
  uri:
    url: "{{ webapp_url }}/api/orgs"
    method: POST
    return_content: yes
    body: "{ \"name\": \"{{ project_name }}\" }"
    body_format: json
    validate_certs: no
    user: "{{ user }}"
    password: "{{ password }}"
    force_basic_auth: yes

while passing the variables as 
ansible-playbook myplay.yml  -e "project_name=first_project"  
n- number of times it works and overwrites the same first_project name.

Is there an option available to stop overwriting if the same project_name is  available with uri module? 
Or we have to use the GET method  to collect and compare the existing project_name , before writing using POST? or will  a conditional check can help ?


Atul Nasir

unread,
Aug 19, 2023, 1:04:16 PM8/19/23
to Ansible Project
- name: Check if project name exists
  uri:
    url: "{{ webapp_url }}/api/orgs"
    method: GET
    return_content: yes

    validate_certs: no
    user: "{{ user }}"
    password: "{{ password }}"
    force_basic_auth: yes
  register: existing_projects

- name: Check if project name exists in the response
  set_fact:
    project_already_exists: "{{ project_name in existing_projects.json | json_query('*.name') }}"

- name: REST POST Example if project name doesn't exist

  uri:
    url: "{{ webapp_url }}/api/orgs"
    method: POST
    return_content: yes
    body: "{ \"name\": \"{{ project_name }}\" }"
    body_format: json
    validate_certs: no
    user: "{{ user }}"
    password: "{{ password }}"
    force_basic_auth: yes
  when: not project_already_exists

Veera

unread,
Aug 23, 2023, 5:10:41 AM8/23/23
to Ansible Project
Thanks .. I am able to achieve it with the above logic and with "assert"  module for exiting the playbook if failed . 
Reply all
Reply to author
Forward
0 new messages