Initial Server Setup with Ansible

Ansible is a configuration automation tool which is simple to use. It helps to automate software provisioning, configuration management, and application deployment. We use Ansible to set up our servers from DigitalOcean.

First, we need an Inventory file which lists either the IP address or hostname of each node that is accessible by Ansible.

hosts.ini

[bare]
bare-server01 ansible_host=server01 ansible_user=root

[digitalocean:vars]
user=account01
ssh_key='.ssh/id_rsa'

[digitalocean]
server01 ansible_host=server01 ansible_user='{{user}}' ansible_ssh_private_key_file='{{ssh_key}}'

Then, we write down our task in the playbook. Playbooks are YAML files that express configurations, deployment, and orchestration in Ansible, and allows Ansible to perform operations on managed nodes. Each Playbook maps a group of hosts to a set of roles. Each role is represented by calls to Ansible tasks.

host-setup.yml

---
- name: Setup host
  become: yes
  hosts: '{{ dst_hosts }}'
  tasks:
    - name: Add `account01` user with password
      vars:
        # 'yourpassword'
        passwd: ''
      user:
        name: account01
        groups: sudo
        password: '{{ passwd }}'
        shell: /bin/bash

    - name: Add ssh authorized key
      authorized_key:
        user: account01
        state: present
        key: "{{ lookup('file', lookup('env','HOME') + '/.ssh/id_rsa.pub') }}"

    - name: Disable password for sudo
      copy:
        # To install Docker, we need to disable password for sudo
        # Put '%sudo ALL=NOPASSWD: ALL' in the './files/sudoers'
        src: ./files/sudoers
        dest: /etc/sudoers.d/sudoers
        owner: root
        group: root
        mode: 0644

    - name: Disable ssh root login
      lineinfile:
        path: /etc/ssh/sshd_config
        backup: yes
        regexp: '^PermitRootLogin yes'
        line: 'PermitRootLogin no'
      notify: 'restart ssh service'

    - name: Disable ssh password login
      lineinfile:
        path: /etc/ssh/sshd_config
        backup: yes
        regexp: '^PasswordAuthentication yes'
        line: 'PasswordAuthentication no'
      notify: 'restart ssh service'

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

With the above playbook, we may do the task with the following command:

$ ansible-playbook -i host.ini host-setup.yml -e dst_hosts=bare --ask-pass

Notes
You can generate password with Python 3 script:

$ python3 -c "from passlib.hash import sha512_crypt; import getpass; print(sha512_crypt.using(rounds=5000).hash(getpass.getpass()))"

0 Comments

Add Yours →

Leave a Reply