terraform-provider-docker/docs/resources/service.md

26 KiB

page_title subcategory description
Resource docker_service - terraform-provider-docker This resource manages the lifecycle of a Docker service. By default, the creation, update and delete of services are detached. With the Converge Config the behavior of the docker cli is imitated to guarantee tha for example, all tasks of a service are running or successfully updated or to inform terraform that a service could no be updated and was successfully rolled back.

Resource (docker_service)

This resource manages the lifecycle of a Docker service. By default, the creation, update and delete of services are detached. With the Converge Config the behavior of the docker cli is imitated to guarantee tha for example, all tasks of a service are running or successfully updated or to inform terraform that a service could no be updated and was successfully rolled back.

Example Usage

Basic

The following configuration starts a Docker Service with

  • the given image,
  • 1 replica
  • exposes the port 8080 in vip mode to the host machine
  • moreover, uses the container runtime
resource "docker_service" "foo" {
  name = "foo-service"

  task_spec {
    container_spec {
      image = "repo.mycompany.com:8080/foo-service:v1"
    }
  }

  endpoint_spec {
    ports {
      target_port = "8080"
    }
  }
}

The following command is the equivalent:

#!/bin/bash
docker service create -d -p 8080 --name foo-service repo.mycompany.com:8080/foo-service:v1

Basic with Datasource

Alternatively, if the image is already present on the Docker Host and not managed by terraform, you can also use the docker_image datasource:

data "docker_image" "foo" {
  name = "repo.mycompany.com:8080/foo-service:v1"
}

resource "docker_service" "foo" {
  name = "foo-service"

  task_spec {
    container_spec {
      image = data.docker_image.foo.repo_digest
    }
  }

  endpoint_spec {
    ports {
      target_port = "8080"
    }
  }
}

Advanced

The following configuration shows the full capabilities of a Docker Service, with a volume, config, secret and network

resource "docker_volume" "test_volume" {
  name = "tftest-volume"
}

resource "docker_volume" "test_volume_2" {
  name = "tftest-volume2"
}

resource "docker_config" "service_config" {
  name = "tftest-full-myconfig"
  data = "ewogICJwcmVmaXgiOiAiMTIzIgp9"
}

resource "docker_secret" "service_secret" {
  name = "tftest-mysecret"
  data = "ewogICJrZXkiOiAiUVdFUlRZIgp9"
}

resource "docker_network" "test_network" {
  name   = "tftest-network"
  driver = "overlay"
}

resource "docker_service" "foo" {
  name = "tftest-service-basic"

  task_spec {
    container_spec {
      image = "repo.mycompany.com:8080/foo-service:v1"

      labels {
        label = "foo.bar"
        value = "baz"
      }

      command  = ["ls"]
      args     = ["-las"]
      hostname = "my-fancy-service"

      env = {
        MYFOO = "BAR"
      }

      dir    = "/root"
      user   = "root"
      groups = ["docker", "foogroup"]

      privileges {
        se_linux_context {
          disable = true
          user    = "user-label"
          role    = "role-label"
          type    = "type-label"
          level   = "level-label"
        }
      }

      read_only = true

      mounts {
        target    = "/mount/test"
        source    = docker_volume.test_volume.name
        type      = "bind"
        read_only = true

        bind_options {
          propagation = "rprivate"
        }
      }

      mounts {
        target    = "/mount/test2"
        source    = docker_volume.test_volume_2.name
        type      = "volume"
        read_only = true

        volume_options {
          no_copy = true
          labels {
            label = "foo"
            value = "bar"
          }
          driver_name = "random-driver"
          driver_options = {
            op1 = "val1"
          }
        }
      }

      stop_signal       = "SIGTERM"
      stop_grace_period = "10s"

      healthcheck {
        test     = ["CMD", "curl", "-f", "http://localhost:8080/health"]
        interval = "5s"
        timeout  = "2s"
        retries  = 4
      }

      hosts {
        host = "testhost"
        ip   = "10.0.1.0"
      }

      dns_config {
        nameservers = ["8.8.8.8"]
        search      = ["example.org"]
        options     = ["timeout:3"]
      }

      secrets {
        secret_id   = docker_secret.service_secret.id
        secret_name = docker_secret.service_secret.name
        file_name   = "/secrets.json"
        file_uid    = "0"
        file_gid    = "0"
        file_mode   = 0777
      }

      secrets {
        # another secret
      }

      configs {
        config_id   = docker_config.service_config.id
        config_name = docker_config.service_config.name
        file_name   = "/configs.json"
      }

      configs {
        # another config
      }
    }

    resources {
      limits {
        nano_cpus    = 1000000
        memory_bytes = 536870912
      }

      reservation {
        nano_cpus    = 1000000
        memory_bytes = 536870912

        generic_resources {
          named_resources_spec = [
            "GPU=UUID1",
          ]

          discrete_resources_spec = [
            "SSD=3",
          ]
        }
      }
    }

    restart_policy = {
      condition    = "on-failure"
      delay        = "3s"
      max_attempts = 4
      window       = "10s"
    }

    placement {
      constraints = [
        "node.role==manager",
      ]

      prefs = [
        "spread=node.role.manager",
      ]

      max_replicas = 1
    }

    force_update = 0
    runtime      = "container"
    networks     = [docker_network.test_network.id]

    log_driver {
      name = "json-file"

      options = {
        max-size = "10m"
        max-file = "3"
      }
    }
  }

  mode {
    replicated {
      replicas = 2
    }
  }

  update_config {
    parallelism       = 2
    delay             = "10s"
    failure_action    = "pause"
    monitor           = "5s"
    max_failure_ratio = "0.1"
    order             = "start-first"
  }

  rollback_config {
    parallelism       = 2
    delay             = "5ms"
    failure_action    = "pause"
    monitor           = "10h"
    max_failure_ratio = "0.9"
    order             = "stop-first"
  }

  endpoint_spec {
    mode = "vip"

    ports {
      name           = "random"
      protocol       = "tcp"
      target_port    = "8080"
      published_port = "8080"
      publish_mode   = "ingress"
    }

    ports {
      # another port
    }
  }
}

Schema

Required

  • name (String) Name of the service
  • task_spec (Block List, Min: 1, Max: 1) User modifiable task configuration (see below for nested schema)

Optional

  • auth (Block List, Max: 1) Configuration for the authentication for pulling the images of the service (see below for nested schema)
  • converge_config (Block List, Max: 1) A configuration to ensure that a service converges aka reaches the desired that of all task up and running (see below for nested schema)
  • endpoint_spec (Block List, Max: 1) Properties that can be configured to access and load balance a service (see below for nested schema)
  • labels (Block Set) User-defined key/value metadata (see below for nested schema)
  • mode (Block List, Max: 1) Scheduling mode for the service (see below for nested schema)
  • rollback_config (Block List, Max: 1) Specification for the rollback strategy of the service (see below for nested schema)
  • update_config (Block List, Max: 1) Specification for the update strategy of the service (see below for nested schema)

Read-Only

  • id (String) The ID of this resource.

Nested Schema for task_spec

Required:

Optional:

  • force_update (Number) A counter that triggers an update even if no relevant parameters have been changed. See the spec.
  • log_driver (Block List, Max: 1) Specifies the log driver to use for tasks created from this spec. If not present, the default one for the swarm will be used, finally falling back to the engine default if not specified (see below for nested schema)
  • networks (Set of String) Ids of the networks in which the container will be put in
  • placement (Block List, Max: 1) The placement preferences (see below for nested schema)
  • resources (Block List, Max: 1) Resource requirements which apply to each individual container created as part of the service (see below for nested schema)
  • restart_policy (Block List, Max: 1) Specification for the restart policy which applies to containers created as part of this service. (see below for nested schema)
  • runtime (String) Runtime is the type of runtime specified for the task executor. See the types.

Nested Schema for task_spec.container_spec

Required:

  • image (String) The image name to use for the containers of the service, like nginx:1.17.6. Also use the data-source or resource of docker_image with the repo_digest or docker_registry_image with the name attribute for this, as shown in the examples.

Optional:

  • args (List of String) Arguments to the command
  • command (List of String) The command/entrypoint to be run in the image. According to the docker cli the override of the entrypoint is also passed to the command property and there is no entrypoint attribute in the ContainerSpec of the service.
  • configs (Block Set) References to zero or more configs that will be exposed to the service (see below for nested schema)
  • dir (String) The working directory for commands to run in
  • dns_config (Block List, Max: 1) Specification for DNS related configurations in resolver configuration file (resolv.conf) (see below for nested schema)
  • env (Map of String) A list of environment variables in the form VAR="value"
  • groups (List of String) A list of additional groups that the container process will run as
  • healthcheck (Block List, Max: 1) A test to perform to check that the container is healthy (see below for nested schema)
  • hostname (String) The hostname to use for the container, as a valid RFC 1123 hostname
  • hosts (Block Set) A list of hostname/IP mappings to add to the container's hosts file (see below for nested schema)
  • isolation (String) Isolation technology of the containers running the service. (Windows only). Defaults to default.
  • labels (Block Set) User-defined key/value metadata (see below for nested schema)
  • mounts (Block Set) Specification for mounts to be added to containers created as part of the service (see below for nested schema)
  • privileges (Block List, Max: 1) Security options for the container (see below for nested schema)
  • read_only (Boolean) Mount the container's root filesystem as read only
  • secrets (Block Set) References to zero or more secrets that will be exposed to the service (see below for nested schema)
  • stop_grace_period (String) Amount of time to wait for the container to terminate before forcefully removing it (ms|s|m|h). If not specified or '0s' the destroy will not check if all tasks/containers of the service terminate.
  • stop_signal (String) Signal to stop the container
  • sysctl (Map of String) Sysctls config (Linux only)
  • user (String) The user inside the container

Nested Schema for task_spec.container_spec.configs

Required:

  • config_id (String) ID of the specific config that we're referencing
  • file_name (String) Represents the final filename in the filesystem

Optional:

  • config_name (String) Name of the config that this references, but this is just provided for lookup/display purposes. The config in the reference will be identified by its ID
  • file_gid (String) Represents the file GID. Defaults to 0.
  • file_mode (Number) Represents represents the FileMode of the file. Defaults to 0o444.
  • file_uid (String) Represents the file UID. Defaults to 0.

Nested Schema for task_spec.container_spec.dns_config

Required:

  • nameservers (List of String) The IP addresses of the name servers

Optional:

  • options (List of String) A list of internal resolver variables to be modified (e.g., debug, ndots:3, etc.)
  • search (List of String) A search list for host-name lookup

Nested Schema for task_spec.container_spec.healthcheck

Required:

  • test (List of String) The test to perform as list

Optional:

  • interval (String) Time between running the check (ms|s|m|h). Defaults to 0s.
  • retries (Number) Consecutive failures needed to report unhealthy. Defaults to 0
  • start_period (String) Start period for the container to initialize before counting retries towards unstable (ms|s|m|h). Defaults to 0s.
  • timeout (String) Maximum time to allow one check to run (ms|s|m|h). Defaults to 0s.

Nested Schema for task_spec.container_spec.hosts

Required:

  • host (String) The name of the host
  • ip (String) The ip of the host

Nested Schema for task_spec.container_spec.labels

Required:

  • label (String) Name of the label
  • value (String) Value of the label

Nested Schema for task_spec.container_spec.mounts

Required:

  • target (String) Container path
  • type (String) The mount type

Optional:

  • bind_options (Block List, Max: 1) Optional configuration for the bind type (see below for nested schema)
  • read_only (Boolean) Whether the mount should be read-only
  • source (String) Mount source (e.g. a volume name, a host path)
  • tmpfs_options (Block List, Max: 1) Optional configuration for the tmpfs type (see below for nested schema)
  • volume_options (Block List, Max: 1) Optional configuration for the volume type (see below for nested schema)

Nested Schema for task_spec.container_spec.mounts.bind_options

Optional:

  • propagation (String) Bind propagation refers to whether or not mounts created within a given bind-mount or named volume can be propagated to replicas of that mount. See the docs for details. Defaults to rprivate

Nested Schema for task_spec.container_spec.mounts.tmpfs_options

Optional:

  • mode (Number) The permission mode for the tmpfs mount in an integer
  • size_bytes (Number) The size for the tmpfs mount in bytes

Nested Schema for task_spec.container_spec.mounts.volume_options

Optional:

  • driver_name (String) Name of the driver to use to create the volume
  • driver_options (Map of String) key/value map of driver specific options
  • labels (Block Set) User-defined key/value metadata (see below for nested schema)
  • no_copy (Boolean) Populate volume with data from the target

Nested Schema for task_spec.container_spec.mounts.volume_options.labels

Required:

  • label (String) Name of the label
  • value (String) Value of the label

Nested Schema for task_spec.container_spec.privileges

Optional:

Nested Schema for task_spec.container_spec.privileges.credential_spec

Optional:

  • file (String) Load credential spec from this file
  • registry (String) Load credential spec from this value in the Windows registry

Nested Schema for task_spec.container_spec.privileges.se_linux_context

Optional:

  • disable (Boolean) Disable SELinux
  • level (String) SELinux level label
  • role (String) SELinux role label
  • type (String) SELinux type label
  • user (String) SELinux user label

Nested Schema for task_spec.container_spec.secrets

Required:

  • file_name (String) Represents the final filename in the filesystem
  • secret_id (String) ID of the specific secret that we're referencing

Optional:

  • file_gid (String) Represents the file GID. Defaults to 0
  • file_mode (Number) Represents represents the FileMode of the file. Defaults to 0o444
  • file_uid (String) Represents the file UID. Defaults to 0
  • secret_name (String) Name of the secret that this references, but this is just provided for lookup/display purposes. The config in the reference will be identified by its ID

Nested Schema for task_spec.log_driver

Required:

  • name (String) The logging driver to use

Optional:

  • options (Map of String) The options for the logging driver

Nested Schema for task_spec.placement

Optional:

  • constraints (Set of String) An array of constraints. e.g.: node.role==manager
  • max_replicas (Number) Maximum number of replicas for per node (default value is 0, which is unlimited)
  • platforms (Block Set) Platforms stores all the platforms that the service's image can run on (see below for nested schema)
  • prefs (Set of String) Preferences provide a way to make the scheduler aware of factors such as topology. They are provided in order from highest to lowest precedence, e.g.: spread=node.role.manager

Nested Schema for task_spec.placement.platforms

Required:

  • architecture (String) The architecture, e.g. amd64
  • os (String) The operation system, e.g. linux

Nested Schema for task_spec.resources

Optional:

  • limits (Block List, Max: 1) Describes the resources which can be advertised by a node and requested by a task (see below for nested schema)
  • reservation (Block List, Max: 1) An object describing the resources which can be advertised by a node and requested by a task (see below for nested schema)

Nested Schema for task_spec.resources.limits

Optional:

  • memory_bytes (Number) The amounf of memory in bytes the container allocates
  • nano_cpus (Number) CPU shares in units of 1/1e9 (or 10^-9) of the CPU. Should be at least 1000000

Nested Schema for task_spec.resources.reservation

Optional:

  • generic_resources (Block List, Max: 1) User-defined resources can be either Integer resources (e.g, SSD=3) or String resources (e.g, GPU=UUID1) (see below for nested schema)
  • memory_bytes (Number) The amounf of memory in bytes the container allocates
  • nano_cpus (Number) CPU shares in units of 1/1e9 (or 10^-9) of the CPU. Should be at least 1000000

Nested Schema for task_spec.resources.reservation.generic_resources

Optional:

  • discrete_resources_spec (Set of String) The Integer resources
  • named_resources_spec (Set of String) The String resources

Nested Schema for task_spec.restart_policy

Optional:

  • condition (String) Condition for restart
  • delay (String) Delay between restart attempts (ms|s|m|h)
  • max_attempts (Number) Maximum attempts to restart a given container before giving up (default value is 0, which is ignored)
  • window (String) The time window used to evaluate the restart policy (default value is 0, which is unbounded) (ms|s|m|h)

Nested Schema for auth

Required:

  • server_address (String) The address of the server for the authentication

Optional:

  • password (String, Sensitive) The password
  • username (String) The username

Nested Schema for converge_config

Optional:

  • delay (String) The interval to check if the desired state is reached (ms|s). Defaults to 7s.
  • timeout (String) The timeout of the service to reach the desired state (s|m). Defaults to 3m

Nested Schema for endpoint_spec

Optional:

  • mode (String) The mode of resolution to use for internal load balancing between tasks
  • ports (Block List) List of exposed ports that this service is accessible on from the outside. Ports can only be provided if 'vip' resolution mode is used (see below for nested schema)

Nested Schema for endpoint_spec.ports

Required:

  • target_port (Number) The port inside the container

Optional:

  • name (String) A random name for the port
  • protocol (String) Rrepresents the protocol of a port: tcp, udp or sctp. Defaults to tcp.
  • publish_mode (String) Represents the mode in which the port is to be published: 'ingress' or 'host'. Defaults to ingress.
  • published_port (Number) The port on the swarm hosts

Nested Schema for labels

Required:

  • label (String) Name of the label
  • value (String) Value of the label

Nested Schema for mode

Optional:

  • global (Boolean) The global service mode. Defaults to false
  • replicated (Block List, Max: 1) The replicated service mode (see below for nested schema)

Nested Schema for mode.replicated

Optional:

  • replicas (Number) The amount of replicas of the service. Defaults to 1

Nested Schema for rollback_config

Optional:

  • delay (String) Delay between task rollbacks (ns|us|ms|s|m|h). Defaults to 0s.
  • failure_action (String) Action on rollback failure: pause | continue. Defaults to pause.
  • max_failure_ratio (String) Failure rate to tolerate during a rollback. Defaults to 0.0.
  • monitor (String) Duration after each task rollback to monitor for failure (ns|us|ms|s|m|h). Defaults to 5s.
  • order (String) Rollback order: either 'stop-first' or 'start-first'. Defaults to stop-first.
  • parallelism (Number) Maximum number of tasks to be rollbacked in one iteration. Defaults to 1

Nested Schema for update_config

Optional:

  • delay (String) Delay between task updates (ns|us|ms|s|m|h). Defaults to 0s.
  • failure_action (String) Action on update failure: pause, continue or rollback. Defaults to pause.
  • max_failure_ratio (String) Failure rate to tolerate during an update. Defaults to 0.0.
  • monitor (String) Duration after each task update to monitor for failure (ns|us|ms|s|m|h). Defaults to 5s.
  • order (String) Update order: either 'stop-first' or 'start-first'. Defaults to stop-first.
  • parallelism (Number) Maximum number of tasks to be updated in one iteration. Defaults to 1

Import

Import is supported using the following syntax by providing the id:

#!/bin/bash
terraform import docker_service.foo id

Example

Assuming you created a service as follows

#!/bin/bash
docker service create --name foo -p 8080:80 nginx
# prints th ID
4pcphbxkfn2rffhbhe6czytgi

you provide the definition for the resource as follows

resource "docker_service" "foo" {
  name = "foo"

  task_spec {
    container_spec {
      image = "nginx"
    }
  }

  endpoint_spec {
    ports {
      target_port    = "80"
      published_port = "8080"

    }
  }
}

then the import command is as follows

#!/bin/bash
terraform import docker_service.foo 4pcphbxkfn2rffhbhe6czytgi