Testing Ansible roles against ec2 instances with molecule

Hey, so lately I’ve been trying to get more familiar with Ansible. This weekend I decided to test out molecule with it’s ec2 driver. Docker containers are cool and all but they are limited, systemd is a pain for example. Also, the ec2 driver gives you the possibility to use your AMIs and choose the instance type, recreating even closer your production environment. All the solutions I found online seemed quite outdated, some of the molecule commands didn’t event work. So I decided to write down step by step what I did to start testing roles against ec2 machines.

First lets create our virtualenv and install the needed dependencies there, to reduce clutter.

# requirements.txt
# creating our virtualenv
virtualenv -p python3 venv
source venv/bin/activate
pip install -r requirements.txt
# you can run pip freeze to check what you've installed

# let's init our molecule scenario
molecule init role test --driver-name ec2

By now we have installed all that we’ll need, and created our scenario with molecule. You can get into the test folder and check what molecule has already setup for us. Now, let’s get this baby rolling.

You will need to created a subnet “by hand”, in your AWS account, where your instances will spawn. Edit your molecule.yml inside the molecule/default folder, and define the platforms key. Here you could add a list of different instances to test the role against.

We will simply use a t2.micro instance, so that we keep things simple and most importantly free-tier eligible (I’m cheap).

- name: test-instance
  image: ami-0fc61db8544a617ed # standard linux AMI
  instance_type: t2.micro
  vpc_subnet_id: ${SUBNET_ID}
# provide your subnet-id and the region
export SUBNET_ID=subnet-99894324fsddasd
export EC2_REGION=us-east-1

You can provide your AWS credentials by either running aws configure (you’ll need to have the awscli installed to do this), or via environment variables. Pick what suits you best. By now, we can now try to run molecule, with molecule test, and you’ll get both errors and deprecation warnings, lovely right? Let’s just close our eyes to how disengaging this is and fix it.

In my case molecule was able to spin-up a ec2 instance, but later on wasn’t able to connect to it via ssh. (Permission denied (publickey, gssapi-keyex, gssapi-with-mic)). Gosh… Edit your create.yml, change the ssh_user from the default value ubuntu, to ec2-user, also change ec2_ami_facts by ec2_ami_info. Next, to remove the warning playbook.yml was deprecated, by renaming your playbook.yml to converge.yml. Now run molecule test again, and you should be all setup.

Hope this helps.

· ec2, ansible, molecule