How to copy ssh key to remote host using Ansible.

How to copy ssh key to remote host using Ansible.

As we are all aware #Ansible is a configuration management tool that is basically being used to do the changes of configurations on a remote host or on N number of remote hosts, but how will we connect to a remote host to execute our play? the answer is we should copy our client machines’ public key to the remote hosts.

Again is it a good idea to copy the public key to remote hosts manually? I would say yes if the number of remote hosts or less than 5, but is it a good idea to copy manually if we wanted to achieve the same with 100’s of remote hosts? No.

So how can we do that? nice question

Yes, we can achieve this by using an ansible-playbook, which will basically copy our public ssh key to the remote hosts.

But before using this play, Please check if the user for which we are generating the public does exist in the remote hosts or not? If, not please do create one.

Now please add the public key that you have generated to the files directory of your role (ssh-key-copy)that will be copied to the remote host.

Please check the #Ansible code base below which you can use to copy the public ssh-key,

task.yml

---- name: Copy SSh Key | copying shh key to remote host  authorized_key:     user: "<your_user>"     state: present     key: "{{ lookup('file', item) }}"  with_fileglob:  - id_dsa.pub  become: true

role.yml

---- include: ssh-key-copy/main.yaml  become: yes

ansible-playbook.yml

---- name: copying ssh key and updating sudoershosts: <host_target_group_name>gather_facts: falsebecome: trueremote_user: <the user with which you wants to perform the operation>roles:  - ssh-key-copy

Note:

Please use the below command to generate a key-pair,

$ ssh-keygen -t <key-name>