How to Make Ansible Connection Parameters Dependent on the Controller Host?
I need to configure Ansible so that the connection parameters depend on the host from which Ansible is executed. Here are a few example scenarios:
1. When Ansible is run on the local host, it's preferable to use a local connection with privilege escalation rather than SSH.
2. Some hosts may have non-standard firewall rules (e.g., using ProxyJump or non-standard SSH ports).
3. In virtualized or containerized environments, it might be necessary to use local tools (e.g., docker exec or oc rsh) to interact with services.
4. Different hosts may use different accounts for connections.
How can I properly organize Ansible execution based on the controller host?
Answers
Morten Rasmussen
Thank you for your ideas! Dynamic inventory indeed suits my needs. Also, the idea of using dynamic connection variables based on the controller host is very interesting — I will use it in my projects.
Nicolas Dubois
Another solution is to use dynamic variables based on the host from which Ansible is executed. This can be done using a construct like:
ansible_connection: "{{ 'local' if lookup('pipe', 'hostname') == 'myclient1' else 'ssh' }}"
This allows you to use a local connection for myclient1 and SSH connection for other hosts.
Marie Martin
You can also use a dynamic inventory to automatically determine connection parameters based on the current host:
#!/usr/bin/env pythonimport json
inventory = {
'all': {
'hosts': ['localhost', 'server1', 'container1'],
'vars': {
'ansible_become': 'yes'
}
},
'_meta': {
'hostvars': {
'localhost': {
'ansible_connection': 'local'
},
'server1': {
'ansible_host': '192.0.2.10',
'ansible_user': 'admin',
'ansible_port': 2222,
'ansible_ssh_common_args': '-o ProxyJump=jumphost'
},
'container1': {
'ansible_connection': 'docker'
}
}
}
}
print(json.dumps(inventory, indent=2))
Make the script executable and use it in Ansible:
chmod +x dynamic_inventory.pyansible-playbook -i dynamic_inventory.py playbook.yml
Matteo Conti
Yes, you can configure connection parameters based on the host by using variables in the inventory. For example:
[all]localhost ansible_connection=local ansible_become=yes
server1 ansible_host=192.0.2.10 ansible_user=admin ansible_port=2222 ansible_ssh_common_args='-o ProxyJump=jumphost'
container1 ansible_connection=docker
To apply different connection settings based on the controller host, you can use conditional statements in your playbooks.
Example:
- hosts: alltasks:
- name: For localhost
debug:
msg: "This is localhost"
when: inventory_hostname == 'localhost'
- name: For server1
debug:
msg: "This is server1"
when: inventory_hostname == 'server1'
- name: For container1
debug:
msg: "This is container1"
when: inventory_hostname == 'container1'
Morten Rasmussen
Thank you for the ideas!