A Block Conditional is Ignored, Ansible Keeps Rolling Regardless!

Hi. Ansible ignores a condition in my block. Here is its logic:

“Go to the ServiceNow ticketing system. Check if there is a new Change Request with the word “GoldenGate” in the short description. If it does exist, export it out for the log to preserve, and create a /tmp/foo.conf from a template file”.

Here is the Playbook:

---
    - name: r-able.com Oracle GoldenGate add deployment process ID 2772.86
      hosts: localhost
      gather_facts: true
      vars_files:
        - vars/main.yml

      tasks:

        - name: Retrieve Change Requests that contain GoldenGate in its short description by using field query
          servicenow.itsm.change_request_info:
            instance:
              host: "{{ sn_instance}}"
              username: "{{ sn_username }}"
              password:  "{{ sn_password }}"
            query:
              - short_description: LIKE GoldenGate
#              - short_description: LIKE SAP
          register: new_ogg_cr_custom_out

        - name: Debug the Change Request data and create the config file in tmp if the condition is met
          when: new_ogg_cr_custom_out | default('') | length > 0
          block:

            - name: Debug the GoldenGate Change Request data ogg_cr_custom_out
              ansible.builtin.debug:
                msg: "new_ogg_cr_custom_out has content: {{ new_ogg_cr_custom_out }}"           

            - name: Apply the template to tmp only if the Change request exists
              ansible.builtin.template:
                src: templates/config.j2
                dest: /tmp/foo.conf

The playbook runs without errors. However, it creates the /tmp/foo.conf whether I use the existing condition , meaning there is an actual GoldenGate Change Request opened, or not:

             - short_description: LIKE GoldenGate
#             - short_description: LIKE SAP

or I use a non-existent SAP query:

#             - short_description: LIKE GoldenGate
              - short_description: LIKE SAP

I expect the playbook to detect that the SAP Change Request isnt there and not to create the /tmp/foo.conf. But the file is created regardless. But it does debug the “GoldenGate” Change Request data from ServiceNow just fine, it gets the CR # and everything. On the “SAP” query it doesnt output any Change Request data which is correct, but still creates the /tmp/ file:

[root@lnx000 tmp]# ls -ltr foo.conf
-rw-rw-r--. 1 ansible_admin ansible_admin 140 Jan 14 14:57 foo.conf

Here is the output on the “GoldenGate” Change Request commented out, and the “SAP” query specified , which doesnt exist:

[ansible_admin@lnx000 ansible]$ ansible-playbook ./playbooks/itsm_ogg_get_cr_info_004.yml  -kK 
[WARNING]: Ansible is being run in a world writable directory (/etc/ansible), ignoring it as an ansible.cfg source. For more information see https://docs.ansible.com/ansible/devel/reference_appendices/config.html#cfg-in-world-writable-dir
SSH password: 
BECOME password[defaults to SSH password]: 
/usr/lib/python3.6/site-packages/requests/__init__.py:91: RequestsDependencyWarning: urllib3 (1.26.20) or chardet (3.0.4) doesn't match a supported version!
  RequestsDependencyWarning)

PLAY [r-able.com Oracle GoldenGate add deployment process ID 2772.86] ************************************************************************************************************************************************************************************************

TASK [Gathering Facts] ***********************************************************************************************************************************************************************************************************************************************
ok: [localhost]

TASK [Retrieve Change Requests that contain GoldenGate in its short description by using field query] ****************************************************************************************************************************************************************
ok: [localhost]

TASK [Debug the GoldenGate Change Request data ogg_cr_custom_out] ****************************************************************************************************************************************************************************************************
ok: [localhost] => 
  msg: 'new_ogg_cr_custom_out has content: {''changed'': False, ''records'': [], ''failed'': False}'

TASK [Apply the template to tmp only if the Change request exists] ***************************************************************************************************************************************************************************************************
changed: [localhost]

PLAY RECAP ***********************************************************************************************************************************************************************************************************************************************************
localhost                  : ok=4    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

[ansible_admin@lnx000 ansible]$ 

Here is the output on the “GoldenGate” query for the existing Change Request (the “SAP” query is commented out). Note the debug correctly outputs the GoldenGate existing CR data:

[ansible_admin@lnx000 ansible]$ ansible-playbook ./playbooks/itsm_ogg_get_cr_info_004.yml  -kK 
[WARNING]: Ansible is being run in a world writable directory (/etc/ansible), ignoring it as an ansible.cfg source. For more information see https://docs.ansible.com/ansible/devel/reference_appendices/config.html#cfg-in-world-writable-dir
SSH password: 
BECOME password[defaults to SSH password]: 
/usr/lib/python3.6/site-packages/requests/__init__.py:91: RequestsDependencyWarning: urllib3 (1.26.20) or chardet (3.0.4) doesn't match a supported version!
  RequestsDependencyWarning)

PLAY [r-able.com Oracle GoldenGate add deployment process ID 2772.86] ************************************************************************************************************************************************************************************************

TASK [Gathering Facts] ***********************************************************************************************************************************************************************************************************************************************
ok: [localhost]

TASK [Retrieve Change Requests that contain GoldenGate in its short description by using field query] ****************************************************************************************************************************************************************
[WARNING]: Encountered unknown value Other while mapping field category.
[WARNING]: Encountered unknown value  while mapping field risk.
[WARNING]: Encountered unknown value Software while mapping field category.
ok: [localhost]

TASK [Debug the GoldenGate Change Request data ogg_cr_custom_out] ****************************************************************************************************************************************************************************************************
ok: [localhost] => 
  msg: 'new_ogg_cr_custom_out has content: {''changed'': False, ''records'': [{''parent'': '''', ''reason'': '''', ''watch_list'': '''', ''upon_reject'': ''cancel'', ''sys_updated_on'': ''2026-01-13 14:56:04'', ''type'': ''standard'', ''approval_history'': '''', ''number'': ''CHG0030866'', ''test_plan'': '''', ''cab_delegate'': '''', ''requested_by_date'': '''', ''state'': ''closed'', ''sys_created_by'': ''admin'', ''knowledge'': ''false'', ''order'': '''', ''phase'': ''requested'', ''cmdb_ci'': '''', ''delivery_plan'': '''', ''contract'': '''', ''impact'': ''low'', ''active'': ''false'', ''work_notes_list'': '''', ''priority'': ''moderate'', ''sys_domain_path'': ''/'', ''cab_recommendation'': '''', ''production_system'': ''false'', ''review_date'': '''', ''business_duration'': '''', ''group_list'': '''', ''requested_by'': ''6816f79cc0a8016401c5a33be04be441'', ''change_plan'': '''', ''approval_set'': ''2026-01-13 14:53:44'', ''copied_from'': '''', ''implementation_plan'': '''', ''universal_request'':
    '''', ''end_date'': '''', ''short_description'': ''Oracle GoldenGate replicat replicat RSRCUI1 down, out of sync - CR triggered by incident INC0010595'', ''correlation_display'': '''', ''delivery_task'': '''', ''work_start'': ''2026-01-13 14:53:52'', ''additional_assignee_list'': '''', ''outside_maintenance_schedule'': ''false'', ''std_change_producer_version'': '''', ''service_offering'': '''', ''sys_class_name'': ''change_request'', ''closed_by'': ''6816f79cc0a8016401c5a33be04be441'', ''follow_up'': '''', ''reassignment_count'': ''0'', ''review_status'': '''', ''assigned_to'': ''3c589a008334f210f28198c6feaad375'', ''start_date'': '''', ''sla_due'': '''', ''comments_and_work_notes'': '''', ''escalation'': ''0'', ''upon_approval'': ''proceed'', ''correlation_id'': '''', ''made_sla'': ''true'', ''backout_plan'': '''', ''conflict_status'': ''Not Run'', ''task_effective_number'': ''CHG0030866'', ''sys_updated_by'': ''admin'', ''opened_by'': ''6816f79cc0a8016401c5a33be04be441'', ''user_input'':
    '''', ''sys_created_on'': ''2026-01-13 14:53:44'', ''on_hold_task'': '''', ''sys_domain'': ''global'', ''route_reason'': '''', ''closed_at'': ''2026-01-13 14:55:57'', ''review_comments'': '''', ''business_service'': '''', ''time_worked'': '''', ''chg_model'': ''e55d0bfec343101035ae3f52c1d3ae49'', ''expected_start'': '''', ''opened_at'': ''2026-01-13 14:53:44'', ''work_end'': ''2026-01-13 14:53:53'', ''phase_state'': ''open'', ''work_notes'': '''', ''close_code'': ''successful'', ''assignment_group'': ''db53580b0a0a0a6501aa37c294a2ba6b'', ''description'': ''Refreshing the target Oracle instance from source INC0010595 on 2026-01-13T14:53:32Z for replicat RSRCUI1'', ''on_hold_reason'': '''', ''calendar_duration'': '''', ''close_notes'': ''Hyperautomation has successfully closed CR at "2026-01-13T14:53:32Z"'', ''sys_id'': ''fc6efca783563210f28198c6feaad306'', ''contact_type'': '''', ''cab_required'': ''false'', ''urgency'': ''low'', ''scope'': ''3'', ''company'': '''', ''justification'': '''',
    ''activity_due'': '''', ''comments'': '''', ''approval'': ''approved'', ''due_date'': '''', ''sys_mod_count'': ''8'', ''on_hold'': False, ''sys_tags'': '''', ''cab_date_time'': '''', ''conflict_last_run'': '''', ''unauthorized'': ''false'', ''location'': '''', ''risk'': ''low'', ''category'': ''Other'', ''risk_impact_analysis'': '''', ''attachments'': [{''size_bytes'': ''5750256'', ''file_name'': ''ansible.log'', ''sys_mod_count'': ''1'', ''average_image_color'': '''', ''image_width'': '''', ''sys_updated_on'': ''2026-01-13 14:56:06'', ''sys_tags'': '''', ''table_name'': ''change_request'', ''sys_id'': ''0beef8e783563210f28198c6feaad3de'', ''image_height'': '''', ''sys_updated_by'': ''system'', ''download_link'': ''https://dev276659.service-now.com/api/now/attachment/0beef8e783563210f28198c6feaad3de/file'', ''content_type'': ''text/x-log'', ''sys_created_on'': ''2026-01-13 14:56:04'', ''size_compressed'': ''502837'', ''compressed'': ''true'', ''state'': ''available'', ''table_sys_id'':
    ''fc6efca783563210f28198c6feaad306'', ''chunk_size_bytes'': ''700000'', ''hash'': ''af4b778148f3bad79c09b39b3911cf47214999e69be15f46e95b99414e0e5f61'', ''sys_created_by'': ''admin''}]}, {''parent'': '''', ''reason'': '''', ''watch_list'': '''', ''upon_reject'': ''cancel'', ''sys_updated_on'': ''2026-01-14 11:28:00'', ''type'': ''normal'', ''approval_history'': '''', ''number'': ''CHG0030884'', ''test_plan'': '''', ''cab_delegate'': '''', ''requested_by_date'': '''', ''state'': ''new'', ''sys_created_by'': ''admin'', ''knowledge'': ''false'', ''order'': '''', ''phase'': ''requested'', ''cmdb_ci'': ''0c43d5e2c61122750182c132a8b9e2d9'', ''delivery_plan'': '''', ''contract'': '''', ''impact'': ''low'', ''active'': ''true'', ''work_notes_list'': '''', ''priority'': ''low'', ''sys_domain_path'': ''/'', ''cab_recommendation'': '''', ''production_system'': ''false'', ''review_date'': '''', ''business_duration'': '''', ''group_list'': '''', ''requested_by'': ''6816f79cc0a8016401c5a33be04be441'',
    ''change_plan'': '''', ''approval_set'': '''', ''copied_from'': '''', ''implementation_plan'': '''', ''universal_request'': '''', ''end_date'': '''', ''short_description'': ''Add an Oracle GoldenGate Deployment'', ''correlation_display'': '''', ''delivery_task'': '''', ''work_start'': '''', ''additional_assignee_list'': '''', ''outside_maintenance_schedule'': ''false'', ''std_change_producer_version'': '''', ''service_offering'': ''04b89573835e7210f28198c6feaad3f0'', ''sys_class_name'': ''change_request'', ''closed_by'': '''', ''follow_up'': '''', ''reassignment_count'': ''1'', ''review_status'': '''', ''assigned_to'': ''3c589a008334f210f28198c6feaad375'', ''start_date'': '''', ''sla_due'': '''', ''comments_and_work_notes'': '''', ''escalation'': ''0'', ''upon_approval'': ''proceed'', ''correlation_id'': '''', ''made_sla'': ''true'', ''backout_plan'': '''', ''conflict_status'': ''Not Run'', ''task_effective_number'': ''CHG0030884'', ''sys_updated_by'': ''admin'', ''opened_by'': ''6816f79cc0a8016401c5a33be04be441'',
    ''user_input'': '''', ''sys_created_on'': ''2026-01-14 10:28:21'', ''on_hold_task'': '''', ''sys_domain'': ''global'', ''route_reason'': '''', ''closed_at'': '''', ''review_comments'': '''', ''business_service'': ''281a4d5fc0a8000b00e4ba489a83eedc'', ''time_worked'': '''', ''chg_model'': ''007c4001c343101035ae3f52c1d3aeb2'', ''expected_start'': '''', ''opened_at'': ''2026-01-14 10:23:49'', ''work_end'': '''', ''phase_state'': ''open'', ''work_notes'': '''', ''close_code'': '''', ''assignment_group'': ''db53580b0a0a0a6501aa37c294a2ba6b'', ''description'': ''Asset ID:\r\nClient: \r\nApplication:\r\nEnvironment:\r\nBusiness Unit:\r\nApproval:\r\nBilling:'', ''on_hold_reason'': '''', ''calendar_duration'': '''', ''close_notes'': '''', ''sys_id'': ''b03a4d7f83da7210f28198c6feaad3a4'', ''contact_type'': '''', ''cab_required'': ''false'', ''urgency'': ''low'', ''scope'': ''3'', ''company'': '''', ''justification'': '''', ''activity_due'': '''', ''comments'': '''', ''approval'': ''not requested'',
    ''due_date'': '''', ''sys_mod_count'': ''2'', ''on_hold'': False, ''sys_tags'': '''', ''cab_date_time'': '''', ''conflict_last_run'': '''', ''unauthorized'': ''false'', ''location'': '''', ''risk'': '''', ''category'': ''Software'', ''risk_impact_analysis'': '''', ''attachments'': []}], ''warnings'': [''Encountered unknown value Other while mapping field category.'', ''Encountered unknown value  while mapping field risk.'', ''Encountered unknown value Software while mapping field category.''], ''failed'': False}'

TASK [Apply the template to tmp only if the Change request exists] ***************************************************************************************************************************************************************************************************
changed: [localhost]

PLAY RECAP ***********************************************************************************************************************************************************************************************************************************************************
localhost                  : ok=4    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

[root@lnx000 tmp]# ls -ltr foo.conf
-rw-rw-r--. 1 ansible_admin ansible_admin 140 Jan 14 15:11 foo.conf
[root@lnx000 tmp]#

Please help. This has something to do with the conditional in the block. Thanks in advance. Nestor.

And what does this block print to the output for first and second case?

- name: Debug the GoldenGate Change Request data ogg_cr_custom_out
  ansible.builtin.debug:
    msg: "new_ogg_cr_custom_out has content: {{ new_ogg_cr_custom_out }}"           

I updated the description for both “GoldenGate” and “SAP” runs. Thank you for the question.

As you can see from the output, new_ogg_cr_custom_out is not a list but a dict with the following content:

new_ogg_cr_custom_out:
  changed: false
  records: [<some records>]
  failed: false

So when you are testing the length of this variable with | length > 0 it always returns value greater than 0. Also, length test is applicable only to lists, it’s not applicable to dicts.

The value you want to test is new_ogg_cr_custom_out['records'] so the code looks like this:

when: new_ogg_cr_custom_out['records'] | default([]) | length > 0
1 Like

I cannot thank you enough, sir. It works on both entries! Creates the template on GoldenGate Change Request and nothing else

Just use debug module often and analyze the format of the variable. Solves 90% of problems in Ansible :laughing:. Cheers.

1 Like