Search code examples
dockeransibleboot2docker

Ansible - Conditionally set volume and tls hostname based on inventory file in docker module


I'm using Ansible to deploy my containers to production. During development, I'd like to have Ansible deploy all containers on my localhost instead of the production servers.

Production servers run on Ubuntu, localhost is OS X with boot2docker.

I have 2 inventory files, production and localhost. My dir structure looks like this:

.
|--inventories
|  |localhost
|  |production
|
|--group_vars
|  |all
|  |localhost
|  |production
|
|--roles
|  |--web
|     |--tasks
         |main.yml
|
|web.yml 

web.yml just defines the host group and assigns the web role.

/roles/web/tasks/main.yml looks like this:

- name: Run web container
  docker:
    name: web
    image: some/image
    state: reloaded
    ...
    tls_hostname: boot2docker
    volumes:
      - "/data/db:/data/db"
    env:
      ...
  tags:
    - ...

I need to set tls_hostname conditionally, only if the localhost inventory was used; likewise, I want to set the volume only if the production inventory file was used.

Very new to Ansible - it seems like I'm not approaching this to right way there's an easier way to do this? I want to avoid creating completely separate tasks to deploy locally; I just need a way to define volume and tls_hostname conditionally (and leave it at default setting otherwise)


Solution

  • As of Ansible 1.8, you can omit variables and module parameters using the default filter with the special omit value. For example,

    - name: Run web container
      docker:
        name: web
        image: some/image
        state: reloaded
        ...
        tls_hostname: "{{ hostname | default('some default value') }}"
        volumes: "{{ volumes | default(omit) }}"
        env:
          ...
      tags:
        - ...