/ linux

Using Ansible to Set Up Docker

Ok so yesterday I wrote about getting Ansible installed and configured on a development machine. I happened to be using Fedora, but I know that the steps will work on Arch, openSuse, and Debian (with a few minor changes). I would really like to get a similar setup that works reliable on MacOS and Windows. Maybe one day...

Today I created a new playbook in that environment, but for getting Docker set up and running.

Here is the playbook, ~/ansible-develop/docker.yml:

---
- name: Setup Docker
  hosts: localhost
  become: True
  tasks:
    - name: install docker packages
      package: name={{ item }}
      with_items:
        - docker
        - docker-compose

    - name: create the docker group
      group: name=docker
             state=present

    - name: add user to docker group
      user: name={{ username }}
            groups=docker
            append=yes

    - name: enable docker service
      service: name=docker
               enabled=yes
               state=started

You can't run this yet because {{ username }} is not defined. I don't want to have to change this file for ever user that runs it so I am putting some variables in a "host_vars" folder in my ansible project. This is very simple. Create a new folder:

mkdir ~/ansible-develop/host_vars

and create a yml file, ~/ansible-develop/host_vars/localhost.yml:

username: brosas

Of course, you need to put your username in the file instead of brosas.

Ansible automatically looks in any host_vars directories within the playbook location (or at a system level) and associates given variables with any playbooks run on a host with the same name. Since we are only running ansible on localhost we can put all of our variables in host_vars/localhost.yml. You can imagine how this would be useful if you ran ansible playbooks on many different hosts.

Now this should work:

cd ~/ansible-develop
ansible-playbook -K docker.yml

Note: You will have to log out and back in again for the group change to take effect. Until then your user will not yet be able to run docker commands without sudo

Benjamin Rosas

Benjamin Rosas

I am a constantly curious programmer with a background in science. I enjoy open-source software, programming languages, web development and server administration, along with music, travel and snark.

Read More
Using Ansible to Set Up Docker
Share this