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
7 months ago
Rating
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
7 months ago
Rating
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
7 months ago
Rating
You can also use a dynamic inventory to automatically determine connection parameters based on the current host:
Make the script executable and use it in Ansible:
Matteo Conti
7 months ago
1 comment
Rating
Yes, you can configure connection parameters based on the host by using variables in the inventory. For example:
To apply different connection settings based on the controller host, you can use conditional statements in your playbooks.
Example:
Morten Rasmussen
7 months ago
Rating
Thank you for the ideas!