Docker Community Forums

Share and learn in the Docker community.

Example usage of docker swarm template placeholders

Today I was playing around with mounting cifs shares into a container and figured I’d like to include the namespace to the mounted path. That made me play with the known swarm template variables (https://docs.docker.com/engine/reference/commandline/service_create/#create-services-using-templates).

I found the template command for X_STACK_NAMESPACE usefull in my endover to have stack name specific mounts :slight_smile:

Maybee this information is usefull to others as well. The stack is called ‘test’.

version: '3.7'
services:
  ubuntu:
    image: ubuntu:bionic
    command: sleep 10000
    deploy:
      labels:
        service.label: "this is a label on the service"
    environment:
      X_NODE_ID: '{{.Node.ID}}'
      X_NODE_HOSTNAME: '{{.Node.Hostname}}'
      X_NODE_PLATFROM: '{{.Node.Platform}}'
      X_NODE_PLATFROM_ARCHITECTURE: '{{.Node.Platform.Architecture}}'
      X_NODE_PLATFROM_OS: '{{.Node.Platform.OS}}'
      X_SERVICE_ID: '{{.Service.ID}}'
      X_SERVICE_NAMES: '{{.Service.Name}}'
      X_SERVICE_LABELS: '{{.Service.Labels}}'
      X_SERVICE_LABEL_STACK_NAMESPACE: '{{index .Service.Labels "com.docker.stack.namespace"}}'
      X_SERVICE_LABEL_STACK_IMAGE: '{{index .Service.Labels "com.docker.stack.image"}}'
      X_SERVICE_LABEL_CUSTOM: '{{index .Service.Labels "service.label"}}'
      X_TASK_ID: '{{.Task.ID}}'
      X_TASK_NAME: '{{.Task.Name}}'
      X_TASK_SLOT: '{{.Task.Slot}}'

The template variables need to be quoted (either single or double quote). I used single quotes in general to be able to use the double quotes to access the keys of the map returned by .Service.Labels.

Resulting env variables inside the container:

X_NODE_HOSTNAME=docker2
X_NODE_ID=o53jektysbnzxptwny1b7eurq
X_NODE_PLATFROM='{x86_64 linux}'
X_NODE_PLATFROM_ARCHITECTURE=x86_64
X_NODE_PLATFROM_OS=linux
X_SERVICE_ID=jjmbj2dxlfjopazfom07gv5gr
X_SERVICE_LABELS='map[com.docker.stack.image:ubuntu:bionic com.docker.stack.namespace:test service.label:this is a label on the service]'
X_SERVICE_LABEL_CUSTOM='this is a label on the service'
X_SERVICE_LABEL_STACK_IMAGE=ubuntu:bionic
X_SERVICE_LABEL_STACK_NAMESPACE=test
X_SERVICE_NAMES=test_ubuntu
X_TASK_ID=q5efpqrexn3h3zzoviy5o9wjc
X_TASK_NAME=test_ubuntu.1.q5efpqrexn3h3zzoviy5o9wjc
X_TASK_SLOT=1

Now I am curious if there are any undocummented template variables…
uupdate: I think i found all :slight_smile:

3 Likes