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.

    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
  with_items: "{{ test_dirs if flag == 'test' else prod_dirs }}"

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

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

  • 2
    are you running the play on the same hosts? why aren't you using group_vars ? – Jacob Evans Mar 2 '17 at 19:53
  • yeah, dev/qa/prod are all on the same host, so though it's useful to know about group_vars, after reading the docs on that page, I'm still unsure how to specify which group to use, based on a condition. I suppose I could define the same hosts in different groups though. Hmm. That might be it. Will check – djb Mar 6 '17 at 8:35
  • Yes. You can add the same host to multiple host groups. – Henrik Pingel Mar 6 '17 at 13:05

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.
     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.

  • Thanks I agree, after looking at the two options, group_vars seems cleaner. I got it working in the end, thanks. with_items worked for processing the list, in all of my tasks – djb Mar 6 '17 at 9:27
  • @djb It would make this question more useful for the long term if you wrote an answer including brief sample code for the two different ways to solve this problem using include_vars and group_vars. The answers and comments assume knowledge not held. Or maybe Henrik's answer could be modified to show how it would work using group_vars. – Xalorous Nov 30 '17 at 14:49
  • Well here's a link to the docs: docs.ansible.com/ansible/latest/… – djb Nov 30 '17 at 15:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.