Learn how to configure default SSH credentials for seamless Ansible automation.

Introduction

When using Ansible to manage infrastructure, specifying the same username and password for each host in the inventory file can be repetitive. To streamline this process and set default credentials globally, follow these best practices.


1. Setting Default Variables in the Inventory File

You can use the [all:vars] group in your inventory file to define default values for all hosts.

For example:

[all:vars]
ansible_connection=ssh
ansible_user=vagrant
ansible_password=vagrant

This method eliminates the need to specify ansible_user and ansible_password for individual hosts.


2. Using Group Variables

If you want to specify default credentials for a specific group of hosts, you can create a directory structure following Ansible best practices. For instance:

inventory/
  group_vars/
    all.yml

Content of all.yml:

ansible_connection: ssh
ansible_user: vagrant
ansible_password: vagrant

You can also create separate files for each group like group_vars/master.yml for the master group.


3. Dynamic Inventory or Central Configuration

For larger environments:

  • Use dynamic inventory scripts to generate host details dynamically.
  • Define these variables in ansible.cfg to make them universally available.

For ansible.cfg:

[defaults]
inventory = ./inventory
host_key_checking = False

[privilege_escalation]
become = True
become_method = sudo
become_user = root

4. Avoid Hardcoding Credentials

While these methods work well, hardcoding credentials in plain text is a security risk. To secure your Ansible environment:

  • Use SSH keys instead of passwords.
  • Store sensitive credentials in encrypted files using Ansible Vault:
    ansible-vault create vars.yml
    
    Add credentials securely:
    ansible_user: vagrant
    ansible_password: vagrant
    
    Use these variables in playbooks:
    - hosts: all
      vars_files:
        - vars.yml
      tasks:
        - name: Test connectivity
          ping:
    

5. Testing Your Configuration

Run a basic ping command to ensure your configuration works:

ansible all -m ping

If configured correctly, the output should confirm successful connectivity without needing to repeatedly specify credentials.


By following these methods, you can manage credentials effectively, reduce redundancy, and ensure secure and streamlined automation using Ansible.

Subscribe to the YouTube channel, Medium, and Website, X (formerly Twitter) to not miss the next episode of the Ansible Pilot.

Academy

Learn the Ansible automation technology with some real-life examples in my Udemy 300+ Lessons Video Course.

BUY the Complete Udemy 300+ Lessons Video Course
.

My book Ansible By Examples: 200+ Automation Examples For Linux and Windows System Administrator and DevOps.

BUY the Complete PDF BOOK to easily Copy and Paste the 250+ Ansible code


Want to keep this project going? Please donate.

Patreon Buy me a Pizza