Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a random number to a variable in ansible?

This is an ansible script that I was expecting to print out the same random number three times. Instead, it prints out three random numbers. How do I assign a random number to a variable in ansible so that it is fixed throughout the playbook?

---
- name: Test random filter
  hosts: localhost
  gather_facts: False
  vars:
    random_number: "{{ 100 | random }}"
  tasks:
    - name: Print the random number
      debug: var=random_number
    - name: Print the random number
      debug: var=random_number
    - name: Print the random number
      debug: var=random_number
like image 372
Ernsibl Avatar asked Feb 12 '15 23:02

Ernsibl


People also ask

How do you assign a value to a variable in Ansible?

Assigning a value to a variable in a playbook is quite easy and straightforward. Begin by calling the vars keyword then call the variable name followed by the value as shown. In the playbook above, the variable name is salutations and the value is Hello world!

How do you create an Ansible variable?

To define a variable in a playbook, simply use the keyword vars before writing your variables with indentation. To access the value of the variable, place it between the double curly braces enclosed with quotation marks. In the above playbook, the greeting variable is substituted by the value Hello world!

Which filter is used to provide default values to variables Ansible?

So if you want to define a default value for a variable you should set it in role/defaults/main. yml . Ansible will use that value only if the variable is not defined somewhere else. Using the Jina2 filters is it possible to do something like {{ variable | default(other_variable) }} ?

What is item variable in Ansible?

item is not a command, but a variable automatically created and populated by Ansible in tasks which use loops. In the following example: - debug: msg: "{{ item }}" with_items: - first - second. the task will be run twice: first time with the variable item set to first , the second time with second .


2 Answers

Just use the set_fact module as a task first:

 - set_fact:
     r: "{{ 100 | random }}"
   run_once: yes

Subsequently, debug: msg=... has the value of r fixed.

like image 134
nik.shornikov Avatar answered Sep 16 '22 17:09

nik.shornikov


Set facts under task:

---
- name: Test random filter
  hosts: localhost
  gather_facts: False
  tasks:
    - name: set fact here
      set_fact:
        randome_number: "{{ 100 | random }}"
      run_once: yes
    - name: Print the random number
      debug: var=random_number
    - name: Print the random number
      debug: var=random_number
    - name: Print the random number
      debug: var=random_number
like image 34
Tuyen Pham Avatar answered Sep 20 '22 17:09

Tuyen Pham