Use Ansible with Python3 on Ubuntu 16.04

DigitalOcean's Ubuntu 16.04 ships with Python3 by default, something Ansible can't work with without some configuration.

Allow me to try and show you how I got it working.

First things first. Create a new Droplet via DigitalOcean, name it whatever you want but make sure you add your local SSH key. I use a $5 Ubuntu 16.04 server, which will suffice.

When DigitalOcean is done provisioning your server, ssh into it via your terminal.

ssh root@server-ip  

When you're logged in, create a new SSH key which we'll use for the servers we want managed by Ansible.

ssh-keygen -t rsa -b 4096 -C "your@email.tld"  
cat ~/.ssh/id_rsa.pub  

Copy the content and open DigitalOcean's security settings and add a new SSH key. Give it a descriptive name and paste your clipboard's content into the text area.

When that's all said and done, it's time to install Ansible on your new server.

Install Ansible

Open up your terminal, make sure you're ssh'ed in, and follow along. Fire the following commands one by one, and when it's done you'll have the latest version of Ansible installed and ready to go.

sudo apt-get install -y software-properties-common

sudo add-apt-repository -y ppa:ansible/ansible

sudo apt-get update

sudo apt-get install -y ansible  

Check Ansible's version:

which ansible

# /usr/bin/ansible
ansible --version

# ansible 2.3.0.0
#  config file = /etc/ansible/ansible.cfg
#  configured module search path = Default w/o overrides
#  python version = 2.7.12 (default, Nov 19 2016, 06:48:10) [GCC 5.4.0 20160609]

At the time of writing this is the latest version.

As you can see, Ansible 2.3.0.0 ships with Python 2.7.12 by default. DigitalOcean's Ubuntu 16.04 ships with Python3 by default. We need to tell Ansible to use Python3 instead. More on that later.

Droplets

At this point it's a good idea to create 2 or 3 new droplets via DigitalOcean (Ubuntu 16.04). These droplets will be managed via Ansible. Make sure to add the main droplet's SSH key alongside your personal key.

Hosts

Make a backup of your hosts file in /etc/ansible and open up a new hosts file.

cd /etc/ansible

mv hosts hosts.backup

vim hosts  

Make a group of IP addresses you want Ansible to manage. These IP addresses come from the droplets we created earlier.

[web]
xxx.xxx.xxx.xxx  
xxx.xxx.xxx.xxx  
xxx.xxx.xxx.xxx  

Run your first command

ansible all -m ping -u root  

You'll have to accept the authenticity of each server. You'll notice Ansible returns an error on each attempt. This is because it can't find Python.

Use Python3

vim hosts  

Edit the file so it looks similar to the following:

[web]
xxx.xxx.xxx.xxx  
xxx.xxx.xxx.xxx  
xxx.xxx.xxx.xxx

[web:vars]
ansible_python_interpreter=/usr/bin/python3  

Run your first command. Again.

ansible all -m ping -u root  

This time the response should be successful.

Conclusion

That's it. You should now be able to manage your Ubuntu 16.04 droplets with Ansible 2.3.0.0. Happy automating!