Nodes

Tutorial: Getting Started with Ansible and Configuration Management

Posted by Joel Hans on Apr 24, 2017

A note about tutorials: We encourage our users to try out tutorials, but they aren't fully supported by our team—we can't always provide support when things go wrong. Be sure to check which OS and version it has been tested with before you proceed. If you run into issues, post a comment and we'll try to help out.

If you want a fully managed experience, with dedicated support for any application you might want to run, contact us for more information.

In last week’s blog, we talked about the basics of what configuration management (CM) is and why it could be an incredibly useful tool for you in provisioning, administering, and maintaining your servers.

In this tutorial, we’ll cover using Ansible as a CM tool for setting up a bare CentOS, Debian, and Ubuntu server with some basic access and server hardening tools and settings.

Our goals:

  1. Set up a non-root user
  2. Give the new user sudo access
  3. Disable password-based logins
  4. Disable

Prerequisites

  1. A newly-provisioned or rebuilt server running any of our OS options—CentOS, Debian, or Ubuntu.

Step 1: Install Ansible on your local machine

Before you can start coding up an Ansible playbook, you need to install it on your local machine. There are installation instructions for a variety of platforms, including various *nix distributions and OS X.

Step 2: Edit the Ansible hosts file

In order for Ansible to connect to your VPS, you need to specify its IP address within Ansible’s hosts file. On Linux and OS X machines, that can be found at /etc/ansible/hosts. The beginning of the file should look like this.

# This is the default ansible 'hosts' file.
#
# It should live in /etc/ansible/hosts
#
#   - Comments begin with the '#' character
#   - Blank lines are ignored
#   - Groups of hosts are delimited by [header] elements
#   - You can enter hostnames or ip addresses
#   - A hostname/ip can be a member of multiple groups

# Ex 1: Ungrouped hosts, specify before any group headers.

## green.example.com
## blue.example.com
## 192.168.100.1
## 192.168.100.10

To enable your VPS, simply add the IP address anywhere in this file underneath an [ssdnodes] grouping. There should be no other symbols—like the # comment—in the line.

[ssdnodes]
123.45.67.89

Now, test out your configuration by pinging your VPS. For now, you have to use -u root to ensure you’re trying to connect via the root account.

$ ansible all -m ping -u root

If it’s successful, you’ll see the following output:

123.45.67.89 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

Step 3: Create a basic Ansible playbook

In order to make any of the aforementioned goals a reality, we need to create a Ansible playbook to define the tasks we need completed. The Ansible playbook is in the common .yaml language.

$ mkdir ansible && cd ansible
$ touch create_user.yaml
$ nano create_user.yaml

And here is a basic playbook that accomplishes our goals. Note: This playbook is meant to run on a bare CentOS 7 server. If you want to run this on an Ubuntu/Debian server, simply change the yum line to apt.

---
- hosts: ssdnodes
  remote_user: root

  vars_prompt:

    - name: "user_name"
      prompt: "Enter a name for the new user"
      private: no
      confirm: yes

    - name: "user_password"
      prompt: "Enter a password for the new user"
      private: yes
      encrypt: "sha512_crypt"
      confirm: yes
      salt_size: 7

  tasks:

    - name: Check to make sure we have a 'wheel' group
      group:
        name: wheel
        state: present

    - name: Install the 'sudo' package
      yum:
        name: sudo
        state: latest

    - name: Create the non-root user
      user:
        name: ""
        password: ""
        shell: "/bin/bash"
        groups: "wheel"

    - name: Add local public key for key-based SSH authentication
      authorized_key:
        user: ""
        key: "{{item}}"
      with_file:
        - ~/.ssh/id_rsa.pub

    - name: Restrict root SSH logins
      lineinfile:
        dest: /etc/ssh/sshd_config
        state: present
        regexp: '^#PermitRootLogin'
        line: 'PermitRootLogin no'

    - name: Restrict SSH logins to keys only
      lineinfile:
        dest: /etc/ssh/sshd_config
        state: present
        regexp: '^#PasswordAuthentication'
        line: 'PasswordAuthentication no'

    - name: Restart sshd
      systemd:
        state: restarted
        daemon_reload: yes
        name: sshd

Before we go into how you run this command, let’s walk through what some of these lines do in practice.

- hosts: ssdnodes
  remote_user: root

These two lines dictate which host group we’re going to work with—in this case, the ssdnodes group we created earlier—and specify that we’re using the root login (just this once) to complete our steps.

vars_prompt:

  - name: "user_name"
    prompt: "Enter a name for the new user"
    private: no
    confirm: yes

  - name: "user_password"
    prompt: "Enter a password for the new user"
    private: yes
    encrypt: "sha512_crypt"
    confirm: yes
    salt_size: 7

These two vars_prompt commands will ask for user input to define which username and password they would like to associate with the newly-created account.

Beyond this, each nested block of script that begins with - name: defines a new task that Ansible will complete in sequential order, once the previous task has completed successfully. Failed tasks will cause the entire playbook to stop running. If you follow along with each of the tasks, you can see that we’re installing sudo, creating our new user, adding your SSH public key to the server, and putting some basic restrictions on sshd before restarting it.

Step 4: Run the Ansible playbook

Running this playbook is fairly straightforward. Here’s the command we’ll use:

ansible-playbook create_user.yaml --ask-pass

We need to include --ask-pass so that Ansible uses a password to log into the server rather than try to use an SSH key that isn’t there.

Once you run the command, you’ll be asked to enter the SSH password:. This is the root login for your server—that password can be found in your SSD Nodes dashboard.

Once you’ve entered the root password, you’ll be prompted to specify and confirm a username and password. Once that’s done, Ansible will get to work!

With any luck, Ansible runs smoothly, and you see the following in your terminal:

 ____________
< PLAY RECAP >
 ------------
           ^__^
           (oo)_______
            (__)       )/
                ||----w |
                ||     ||

123.45.67.89               : ok=8    changed=6    unreachable=0    failed=0  

At this point, you’ll be able to log into your new user account using your SSH key. Congratulations! You’re now ready to start provisioning new servers with ease, and with an eye toward security. For more information about how to dive deeper into Ansible for automated server hardening, check out one these resources:

Get 8GB RAM and 40GB SSD of the fastest cloud hosting for only $7.49/mo.

Get started

Our most popular posts:

VPS Comparison: Vultr vs. Digital Ocean vs. Linode vs. SSD Nodes Using Docker and Nginx to Host Multiple Websites Tutorial: Installing OpenVPN on Ubuntu 16.04