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
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!
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!
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) }} ?
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 .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With