How to install Ansible on Ubuntu 18.04 for IT automation

Ansible is an open source and free configuration management IT tool. It is similar to Chef or Puppet. It works over SSH-based session and does not need any software or client agent on remote Unix servers. One can use Ansible to manage Linux, Unix, macOS, and *BSD family of operating systems. This page shows how to install ansible and set up your first Ansible playbook on Ubuntu Linux 1

 

Procedure to install Ansible on Ubuntu 18.04

  1. Update your Ubuntu 18.04 system, run: sudo apt update
  2. Install Ansible on Ubuntu 18.04, run: sudo apt install ansible
  3. Upgrade Ansible in Ubuntu 18.04, run: sudo apt upgrade ansible
  4. Set up ssh key-based authentication
  5. Test Ansible

 

Step 1. Ubuntu Linux install Ansible

Type the following apt command to update Ubuntu box:

{admin@ubuntu:~}$ sudo apt update

 

Sample outputs:

 

Hit:1 http://archive.ubuntu.com/ubuntu bionic InRelease
Get:2 http://security.ubuntu.com/ubuntu bionic-security InRelease [83.2 kB]
Get:3 http://archive.ubuntu.com/ubuntu bionic-updates InRelease [88.7 kB]          
Fetched 172 kB in 1s (198 kB/s)                                      
Reading package lists... Done
Building dependency tree       
Reading state information... Done
All packages are up to date.

 

Search it:

{admin@ubuntu:~}$$ apt search ansible

 

Sample outputs:

 

ansible - Configuration management, deployment, and task execution system
ansible-lint - lint tool for Ansible playbooks
ansible-tower-cli - command line tool for Ansible Tower and AWX Project
ansible-tower-cli-doc - documentation for tower-cli command line tool and library
bootstrap-vz - tool for creating Debian images for cloud platforms (CLI)
pyinfra - state based and programmable service deployment tool
python-reclass - hierarchical inventory backend for configuration management systems
python-tower-cli - Python 2 client library for the Ansible Tower and AWX Project's REST API
python3-tower-cli - Python 3 client library for the Ansible Tower and AWX Project's REST API
reclass - hierarchical inventory backend for configuration management systems
reclass-doc - reclass documentation
ssg-applications - SCAP Guides and benchmarks targeting userspace applications
ssg-debderived - SCAP Guides and benchmarks targeting Debian-based OS
ssg-debian - SCAP Guides and benchmarks targeting Debian 8
ssg-nondebian - SCAP Guides and benchmarks targeting other GNU/Linux OS
vim-syntastic - Syntax checking hacks for vim

 

 

Find out information about the Ansible package, run:

{admin@ubuntu:~}$ apt show ansible

 

Sample outputs:

 

Package: ansible
Version: 2.5.1+dfsg-1
Priority: optional
Section: universe/admin
Origin: Ubuntu
Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Original-Maintainer: Harlan Lieberman-Berg <hlieberman@debian.org>
Bugs: https://bugs.launchpad.net/ubuntu/+filebug
Installed-Size: 26.9 MB
Depends: python-cryptography, python-jinja2, python-paramiko, python-pkg-resources, python-yaml, python:any (<< 2.8), python:any (>= 2.7.5-5~), python-crypto, python-httplib2, python-netaddr
Recommends: python-jmespath, python-kerberos, python-libcloud, python-selinux, python-winrm (>= 0.1.1), python-xmltodict
Suggests: cowsay, sshpass
Homepage: https://www.ansible.com
Download-Size: 3,197 kB
APT-Sources: http://archive.ubuntu.com/ubuntu bionic/universe amd64 Packages
Description: Configuration management, deployment, and task execution system
 Ansible is a radically simple model-driven configuration management,
 multi-node deployment, and remote task execution system. Ansible works
 over SSH and does not require any software or daemons to be installed
 on remote nodes. Extension modules can be written in any language and
 are transferred to managed machines automatically.

 

Installing Ansbile on Ubuntu Linux

Finally, type the following apt command:

{admin@ubuntu:~}$ sudo apt install ansible

 

Find the Ansible version

We can verify the Ansible version by running the following command:

{admin@ubuntu:~}$ ansible --version

 

Sample outputs:

ansible 2.5.1
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/home/admin/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/dist-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.15rc1 (default, Nov 12 2018, 14:31:15) [GCC 7.3.0]

 

Step 2. Set up ssh keys on a Linux or Unix

First, create the key pair using the ssh-keygen command on your Ubuntu Linux desktop/workstation:

{admin@ubuntu:~}$ ssh-keygen -t ed25519 -C "Desktop ssh key"

 

Next, copy and install the public key in remote Linux/Unix/BSD servers using the ssh-copy-id command:

{admin@ubuntu:~}$ ssh-copy-id -i $HOME/.ssh/id_ed25519.pub user@ubuntu-server-ec2
{admin@ubuntu:~}$ ssh-copy-id -i $HOME/.ssh/id_ed25519.pub ec2-user@freebsd-server-lightsail
{admin@ubuntu:~}$ ssh-copy-id -i $HOME/.ssh/id_ed25519.pub admin@centos-server-instahostz

 

Test password less log in using the ssh command:

{admin@ubuntu:~}$ ssh admin@centos-server-instahostz
{admin@ubuntu:~}$ ssh ec2-user@freebsd-server-lightsail

 

Step 3. Test the Ansible

 

First, create an inventory file as follows on a control machine:

{admin@ubuntu:~}$ vi inventory

 

Add hostnames/IP address of all remote Linux/*BSD servers:

## my vms/server hosted locally ##
[lanhosts]
192.168.2.203
192.168.2.207

## my vms/servers hosted by AWS (EC2/Lightsail) ##
[awshosts]
vm1.ucartz.biz

## my instahostz VMs ##
[instahostzhosts]
vm2.ucartz.biz

 

Next, run the uptime command and lsb_release command on two hosts located in my LAN i.e. lanhosts group as user admin:

{admin@ubuntu:~}$ ansible -u admin -i inventory -m raw -a 'uptime' lanhosts
{admin@ubuntu:~}$ ansible -u admin -i inventory -m raw -a 'lsb_release -a' lanhosts

 

Step 4. Writing your first Ansible playbook to manage Linux/Unix servers

First, update your inventory file to indicate user name and method to become sudo on the remote server. Here is my updated hosts file displayed with the cat command:

cat inventory

 

Sample config file:

[all:vars]
ansible_user='admin'           # Username for ssh connection
ansible_become='yes'             # Run commands as root user?
ansible_become_pass='PasswordForadminUser' # Password for sudo user i.e. ansible_user password
ansible_become_method='sudo'     # How do I become root user? Use sudo.
 
## my vms/server hosted locally ##
## Setup python path on remote server ansible_python_interpreter ##
[lanhosts]
192.168.2.203 ansible_python_interpreter='/usr/bin/python2'
192.168.2.207 ansible_python_interpreter='/usr/bin/python3'
 
## my vms/servers hosted by AWS (EC2/Lightsail) ##
[awshosts]
vm1.ucartz.biz
 
## my instahostz VMs ##
[instahostzhosts]
vm2.ucartz.biz

 

A playbook is nothing but scripts/commands that executed on the remote box. Create a playbook named date.yml as follows using a text editor such as vim command/nano command: 

vim date.yml

 

Append the following code: 

---
- hosts: lanhosts
 
  tasks:
          - name: Get date for testing purpose
            command: /bin/date
            changed_when: False
            register: date
 
          - debug: var={{ item }}
            with_items:
                    - date.stdout

 

Playbooks in Ansible use Yaml. Next, run it as follows from Ubuntu Linux workstation/control machine:

{admin@ubuntu:~}$ ansible-playbook -i inventory date.yml

 

A note about password stored in an insecure format

 

Take a close look at the following config directory in inventory file:

 

ansible_become_pass='PasswordForadminUser'

It is a bad idea to store password and other sensitive information in clear text format. Let us fix this:

{admin@ubuntu:~}$ vim inventory

 

Find:

ansible_become_pass='PasswordForadminUser'

 

Replace:

ansible_become_pass='{{ my_user_password }}'

 

Save and close the file. Next create a new encrypted data file named passwords.yml, run the following command:

{admin@ubuntu:~}$ ansible-vault create passwords.yml

 

Set the password for vault. After providing a password, the tool will start whatever editor you have defined with $EDITOR. Append the following:

my_user_password: your_password_for_ansible_user

 

Save and close the file. Run it as follows:

{admin@ubuntu:~}$ ansible-playbook -i inventory --ask-vault-pass --extra-vars '@passwords.yml' date.yml

 

Adding user using the Ansible playbook

 

Say you need to add a new user named tom all hosts in lanhosts group. Create a new playbook named add-tom-user.yml:

 

---

- hosts: lanhosts

  tasks:

          - name: Add a new user to my Linux VMs with password disabled but allow ssh log in

 ---
- hosts: lanhosts
  tasks:
          - name: Add a new user to my Linux VMs with password disabled but allow ssh log in
            user:
                    name: tom
                    comment: "Tom Cat"
                    shell: /bin/bash
                    groups: sudo
                    append: yes
                    password: *
          - name: Upload ssh key for user tom for log in purpose
            authorized_key:
                    user: admin
                    state: present
                    manage_dir: yes
                    key: "{{ lookup('file', '/home/admin/.ssh/tom_id_ed25519.pub') }}"           

 

Run it as follows:

{admin@ubuntu:~}$ ansible-playbook -i inventory --ask-vault-pass --extra-vars '@passwords.yml' add-tom-user.yml

 

How to add and remove packages

 

In this example, we are going to add and remove packages using the apt command for all hosts located in instahostzhosts group. Create a file named software.yml:

---
- hosts: instahostzhosts
  tasks:
          - name: Add a list of software on instahostz VMs ...
            apt:
                    name: "{{ packages }}"
                    state: present
            vars:
                    packages:
                            - nginx
                            - php7
                            - htop
                            - iotop
                            - nicstat
                            - vnstat
          - name: Delete a list of software from instahostz VMs ...
            apt:
                    name: "{{ packages }}"
                    state: absent
            vars:
                    packages:
                            - nano
                            - apache2

 

Again run it as follows:

{admin@ubuntu:~}$ ansible-playbook -i inventory --ask-vault-pass --extra-vars '@passwords.yml' software.yml

 

Conclusion

And there you have it, Ansible set up and tested to manage Linux or Unix boxes. Ansible works very fast for repeated tasks such as adding users in bulk, installing software, configuring *BSD/Linux/Unix boxes. YAML takes a little time to master but easy to learn.

 

Was this answer helpful? 0 Users Found This Useful (0 Votes)