How to access Ansible remote machine using SSH user and key?

How to access Ansible remote machine using SSH user and key?

There are following ways, you can autheticte linux remote server using Ansible.

Method 1 – Password Less authentication

SSH Passwordless Login Using SSH Keygen in 5 Easy Steps

If You want to automate this process using Ansible in mutiple machine, follow this
https://everythingshouldbevirtual.com/ansible-ssh-key-distribution-for-password-less-ssh/

Method 2 – SSH key file using command line

[code]ansible-playbook -i hosts playbook.yml –key-file=remote-access.pem -u ec2-user –become[/code]

Method 3 – SSH key file in the inventory file:

[code]myHost1 ansible_ssh_private_key_file=remote-access.pem ansible_user=ec2-user
myHost2 ansible_ssh_private_key_file=remote-access.pem ansible_user=ec2-user[/code]

Method 4 – SSH key file in the host_vars:

[code]# hosts_vars/myHost1.yml
ansible_ssh_private_key_file: ~/.ssh/mykey1.pem
ansible_user=ec2-user
# hosts_vars/myHost2.yml
ansible_ssh_private_key_file: ~/.ssh/mykey2.pem
ansible_user=ec2-user[/code]

Method 5 – SSH key file in the group_vars:

[code]# hosts_vars/myHost1.yml
ansible_ssh_private_key_file: ~/.ssh/mykey1.pem
ansible_user=ec2-user
# hosts_vars/myHost2.yml
ansible_ssh_private_key_file: ~/.ssh/mykey2.pem
ansible_user=ec2-user[/code]

Method 6 – SSH key file in the vars section of your play:

[code]- hosts: myHost
remote_user: ubuntu
vars_files:
– vars.yml
vars:
ansible_ssh_private_key_file: "{{ key1 }}"
tasks:
– name: Echo a hello message
command: echo hello[/code]

Method 7 – SSH key file in the ansible.cfg:

[code][defaults]
inventory: <YOUR INVENTORY>
remote_user = <YOUR USER>
private_key_file = <PATH TO KEY_FILE>[/code]

Rajesh Kumar

DevOps Architect - Mentor - Coach - Trainer at Cotocus
Email - DevOps@RajeshKumar.xyz
CV - www.RajeshKumar.xyz

Total, Over 15 years of extensive experience working with more than 8 software MNCs for software development/maintenance and production environments involved in continuous improvement and automating entire life cycle using latest devops tools and techniques from design and architecture, through implementation, deployment, and successful operations. Also, helping more than 70 software organizations globally, providing coaching, mentoring and consulting in devops, CICD, cloud, containers and operations.

I help software organization to improve a quality of the software, reducing the software development/operational cost and immediate feedback/monitoring. Have in-depth working experience in following domains with real project implementation.

- Test Driven DevOps Approach
- Continuous Integration
- Continuous Delivery
- Continuous Deployment
- Continuous Inspection
- Technical Debt Reduction
- Containerization/Micro Services Using Kubernetes & Docker
- Cloud Migration using AWS
- Production Monitoring & Postmortem
Rajesh Kumar