Getting Started with Ansible

This is a breif guide of how I get ansible up and running on systems in the simplest way possible. I will be updating this guide as my configuration changes, however I would like to keep it as simple as possible. This is aimed at Debian/Ubuntu installations however it can be easily adapted to most linux distros just by using the appropriate package manager.

Generating and installing SSH keypairs

Generate a ed25519 keypair. This will be used to connect to our servers through ansible. The security of this key is of the utmost importance as this will give essentially root access to our systems.

Do not put a password on the key, we want ansible to be able to be run unencumbered.

ssh-keygen -t ed25519 -C "Ansible key" -f ~/.ssh/ansible

Then go ahead and copy the public key each server you wish to configure with ansible.

ssh-copy-id -i ~/.ssh/ansible.pub <host ip>

Check the connection by ssh-ing into the server without a password (or don't).

ssh -i ~/.ssh/ansible.pub <host ip>

Install ansible

Run the following command to install ansible

sudo apt update && sudo apt install ansible -y

Configuring Ansible

Create an inventory list

<host ip 1>
<host ip 2>
.
.
.
<host ip n>

At this point you should be able to ping all the servers with this command.

ansible all --key-file ~/.ssh/ansible -i inventory -m ping

Now lets change the defaults so we don't have to type that long command.

touch ansible.cfg

Add this to your ansible.cfg

[defaults]
inventory = inventory
private_key_file = ~/.ssh/ansible

Now you should be able to ping everything with this simple command.

ansible all -m ping

You can also gather facts about the machines with this. Gathering facts gives you a lot of information about the systems including system hardware details, OS details, installed packages and more.

ansible all -m gather_facts

Now lets create a playbook to automate the deployment (somewhat).

---

- hosts: all
  become: true
  pre_tasks:

  - name: Update system
    tags: always
    apt:
      upgrade: dist
      update_cache: true

- hosts: all
  become: true
  tasks:

  - name: Create ansible user
    user:
      name: ansible
      groups: root

  - name: Add ssh key for ansible user
    authorized_key:
      user: ansible
      state: present
      key: "{{ lookup('file', '/home/jake/.ssh/ansible.pub') }}"

  - name: Add sudoers file for ansible user
    copy:
      content: "ansible ALL=(ALL) NOPASSWD: ALL"
      dest: /etc/sudoers.d/ansible
      owner: root
      group: root
      mode: 0440

This will create a user and pass the same key we generated for ansible to the system and configure it for the ansible user. Now you will never have to run the --ask-become-pass for privilege escalation.

Make sure you add the following to your ansible.cfg

remote_user = ansible

Now to boostrap a system simply copy the ssh key and run the playbook.

ansible-playbook bootstrap.yml -u user --ask-become-pass --limit 192.168.1.5