Ansible variable assignment

10,917

You can use the set_fact module to increment your variable:

- set_fact: some_variable={{ some_variable | int + 1 }}

Your condition for running the extra task then should look like this:

  when: some_variable | int == 5

Make sure you always cast the value to an int with | int or it will be handled as a string.

Share:
10,917
ady8531
Author by

ady8531

Updated on June 28, 2022

Comments

  • ady8531
    ady8531 over 1 year

    I want to run a role 10 times in a playbook and only on the 5th run of that role, I want it to run the second shell cmd from within that role. How can I address that? Playbook:

    - name: bla bla
      hosts: ALL
      remote_user: root
      vars:
         some_variable: 0
      roles:
        - role: nonreg
      whentorun:
        - post
    

    The actual role is this:

    - name: basic
      shell: /scripts/nonReg/expoNonRegTest.sh {{ item }}
      {{ some variable }} ++ ???
      with_items: "{{ whentorun }}"
    - name: on 5th run
      shell: /scripts/nonReg/expoNonRegTest.sh diff
      when: {{ some variable }} == 5 ????
    

    How can I do that? How can I declare a variable and assign a value to it (during the run o a role/playbook)? What is the syntax ? In the ansible documentation, at variables, there isn't a simple example of how can you assign a value to a variable (not with register :P)