Home:ALL Converter>How to restrict scope of set_fact variable in ansible

How to restrict scope of set_fact variable in ansible

Ask Time:2020-06-15T22:33:17         Author:user13750277

Json Formatter

below is my ansible playbook for validation of objects - I am first using validateip role and under that executing login,validation and then logout tasks.

- name: validate  object
  vars:
   mserver: [1.1.1.1,2.2.2.2]
   domain: [3.3.3.3,4.4.4.4]
  tasks:
    - include_role:
        name: validateip
      when: object_type == "ip"
  with_together:
           - "{{ mserver_hostname }}"
           - "{{ domain }}"


- name: Checking Network objects
      uri:
        url: "https://{{item.0}}/web_api/show-objects"
        validate_certs: False
        method: POST
        headers:
          x-chkp-sid: "{{ login.json.sid }}"
        body:
          type: host
          filter: "{{ip}}"
          ip-only: true
        body_format: json
      register: check_host_result
      when: item.0 != ""

    - debug:
        var: check_host_result
    - name: Checking if Network Object exists
      set_fact:
        item_ip_exists: true
        obj_name: "{{ item2['name'] }}"
      loop: "{{ check_host_result.json.objects  }}"
      loop_control:
        loop_var: item2
      when:
        - item2['ipv4-address'] is defined and item2['ipv4-address'] == ip

    - debug:
        msg: "Network Object exists with name [{{obj_name}}]"
      when: item_ip_exists is defined
    - debug:
        msg: " Network Object ({{ip}}) will be created"
      when: item_ip_exists is not defined

I am facing issue for set_fact variable like obj_name and item_ip_exists so when loop runs on first item and if object is present so it set both the variable (obj_name and item_ip_exists ) and print the correct debug messages. but when 2nd item executed and there if object is not present so it is printing the wrong debug message due to the set_fact variables( obj_name and item_ip_exists) which has already the value from the first items execution so how i can restrict the scope of set_fact variables ( obj_name and item_ip_exists ) so when second item execute the variables take the value from there not from previously set_fact values. I am totally stuck here. Please help me. Thanks in advance.

Author:user13750277,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/62390505/how-to-restrict-scope-of-set-fact-variable-in-ansible
yy