Ernsibl
Ernsibl

Reputation: 191

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

Upvotes: 19

Views: 32802

Answers (2)

raring-coffee20
raring-coffee20

Reputation: 300

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

Upvotes: 1

nik.shornikov
nik.shornikov

Reputation: 1935

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.

Upvotes: 27

Related Questions