Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible variable assignment

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)

like image 436
ady8531 Avatar asked Mar 16 '15 05:03

ady8531


People also ask

How do you assign variables in Ansible?

You can decide where to set a variable based on the scope you want that value to have. Ansible has three main scopes: Global: this is set by config, environment variables and the command line. Play: each play and contained structures, vars entries (vars; vars_files; vars_prompt), role defaults and vars.

What does {{ }} mean in Ansible?

Ansible uses the jinja2 template. the {{ }} are used to evaluate the expression inside them from the context passed. So {{ '{{' }} evaluates to the string {{ And the while expression {{ docroot }} is written to a template, where docroot could be another template variable.

How do you pass variables in Ansible playbook?

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

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.

like image 114
udondan Avatar answered Oct 22 '22 21:10

udondan