Functionality - Decisions

Summary

You can make decisions mid-task based on the values of static & dynamic variables.

The when keyword controls when a step or action is triggered.

Its value should be a Jinja2 or Python expression returning True or False.

Conditional Actions

Use when in one or more actions when making a decision inside a step.

This example asks the Task Operator to choose a number, & saves it as exit_code.

The value of exit_code is used to make decisions in the subsequent actions.

Conditional Actions
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
actions:
  - ppa.ui.input_choice:
      text: Choose an exit code
      options:
        - 0
        - 1
        - 2
    store: exit_code

  - exit:
    when: 'exit_code == 0'
      exit_code: 0

  - ppa.ui.output_error:
    when: 'exit_code != 0'
      text: Task failed

  - exit:
    when: 'exit_code != 0'
    load:
      exit_code: exit_code

Conditional Steps

Use when in a step to trigger all the contained actions from the same condition.

This example uses exit_code to make the same decisions as conditional actions.

To avoid repeating the second condition, the actions are grouped into conditional steps.

Conditional Steps
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
- name: Choose Exit Code
  actions:
    - ppa.ui.input_choice:
        text: Choose an exit code
        options:
          - 0
          - 1
          - 2
      store: exit_code

- name: Succeed
  when: 'exit_code == 0'
  actions:
    - task.exit:
        exit_code: 0

- name: Fail
  when: 'exit_code != 0'
  actions:
    - ppa.ui.output_error:
        text: Task failed
    - task.exit:
      load:
        exit_code: exit_code