Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible conditional module arguments

Is it possible to only include module argument when a certain condition is valid, without duplicating the play?

Example:

I have a play that looks like the following:

  - name: Start Container
    docker:
      name: "{{containerName}}"
      state: reloaded
      command: "java -jar {{containerImage}}-{{containerJarVersion}}.jar"

I want to change the value of the command argument depending on if a condition is true of false? Currently, I have to duplicate the whole play and wrap it in a condition, which is horrible as only one argument is different.

Current solution:

  - name: Start Container Debug
    docker:
      name: "{{containerName}}"
      state: reloaded
      command: "java  -Xdebug -Xrunjdwp:server=y,transport=dt_socket,suspend=n,address={{debugPort}} -jar {{containerImage}}-{{containerJarVersion}}.jar"
    when: ({{enableDebug}} == true)

  - name: Start Container
    docker:
      name: "{{containerName}}"
      state: reloaded
      command: "java -jar {{containerImage}}-{{containerJarVersion}}.jar"
    when: ({{enableDebug}} == false)
like image 943
Ash Avatar asked Apr 26 '16 08:04

Ash


People also ask

How can we pass variables as arguments to ansible?

The easiest way to pass Pass Variables value to Ansible Playbook in the command line is using the extra variables parameter of the “ansible-playbook” command. This is very useful to combine your Ansible Playbook with some pre-existent automation or script.


1 Answers

I think you will still have to use a conditional somewhere (You want to do different things based on a condition in the end..:).

The only thing I can think of is avoid you writing your task twice ( causing all those annoying skipped ), you could do the following:

     # file: play.yml

     - include_vars: debug_vars.yml
        when: enableDebug == True

     - include_vars: prod_vars.yml
        when: enableDebug == False


     - name: Start Container
       docker:
          name: "{{containerName}}"
          state: reloaded
          command: "{{ start_container_command }}"



      # file: debug_vars.yml
        start_container_command: "java  -Xdebug -Xrunjdwp:server=y,transport=dt_socket,suspend=n,address={{debugPort}} -jar {{containerImage}}-{{containerJarVersion}}.jar"

      # file: prod_vars.yml
        start_container_command: "java -jar {{containerImage}}-{{containerJarVersion}}.jar"
like image 199
shaps Avatar answered Sep 18 '22 17:09

shaps