Ansible Bootstrap Playbook

Learn how to write your first playbook with Ansible. This tutorial shows you how to bootstrap your server for future Ansible runs as well as adding some security.

PLEASE NOTE: This tutorial comes from my course called Discover Ansible and assumes you installed Ansible and configured it to use a hosts file in a specific location.

# Create certificates folder and copy SSH public key
cd ~/apps/ansible
mkdir certificates
cp ~/.ssh/id_rsa.pub certificates

# Create crypted password
# If you are using an environment different from your server (e.g., a Mac), 
# run this command on your server instead
mkpasswd --method=SHA-512 -S 

# if needed to run mkpasswd
sudo apt-get install whois

Create ansible/bootstrap.yml

---
- name: Bootstrap server for future ansible runs
  hosts: all
  remote_user: root

  vars: 
    user_name: creston
    user_pass: $6$gGF67h7gg6$gHpPcLliXbq4wGX8SywQ4BLf/iUaRYNzlN6IBsN1YXI.o/ITmqfeirKcYTenyTo67csjdUTRHTsGVtE0zd9sZ1

  tasks: 
  - name: Update apt cache
    apt: update_cache=yes

  - name: Safe aptitude upgrade
    apt: upgrade=safe
    async: 600
    poll: 5

  - name: Add my user
    user: >
      name={{ user_name }} 
      password={{ user_pass }} 
      shell=/bin/bash 
      groups=sudo 
      append=yes 
      generate_ssh_key=yes 
      ssh_key_bits=2048 
      state=present

  - name: Add my workstation user's public key to the new user
    authorized_key: 
      user: "{{ user_name }}"
      key: "{{ lookup('file', 'certificates/id_rsa.pub') }}" 
      state: present
#    notify: restart ssh

  - name: Change SSH port
    lineinfile: 
      dest: /etc/ssh/sshd_config 
      regexp: "^Port" 
      line: "Port 30000" 
      state: present
#    notify: restart ssh

  - name: Remove root SSH access
    lineinfile: 
      dest: /etc/ssh/sshd_config 
      regexp: "^PermitRootLogin" 
      line: "PermitRootLogin no" 
      state: present
#    notify: restart ssh

  - name: Remove password SSH access
    lineinfile: 
      dest: /etc/ssh/sshd_config 
      regexp: "^PasswordAuthentication" 
      line: "PasswordAuthentication no" 
      state: present

  - name: Reboot the server
    command: /sbin/reboot 

  handlers:
  - name: restart ssh
    service: name=ssh state=restarted

Run your bootstrap playbook from ~/apps/ansible

ansible-playbook bootstrap.yml

Please go ahead and leave a comment below if you have any questions about this tutorial.