Testing Ansible playbooks with Vagrant

By: on May 15, 2013

One of the projects here at LShift uses ansible to configure its EC2 machines. I needed to refactor the playbook in a minor way. But of course “refactor” doesn’t just mean “change the code”. It means “change the code (presumably for the better) while preserving behaviour“. I really didn’t want to check the change by running the playbook against a production deployment! So what to do?

Handily, vagrant supports ansible, so I can run a playbook from scratch simply by saying vagrant up. I had to smooth out some wrinkles: EC2 Ubuntu machine have an ‘ubuntu’ user, while Vagrant Ubuntu boxes have a ‘vagrant’ user. EC2 Ubuntu machines have a /dev/xvdb device, Vagrant boxes don’t.

And thus, this little shim playbook came to be:

- hosts: target
: vagrant
: True

    - name
: Create fake block device for /dev/xvdb, simulating ephemeral storage
: file src=/dev/ram1 path=/dev/xvdb mode=0660 owner=root group=disk state=link

    - name
: Create fake block device for /dev/xvdf, simulating an EBS volume
: file src=/dev/ram2 path=/dev/xvdf mode=0660 owner=root group=disk state=link

    # As yet there's no ansible module for making a file system [1]. We try, and if mkfs fails
    # we presume it's because there's already a file system on that device, and eat the
    # failure.
    # [1] https://github.com/ansible/ansible/pull/2776
    - name
: Put a filesystem on block devices to emulate EBS volumes
: shell mkfs -t ext4 /dev/$item ; true
       - xvdb
        - xvdf

    - name
: Create the ubuntu user
: user name=ubuntu state=present groups=admin

    - name
: Make the ubuntu user an sudoer
: lineinfile dest=/etc/sudoers regexp="^ubuntu" line="ubuntu ALL=(ALL) ALL" state=present

    - name
: Make /home/ubuntu/.ssh/
: file path=/home/ubuntu/.ssh/ state=directory

    # This is not as lame as it looks. The real playbook will run as the 'ubuntu' user,
    # and this is a test environment.
    - name
: Copy the ansible key from the vagrant user to the ubuntu user
: shell cp /home/vagrant/.ssh/authorized_keys /home/ubuntu/.ssh/authorized_keys creates=/home/ubuntu/.ssh/authorized_keys

    - name
: Fix permissions of same
: file path=/home/ubuntu/.ssh/ owner=ubuntu group=ubuntu mode=0600 state=directory
: file path=/home/ubuntu/.ssh/authorized_keys owner=ubuntu group=ubuntu mode=0600 state=file

- include
: therealplaybook.yml

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>