Ansible Inventory Variables – ansible_port with Examples
Ansible’s robust capabilities in infrastructure automation stem from its flexible configuration options. One such feature is the inventory file, which holds information about the managed nodes. Here, we often use inventory variables to control specific connection parameters, with
ansible_port being a common choice. This blog post explores the usage of
ansible_port with practical examples.
ansible_port variable in Ansible inventory specifies the port number that Ansible should use to connect to the target host. By default, Ansible uses port 22 for SSH connections (the most common connection type). However, if your host uses a non-default port, you can use the
ansible_port variable to specify it.
Defining ansible_port in the Inventory File
To define the
ansible_port variable, add it to your inventory file. The general format is
alias ansible_host=your_actual_host ansible_port=your_port. Here’s how to set it up:
Example with Non-Default SSH Port
Suppose you have a server with the IP address
192.168.1.100 that uses port 2222 for SSH connections. To specify this in your inventory file, you’d write:
my_server ansible_host=192.168.1.100 ansible_port=2222
Using ansible_port in a Playbook
ansible_port is defined in your inventory file, Ansible will use that port to connect to the corresponding host. For instance, consider the following playbook:
- hosts: my_server
- name: Install Apache
command: sudo apt-get install apache2 -y
When you run this playbook, Ansible will connect to
192.168.1.100) on port
2222 and execute the command to install Apache.
ansible_port inventory variable allows you to specify the connection port for each host, enabling you to handle hosts with non-default SSH ports seamlessly. This capability, along with other inventory variables, contributes to Ansible’s flexibility and ease of use in managing diverse infrastructures.