Home > Mobile >  Ansible failed_when statement
Ansible failed_when statement

Time:08-06

In the following task I want to make ansible not to fail when stderr contains the object has been modified or have a resource type.

- name: List nodes
  delegate_to: localhost
  shell: kubectl get nodes
  run_once: true
  register: output_error
  failed_when: (output_error.stderr_lines | length > 0) and ("'the object has been modified' not in output_error.stderr or 'have a resource type' not in output_error.stderr")

However I am reveiving the following error message:

kubectl get nodes", "delta": "0:00:00.498169", "end": "2022-08-05 11:08:01.386024", "failed_when_result": true, "item": "nodes", "rc": 0, "start": "2022-08-05 11:08:00.887855", "stderr": "error: the server doesn't have a resource type \"nodes\"", "stderr_lines": ["error: the server doesn't have a resource type \"nodes\""], "stdout": "", "stdout_lines": []}

CodePudding user response:

Use a regex which includes both alternatives:

- name: List nodes
  delegate_to: localhost
  shell: kubectl get nodes
  run_once: true
  register: output_error
  failed_when:
    - output_error.stderr_lines | length > 0
    - output_error.stderr is not regex('the object has been modified|have a resource type')

For easier reading and maintenance you can set your positive matches in a list and join them together in an expression.

- name: List nodes
  vars:
    acceptable_err_matches:
      - the object has been modified
      - have a resource type
    match_regex: acceptable_err_matches | map('regex_escape') | join('|')
  delegate_to: localhost
  shell: kubectl get nodes
  run_once: true
  register: output_error
  failed_when:
    - output_error.stderr_lines | length > 0
    - output_error.stderr is not regex(match_regex)
  • Related