Define ssh key per host using ansible_ssh_private_key_file

You can define an SSH key per host using the ansible_ssh_private_key_file variable in Ansible. This variable allows you to specify a different private key file for each host or group of hosts.

Here is an example of how you can use the ansible_ssh_private_key_file variable in your inventory file:

[web-servers]
web1 ansible_host=192.168.1.100 ansible_ssh_private_key_file=~/.ssh/web1.pem
web2 ansible_host=192.168.1.101 ansible_ssh_private_key_file=~/.ssh/web2.pem
web3 ansible_host=192.168.1.102 ansible_ssh_private_key_file=~/.ssh/web3.pem
[database-servers]
db1 ansible_host=192.168.1.200 ansible_ssh_private_key_file=~/.ssh/db1.pem
db2 ansible_host=192.168.1.201 ansible_ssh_private_key_file=~/.ssh/db2.pem

In this example, the web-servers group uses the private key file ~/.ssh/web1.pem for the web1 host, ~/.ssh/web2.pem for the web2 host, and so on. Similarly, the database-servers group uses the private key files ~/.ssh/db1.pem and ~/.ssh/db2.pem for the db1 and db2 hosts respectively.

You can also use the ansible_ssh_private_key_file variable for a specific host in a group, for example:

[web-servers]
web1 ansible_host=192.168.1.100 ansible_ssh_private_key_file=~/.ssh/web1.pem
web2 ansible_host=192.168.1.101
web3 ansible_host=192.168.1.102 ansible_ssh_private_key_file=~/.ssh/web3.pem

In this example, the web2 host uses the default ssh key configured in the ssh-agent or the ssh_config file, while web1 and web3 use specific ssh keys.

It’s important to remember that the private key files must be accessible by the user running Ansible and the path of the key file must be an absolute path.

 

In Ansible, you can define a specific ssh key per host using the ansible_ssh_private_key_file variable in your inventory file.

  1. Create an inventory file or edit an existing one.
  2. Under the host or group section for the host you want to specify the key for, add the variable ansible_ssh_private_key_file and set its value to the path of the private ssh key.
[host_or_group]
hostname ansible_ssh_private_key_file=/path/to/private_key
  1. Run your ansible commands specifying the inventory file.
ansible-playbook -i inventory.ini playbook.yml

You can also set this variable in your ansible.cfg file, so that it will be used for all the hosts across your inventory.

[defaults]
private_key = /path/to/private_key

By using ansible_ssh_private_key_file variable you can define different ssh keys for different hosts. This will help you to connect the hosts with different ssh key.

Leave a Comment