Ansible. Test With Vagrant on MacOS

Table of Contents

Prepare

Before start, we need to prepare our local environment.

Install required packages

For install required packages run:

brew install --cask vagrant
brew install virtualbox qemu
vagrant plugin install vagrant-libvirt

Add needed vagrant box. For example, it was a Debian 12:

vagrant box add generic/debian12 --provider virtualbox

Install requeired python packages

First, create a virtual env:

python3 -m venv .ansible

Activate a virtual env

source .ansible/bin/activate

Install python packages

pip3 install ansible ansible-lint yamllint python-vagrant molecule rich 'molecule-plugins[vagrant]'

Molecule scenario

Now, we need to create a new ansible role, add molecule scenario and add some useful staff.

Init role

Init new roles with ansible-galaxy if you want to create a new role:

ansible-galaxy role init my_role

Now, add molecule scenario to exist role:

molecule init scenario --driver-name vagrant

Update molecule files

Update molecule.yaml:

dependency:
  name: galaxy
driver:
  name: vagrant
  provider:
    name: virtualbox
    options:
      memory: 512
      cpus: 1
lint: |
  set -e
  yamllint .
  ansible-lint .  
platforms:
  - name: debian-12
    box: generic/debian12
provisioner:
  name: ansible
  lint:
    name: ansible-lint
verifier:
  name: ansible

Practice part

Now, lets try to make some example. Full example I put on GitHub.

Create example role

First, create an ansible role with command:

ansible-galaxy role init example-ansible-vagrant-test

step into directory and init new molecule role:

molecule init scenario --driver-name vagrant

Perfect! Now we will add task for install nginx into tasks/main.yaml:

---
- name: Install nginx
  ansible.builtin.package: 
    name: nginx
    state: latest
    update_cache: true

remove not nessary files:

  • molecule/default/create.ymy
  • molecule/default/destroy.yml;

update molecule/default/converge.yml:

---
- name: Converge
  hosts: all
  become: true
  pre_tasks:
    - name: Update apt cache
      ansible.builtin.apt:
        update_cache: true
        cache_valid_time: 600
      changed_when: false
      when: ansible_pkg_mgr == "apt"
  tasks:
  - name: "Include role"
    ansible.builtin.include_role:
      name: myrole.example_ansible_vagrant_test

Add molecule verify staff (molecule/default/verify.yml):

---
- name: Verify
  hosts: all
  become: true
  tasks:
    - name: Get nginx package status
      ansible.builtin.package:
        name: nginx
        state: latest
      register: package_facts

    - name: Check nginx package status
      ansible.builtin.assert:
        that: "false == package_facts['changed']"

Run test

Let`s test role with command:

molecule test

That`s all! Perfect!