Help w a Conditional Block with an "import playbook" Syntax

Hello. I need some help with a conditional block execution. It has to import a playbook only if a certain condition is met. So far, I can either:

  • import the other playbook without the condition,
  • or debug the variable condition only (meaning the "import playbook} isnt run).

My guess is this is because of my inexperience with the “block” syntax.

Here is the logic:

"Go to ServiceNow ticketing system, check every 15 seconds if there is a new Change Request open with the word “GoldenGate” in the short description. If there is, immediately debug the Change Request VAR and import a different playbook “itsm_ogg_add_deployment.yml”

Here is the playbook that has the condition in the debug, but not the import 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: This task runs only if a new GoldenGate Change Request 'new_ogg_cr_custom_out' is defined and not empty
        ansible.builtin.debug:
          msg: "new_ogg_cr_custom_out has content: {{ new_ogg_cr_custom_out }}"
        when: new_ogg_cr_custom_out | default('') | length > 0

      - import_playbook: itsm_ogg_add_deployment.yml 
        when: new_ogg_cr_custom_out | default('') | length > 0

Here is an example of a successful run if I comment out the “import 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: This task runs only if a new GoldenGate Change Request 'new_ogg_cr_custom_out' is defined and not empty
        ansible.builtin.debug:
          msg: "new_ogg_cr_custom_out has content: {{ new_ogg_cr_custom_out }}"
        when: new_ogg_cr_custom_out | default('') | length > 0

#      - import_playbook: itsm_ogg_add_deployment.yml 
#        when: new_ogg_cr_custom_out | default('') | length > 0

Output:

[ansible_admin@lnx000 ansible]$ ansible-playbook ./playbooks/itsm_ogg_get_cr_info_003.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 [This task runs only if a new GoldenGate Change Request 'new_ogg_cr_custom_out' is defined and not empty] *******************************************************************************************************************************************************
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}'

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

[ansible_admin@lnx000 ansible]$ 

Please help. My guess is I need to place the block in the right places with just one condition underneath.
Thanks.

If I’m interpreting the error correctly, its complaining that you have two tasks that both have the same when condition, and so that should be a block. It should look something like this

      - name: Tasks to run on new GoldenGate Change Request
        when: new_ogg_cr_custom_out | default('') | length > 0
        block:
          - name: Debug ogg_cr_custom_out
            ansible.builtin.debug:
            msg: "new_ogg_cr_custom_out has content: {{ new_ogg_cr_custom_out }}"
        
          - import_playbook: itsm_ogg_add_deployment.yml 

the block documentation should have more examples.

1 Like

import_playbook is only valid at the top level of the playbook, it is not a task that can be used inside a play. It imports the plays from the target playbook into the current one.

You might instead want to put the tasks from that playbook in a task file (either free-standing or as a role) and then import that in both playbooks.

Also, imports cannot be made conditional, only includes can, and no, there is no include_playbook.

Good catches @flowerysong & @bcoca, I was focused on the block syntax and wasn’t paying attention to the import_playbook part

1 Like

Yes, it told me that, exactly. The import is only allowed at the top and cannot just replace tasks.
Thank you. Re-writing.

Conditional playbook imports are very much possible with ansible. But cannot be put inside block (documentation clearly says that import_playbook cannot be used inside action or play only at the top level)

Here is an example:

bash-5.2$ cat conditional_import.yml 
- import_playbook: "{{ playbook_name }}.yml"
bash-5.2$ cat one.yml 
---
- name: One
  gather_facts: false
  hosts: localhost
  tasks:
    - ansible.builtin.debug:
        msg: "playbook one"
bash-5.2$ cat two.yml 
---
- name: Two
  gather_facts: false
  hosts: localhost
  tasks:
    - ansible.builtin.debug:
        msg: "playbook two"

Execute them like this:

bash-5.2$ ansible-playbook conditional_import.yml --extra-vars "playbook_name=one"
[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'

PLAY [One] **********************************************************************************************************************************************************

TASK [ansible.builtin.debug] ****************************************************************************************************************************************
ok: [localhost] => {
    "msg": "playbook one"
}

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


bash-5.2$ ansible-playbook conditional_import.yml --extra-vars "playbook_name=two"
[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'

PLAY [Two] **********************************************************************************************************************************************************

TASK [ansible.builtin.debug] ****************************************************************************************************************************************
ok: [localhost] => {
    "msg": "playbook two"
}

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

There are of course limitations what variables can be used in such conditions. This is an exercise for curious reader. That would be nice if someone checked that - I do not know the answer to that question.

Hint: with ansible.builtin.ternary filter one can make it actual logical condition.

- import_playbook: "{{ playbook_name }}.yml"
  vars:
    playbook_name: "{{ (param | int > 1) | ternary('two','one') }}"

bash-5.2$ ansible-playbook conditional_import.yml --extra-vars "param=3"
[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'

PLAY [Two] **********************************************************************************************************************************************************

TASK [ansible.builtin.debug] ****************************************************************************************************************************************
ok: [localhost] => {
    "msg": "playbook two"
}

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


2 Likes