Ansible conditional lists

ansibleansible-playbook

I'd like to deploy to different directories depending on a flag.

I saw there was --extra-vars which allows passing in a variable,

so let's say, --extra-vars "flag=test" or --extra-vars "flag=prod"

Now I'd like to either use the test_* or prod_* variables, depending on this flag.

  vars:
    test_dirs: ["/dataVolumes/dev/deployments/", "/dataVolumes/qa/deployments/"]

    prod_dirs: ["/dataVolumes/preprod/deployments/", "/dataVolumes/prod/deployments/"]

Let's say there's two steps, delete old files, and copy new files.

Is there a way to do something like the following?

-
  name: delete old files
  file: 
   state:absent 
   path:"{{item}}"
  with_items: "{{ test_dirs if flag == 'test' else prod_dirs }}"

-
  name: copy new files
  copy:
   src: /opt/ansible/
   dest:"{{item}}"
  with_items: "{{ test_dirs if flag == 'test' else prod_dirs }}"

Like, a conditional operator, to choose between two lists to work with?

Best Answer

You could achieve this by adding a include_vars task at the beginning of your play. As variables set by include_vars have a high precedence they should rule out the variables set elsewhere.

So all you need to do is add something like this at the beginning of your play:

- name: Include test vars.
  include_vars:
     file: test.yml
  when: test == True

the value of the variable test would then need to be a boolean.

However as already pointed out using group_vars would likely be a cleaner solution.