Ansible and private networks
Ansible is an efficient tool to automate an infrastructure. No need for an agent to be installed on every system, it only needs SSH. But… What happens if some part of the infrastructure is not directly accessible from the machine running Ansible?
This article will present you a simple solution and hopefully prevent you from spending hours on it!
Diagram
Here is an example of infrastructure we need to manage by running Ansible scripts only from server A (a GitLab runner for example).
Problem
A can reach B with SSH but cannot reach C or D directly (different networks). So how can Ansible apply changes on C and D from A?
A can reach C or D through B with SSH but how to do it easily with Ansible?
Solution
- If it is not the case, generate SSH keys without a passphrase on A (I have not been able to make Ansible work in this case with a passphrase)
ssh-keygen -t rsa -b 4096 -C "username@my.domain"
- If you did generate new keys, copy them on B (you’ll be prompted to enter your password)
ssh-copy-id username@servername
- Make sure you can login from A to B without any password or passphrase
ssh servername
- If it doesn’t exist, create a file ~/.ssh/config on A with the right permissions (ref. Using the SSH Config File)
touch ~/.ssh/config
chmod 600 ~/.ssh/config
- Edit the file ~/.ssh/config on A
Host 192.168.56.*
ProxyCommand ssh -W %h:%p username@servername
- Make sure you can access server C or D through SSH from A
ssh 192.168.56.12 -l remoteuser
- Specify ansible parameters for C and D in the Ansible inventory host file on A
[lab]
k8S-node1 ansible_host=192.168.56.11 ansible_user=remoteuser ansible_ssh_pass=*******
k8S-node2 ansible_host=192.168.56.12 ansible_user=remoteuser ansible_ssh_pass=*******
- Ping C and D with Ansible from A
ansible -i inventory all -m ping
- Et voilà ! You should see something like that
Lessons learned
- Using ProxyJump SSH option seemed too complicated
- Ansible ProxyCommand didn’t work
- Use -v (-vv, -vvv, -vvvv) on SSH and Ansible commands to have verbose logs!
Acknowledgments
- The article Ansible, Bastion Host, ProxyCommand of Paul Skarseth helped me find the solution 🙂
Latest posts by bertrand (see all)
- Install Rancher on Azure Kubernetes Service (AKS) - September 25, 2023
- Automate NeuVector installation and management with Fleet – The GitOps way - August 25, 2023
- AKS startup error: Token refresh failed with invalid client secret error - August 22, 2023