Ansible

Ansible | Getting Started

Installation

Install Python 3

Install Ansible

pip install ansible

Setup virtual machines

In this example, we use Vagrant. But using docker is also a good choice

Create Vagrantfile

Change IP Address and Hostname for each virtual machine

Vagrant.configure("2") do |config|
  config.vm.box = "hashicorp/bionic64"
  config.vm.network "public_network", ip: "172.16.2.191", bridge: "en0: Ethernet"

  config.vm.synced_folder "./data", "/DATA"
  config.vm.hostname = "host1"
end

Start virtual machine

vagrant up
vagrant ssh

Configure virtual machine

Install required programm sshpass for running ansible commands as root on target machines.

sudo apt-get install sshpass

Setup SSH permissions

Create ssh key

ssh-keygen -t rsa

Add id_rsa_<user>.pub to virtual machines into $HOME/.ssh/authorized_keys

Setup config files

etc/ansible/hosts

ansible1
ansible2
ansible3

etc/ansible/ansible.cfg

Create Ansible configuration file in current directory with this content:

[defaults]
interpreter_python = auto

Ansible searches for configuration files in the following order, processing the first file it finds and ignoring the rest:

  1. $ANSIBLE_CONFIG if the environment variable is set.
  2. ansible.cfg if it’s in the current directory.
  3. ~/.ansible.cfg if it’s in the user’s home directory.
  4. /etc/ansible/ansible.cfg, the default config file.

First Test

 ansible -i etc/ansible/hosts all -m ping -u vagrant

Set default Python version on Ubuntu

update-alternatives --install /usr/bin/python python /usr/bin/python3.6 1

Working with Playbooks

Create simple playbook

Create file httpd.yaml

---
- hosts: webservers
  remote_user: ansible
  tasks:
  - name: Ensure apache is installed and updated
    yum:
      name: httpd
      state: latest
    become: yes

Run playbook

ansible-playbook -i etc/ansible/hosts  httpd.yaml -kK

Troubleshooting

Allow SSH root login

$ sudo sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config