Search code examples
ansibleansible-2.xjmespath

How to check if task output list contains a string using filter or JMESPath?


I am writing a simple Ansible playbook (Ansible version - 2.9) to start a service and then want to extract certain fields – "changed" and "failed" – from the output for debugging purpose

These are my tasks:

- name: Start service if stopped
  command: systemctl start confluent-*
  register: confluent_start_status
  ignore_errors: true

- debug:
    var: "{{ confluent_start_status.cmd| json_query([?contains(@,'start') == 'true']) }}"

And this is the output of the start task.

{
    "confluent_start_status": {
        "changed": true,
        "cmd": [
            "systemctl",
            "start",
            "confluent-*"
        ],
        "delta": "0:00:01.425703",
        "end": "2023-01-31 14:14:22.567335",
        "failed": false,
        "rc": 0,
        "start": "2023-01-31 14:14:21.141632",
        "stderr": "",
        "stderr_lines": [],
        "stdout": "",
        "stdout_lines": []
    }
}

How can I check that the cmd list contains the string start and assign true to a variable if it does?
Basically I want to create a variable using set_fact, when changed is true, failed is false and cmd contains start, to use it in the next task.


Solution

  • How can I check that the cmd list contains the string start and assign true to a variable if it does?

    With JMESPath:

    - set_fact:
        is_start: >-
          {{ 
            confluent_start_status 
              | json_query('contains(cmd, `start`)') 
          }}
    

    With plain Jinja:

    - set_fact:
        is_start: "{{ 'start' in confluent_start_status.cmd }}"
    

    As for your requirements to combine the facts that the task should raise a changed state, should not have failed and that the cmd should contain start, there are also tests for tasks results that makes is more human readable:

    - set_fact:
        confluence_task_status: >-
          {{
            'start' in confluent_start_status.cmd
            and confluent_start_status is changed
            and confluent_start_status is not failed
          }}