Pages

Tuesday, 3 December 2019

EX294: Building lab environment with vagrant

0. Basic Idea

Although you can test ansible on the localhost for most of the modules, working with multiple manages nodes is far more practical and useful.

Even though EX294 focuses on RHEL8, in a real production environment, RHEL7 is still running everywhere. Both CentOS 8 and CentOS 7 are needed as managed nodes in our Lab.

Vagrant creates VMs much faster than doing it manually on virt-manager. On my own laptop, it took about 2 minutes to create and bring up 4 nodes.

As a result, you can have a completely fresh EX294 lab env within minutes.

1. folder layout

$LABDIR/
   Vagrantfile # virtual machines configuration 
   playbook.yml# provisoning playbook
   ansible.cfg # local ansible configuration
   hosts       # local inventory file

2. Vagrantfile

$ cat Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|

  # use the offical box from CentOS.org
  config.vm.box = "centos/8"

  # all vms trust ~/.vagrant.d/insecure_private_key
  config.ssh.insert_key = false

  config.vm.synced_folder ".", "/vagrant_data", disabled: true

  config.vm.provider "libvirt" do |kvm|
      kvm.memory = "1024"
  end

  # define a VM
  config.vm.define "app1" do |app|
      app.vm.hostname = "app1"
      app.vm.network "private_network", ip: "192.168.66.111"
  end

  # define a VM
  config.vm.define "app2" do |app|
      app.vm.hostname = "app2"
      app.vm.network "private_network", ip: "192.168.66.112"
  end

  # define a VM
  config.vm.define "app3" do |app|
      app.vm.hostname = "app3"
      app.vm.network "private_network", ip: "192.168.66.113"
  end

  # define another VM
  config.vm.define "app4" do |app|
      app.vm.box = "centos/7"
      app.vm.hostname = "app4"
      app.vm.network "private_network", ip: "192.168.66.114"
  end

  config.vm.provision "ansible" do |ansible|
      ansible.playbook = "playbook.yml"
  end
end

3. playbook.yml

$ cat playbook.yml
---
- hosts: all
  become: yes
  tasks:
      - name: Ensure chrony is installed
        yum: name=chrony state=present

      - name: Ensure chronyd is running
        service: name=chronyd state=started enabled=yes

4. hosts


$ cat hosts
[app]
app1 ansible_host=192.168.66.111
app2 ansible_host=192.168.66.112
app3 ansible_host=192.168.66.113
app4 ansible_host=192.168.66.114

[all:vars]
ansible_user=vagrant
ansible_ssh_private_key_file=~/.vagrant.d/insecure_private_key

5. ansible.cfg

$ cat ansible.cfg
[defaults]
inventory=./hosts
host_key_checking = False

6. Test the lab env

$ cd $LABDIR
$ vagrant up
$ ansible all -a 'cat /etc/redhat-release'
app4 | CHANGED | rc=0 >>
CentOS Linux release 7.6.1810 (Core)

app2 | CHANGED | rc=0 >>
CentOS Linux release 8.0.1905 (Core)

app1 | CHANGED | rc=0 >>
CentOS Linux release 8.0.1905 (Core)

app3 | CHANGED | rc=0 >>
CentOS Linux release 8.0.1905 (Core)



No comments:

Post a Comment