Software >> Automation >> Ansible >> Variables >> The various ways of defining a variable

 

 Description Example
 
- name: Installs Apache and starts the service
  hosts: webserver
  vars:
    base_path: /srv/users/host1/mgmt/sys/users
    users:
      joe:
        name: Joe Foo
        home: "{{ base_path }}/joe"
      bob:
        name: Bob Bar
        home: "{{ base_path }}/bob"

  tasks:
  - name: Print user details records
    debug: msg="User {{ item.key }} full name is {{ item.value.name }}. Home is {{ item.value.home }}"
    with_dict: "{{users}}"

Variables defined in the playbook
- hosts: webservers
  vars:
    http_port: 80

Register the output to a variable via register keyword
    ---
    - hosts: all
      tasks:
        - name: Checking if Sources are Available
          shell: echo "This is a test"
          register: results
via set_fact
    - set_fact:
      user: joe
defined with -a or --args:
    ansible-playbook main.yml -a "user=joe"

    ansible-playbook main.yml --args "user=joe"
via vars_prompt
vars:
from: "user"
  vars_prompt:
    - name: "user"
      prompt: "User to create"
via vars_files # put the variables in a .yml file and specify it
# in the playbook such as follows :

vars_files:
  - /vars/environment.yml


environment.yml

---
# in the above example, this would be vars/external_vars.yml
somevar: somevalue
password: magic
task variables
Only for task itself:

  - user: name=joe
    
extra variables
[user@demo ~]$ ansible-playbook users.yml -e "user=joe"
as group variable in inventory file
 

[servers]
demo.example.com

[servers:vars]
user: joe