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.
Understanding ansible_connection
The 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.
SSH Connection
In most cases, ssh
is the default connection type. However, you might want to explicitly define it in your inventory file:
1 |
linuxserver ansible_host=192.168.1.100 ansible_connection=ssh |
Local Connection
If you are running Ansible on the target machine, you can use the local
connection type:
1 |
localhost ansible_connection=local |
WinRM Connection
If you are managing Windows hosts, you will typically use the winrm
connection:
1 |
windowsserver ansible_host=192.168.1.101 ansible_connection=winrm |
Docker Connection
For Docker containers, use the docker
connection type:
1 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
--- - hosts: linuxserver tasks: - name: Check the disk usage command: df -h - hosts: windowsserver tasks: - name: Check free disk space win_shell: Get-PSDrive C | Select-Object Free - hosts: dockercontainer tasks: - 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.
Conclusion
The 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.