Ansible Inventory Variables – ansible_connection with Examples

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:

Local Connection

If you are running Ansible on the target machine, you can use the local connection type:

WinRM Connection

If you are managing Windows hosts, you will typically use the winrm connection:

Docker Connection

For Docker containers, use the docker connection type:

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:

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.