Run an Ansible playbook in your Docker build

Drew Sears edited this page Feb 28, 2017 · 1 revision

Start your build:

dsears@ubuntu:~$ mkdir ansibletest
dsears@ubuntu:~$ cd ansibletest
dsears@ubuntu:~/ansibletest$ nano Dockerfile

Dockerfile:

FROM centos:7
COPY playbook /playbook
RUN yum -y install epel-release && \
    yum -y install gcc openssl-devel python-devel python-pip && \
    pip install ansible && \
    ansible-playbook -i "localhost," -c local /playbook/playbook.yml && \
    rm -rf /playbook

Here we copy the playbook directory, install Ansible, run the playbook locally, and clean up.

Finally, create your playbook:

dsears@ubuntu:~/ansibletest$ mkdir playbook
dsears@ubuntu:~/ansibletest$ nano playbook/playbook.yml

playbook.yml:

---
- hosts: all
  tasks:
  
  - name: Install yum packages
    yum: name={{item}} state=installed
    with_items:
      - httpd
      - php

Build your image:

docker build -t ansibletest .

Run it:

docker run -it -v `pwd`/playbook:/playbook ansibletest bash

The original /playbook was statically copied from the host and then deleted. Now we've re-mounted it from the host's working directory, so you can edit and re-run your playbook inside the container and your changes will persist on the host.