ansible variables

In Ansible, variables are used to store values that can be reused throughout playbooks, roles, and tasks. Variables can be defined at the playbook, role, and task level, and can be used to store values such as IP addresses, hostnames, usernames, passwords, and configuration settings.

There are several ways to define variables in Ansible:

  1. Inline: Variables can be defined inline within a task or playbook using the vars keyword.

  2. Inventory: Variables can be defined in the inventory file using the host_vars and group_vars directories.

  3. Playbooks: Variables can be defined at the playbook level using the vars keyword.

  4. Roles: Variables can be defined at the role level using the vars directory.

  5. Command line: Variables can be passed in as command line arguments using the -e flag.

Here are some examples of how variables can be defined in Ansible:

- name: Example task
  hosts: all
  vars:
    my_var: "Hello, world!"
  tasks:
    - name: Example inline variable
      debug:
        var: my_var
Sou‮r‬ce:www.theitroad.com

In this example, we define a variable called my_var at the playbook level using the vars keyword. We then use the debug module to display the value of the variable.

Variables can also be defined in inventory files using the host_vars and group_vars directories:

inventory/
├── group_vars
│   └── all
├── host_vars
│   └── my_host
└── hosts

In this example, we have an inventory file that contains directories for group_vars and host_vars. Variables defined in these directories can be used in playbooks and tasks.

Variables can also be defined at the role level using the vars directory:

roles/
└── my_role
    ├── defaults
    ├── files
    ├── handlers
    ├── meta
    ├── tasks
    ├── templates
    └── vars
        └── main.yml

In this example, we have a role called my_role that contains a vars directory for defining variables specific to the role.

Finally, variables can be passed in as command line arguments using the -e flag:

ansible-playbook my_playbook.yml -e "my_var=value"

This will pass in a variable called my_var with a value of value to the playbook.