Ansible Inventory Variables – ansible_connection with Examples
In Ansible’s world of automation, Inventory files are the source of truth about the nodes you manage. Inventory variables are a powerful feature, enhancing the flexibility of your playbooks. One such variable is
ansible_connection, which plays a critical role in defining the connection type to your hosts. This blog post explores the use of
ansible_connection with illustrative examples.
ansible_connection variable determines the type of connection to use when reaching out to the targeted host. This setting is particularly useful when you manage hosts with different operating systems, connection types, or both.
Some commonly used connection types are:
ssh: The default connection type. It is suitable for most Linux/Unix hosts.
local: Executes the commands on the local node.
winrm: Used for Windows hosts.
docker: Used for Docker containers.
Defining ansible_connection in the Inventory File
To specify the
ansible_connection variable, add it to your inventory file, following the format:
alias ansible_host=your_actual_host ansible_connection=connection_type. Let’s see how to apply this in the context of different connection types.
In most cases,
ssh is the default connection type. However, you might want to explicitly define it in your inventory file:
linuxserver ansible_host=192.168.1.100 ansible_connection=ssh
If you are running Ansible on the target machine, you can use the
local connection type:
If you are managing Windows hosts, you will typically use the
windowsserver ansible_host=192.168.1.101 ansible_connection=winrm
For Docker containers, use the
docker connection type:
dockercontainer ansible_host=my_container ansible_connection=docker
Using ansible_connection in a Playbook
Now that we understand how to define
ansible_connection in an inventory file, let’s see how it’s used in practice with a playbook:
- hosts: linuxserver
- name: Check the disk usage
command: df -h
- hosts: windowsserver
- name: Check free disk space
win_shell: Get-PSDrive C | Select-Object Free
- hosts: dockercontainer
- name: Check available disk space
command: df -h
In this playbook, Ansible uses the connection types defined in the inventory file to connect to the respective hosts and execute the commands.
ansible_connection inventory variable plays a critical role in determining how Ansible connects to your hosts. By understanding and effectively using this variable, you can manage a diverse set of hosts with varying operating systems and connection requirements.