How to run Ansible commands based on versions in single task?

Viewed 20

Can I perform these below in single task? If so, what shall be the approach?

- name: fetch configuration
  command: "oc get disk -n **xyz** -o json"
  when: vars.version == **"2.1"**
  register: oc_result

- name: fetch configuration
  command: "oc get disk -n **abc** -o json"
  when: vars.version == **"3.0"**
  register: oc_result

So, if the version is 2.1, then, the command should be run with xyz namespace, else with abc namespace.
The version will be from another YAML variable, which I will refer using {{ vars.version }}.

1 Answers

You could create a dictionary to match the version to a specific namespace.
And use a default for the cases not in the dictionary of versions.

For example:

- name: fetch configuration
  command: "oc get disk -n {{ _v[vars.version] | default('abc') }} -o json"
  register: oc_result
  vars:
    _v: 
      '2.1': xyz
Related