Hello World with Jinja
Tip
We recommend to use the Sandbox to play around with this example.
Tip
All the files from this section are in hello-world-with-jinja.zip.
In Introduction, it was mentioned that inventory can contain variables. In this section, you will learn how to use variables from the inventory, vault, or command line in the playbook.
Note
Variables are passed to Ansible from the command line using --extra-vars.
Inventory
web:
hosts:
managed_node_01:
ansible_user: ansible
ansible_password: '{{ managed_node_password }}'
hello_world_text: Hello world!
The above inventory defines a variable named hello_world_text and uses a variable managed_node_password defined in the vault.
Playbook
- name: My first play
hosts:
- web
tasks:
- name: Print message
ansible.builtin.debug:
msg: '{{ hello_world_text }}'
The above playbook uses the variable named hello_world_text defined in the inventory.
Important
The {{ variable_name }} is from Jinja.
Running
cd hello-world-with-jinja
--ask-vault-pass \
-i inventories/production.yml \
--extra-vars @vault/production \
playbook.yaml
Note
The password for the vault used in the example is 123. You must use a strong passwords, for example, a minimum of 8 randomly generated characters.
returns
PLAY [My first play] ***********************************************************
TASK [Gathering Facts] *********************************************************
ok: [managed_node_01]
TASK [Print message] ***********************************************************
ok: [managed_node_01] => {
"msg": "Hello world!"
}
PLAY RECAP *********************************************************************
managed_node_01 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Filters
Jinja allow the use of filters to modify the value of variables. You can use Jinja’s builtin filters, Ansible’s builtin filters, or your own custom filter. Filters are separated from the variable by a pipe symbol (|) and may have optional arguments in parentheses. Multiple filters can be chained.
Playbook
- name: My first play
hosts:
- web
tasks:
- name: Print message
ansible.builtin.debug:
msg: '{{ hello_world_text | upper | truncate(6) }}'
Running
cd hello-world-with-jinja
ansible-playbook \
--ask-vault-pass \
-i inventories/production.yml \
--extra-vars @vault/production \
playbook-with-filter.yaml
Note
The password for the vault used in the example is 123. You must use a strong passwords, for example, a minimum of 8 randomly generated characters.
returns
PLAY [My first play] ***********************************************************
TASK [Gathering Facts] *********************************************************
ok: [managed_node_01]
TASK [Print message] ***********************************************************
ok: [managed_node_01] => {
"msg": "HEL..."
}
PLAY RECAP *********************************************************************
managed_node_01 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0