feat/doc generation (#193)

* chore: add tfplugindocs tool

* feat: add tfplugin doc dependency and make target

* chore: apply documentation generation

* docs(contributing): update for documentation generation

* fix: adapt website-lint target to new do folder

* docs(network): update ds descriptions

* docs: add template for index.md

* docs: add network resource generation

* chore(ci): updates paths for website checks

* docs: add plugin data source generation

* docs: add import cmd for network resource

* docs: add plugin resource generation

* feat: outlines remaining resources with example and import cmd

* feat: add descriptions to docs

* chore: add DevSkim ignores and fix capitalized errors

* docs: complete ds registry image

* docs: add container resource generation

* docs: add lables description to missing resources

* docs: remove computed:true from network data

so the list is rendered in the description

* Revert "docs: remove computed:true from network data"

This reverts commit dce9b7a5a2.

* docs: add docker image descriptions to generate the docs

* docs: add docker registry image descriptions to generate the docs

* docs: add docker service descriptions to generate the docs

* docs: add docker volume descriptions to generate the docs

* docs(index): clarifies description

so more docker resources are mentioned

* docs(network): fixes required and read-only attributes

so the ds can only be read by-name

* docs(plugin): clarifies the ds docs attributes

* docs: fix typo registry image ds

* docs(config): clarifies attributes and enhances examples

Provide a long example and import command

* fix(config): make data non-sensitive

Because only secrets data is

* docs(containter): clarifies attributes

and enhances examples with import

* docs(config): fix typo

* docs(image): clarifies attributes and remove import

* docs(network): clarifies attributes and adapts import

* docs(plugin): clarifies attributes and import

* docs(registry_image): clarifies attributes and removes import

* chore(secret): remove typo

* docs(service): clarifies attributes and import

* docs(volume): clarifies attributes and import

* fix: correct md linter rules after doc gen

* docs(volume): regenerated

* docs: add config custom template

* docs: add templates for all resources

* docs(config): templates all sections and examples

for better redability and structure

* docs(config): fix md linter

* docs(container): templates all sections and examples

* docs(image): templates all sections and examples

* docs(image): fix import resource by renaming

* docs(network): templates all sections and examples

* docs(service): templates all sections and examples

* docs(volume): templates all sections and examples

* fix(lint): replace website with doc directory

* fix(ci): link check file extension check

* fix: markdown links

* chore: remove old website folder

* chore: fix website-lint terrafmr dir and pattern

* fix: lint fix target website folder

* fix: website links

* docs(provider): update examples

with templates on auth and certs

* docs(provider): add tf-plugin-docs line

* docs(contributing): split doc generation section

* docs: final brush up for readability and structure

* chore(ci): add website-generation job

to see if files changed and it should run locally again

* chore(ci): remove explicit docker setup

from website lint because it's installed by default
This commit is contained in:
Manuel Vogel 2021-05-21 14:30:56 +02:00 committed by GitHub
parent 96a6a8dbee
commit 6c796e15a5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
122 changed files with 4639 additions and 2645 deletions

View file

@ -10,7 +10,7 @@ on:
pull_request:
paths:
- .github/workflows/website-link.yaml
- website/docs/**
- docs/**
- .markdownlint.yml
jobs:
@ -19,10 +19,10 @@ jobs:
steps:
- uses: actions/checkout@v2
- uses: gaurav-nelson/github-action-markdown-link-check@v1
name: markdown-link-check website/docs/**/*.markdown
name: markdown-link-check docs/**/*.md
with:
use-quiet-mode: 'yes'
use-verbose-mode: 'yes'
config-file: '.markdownlinkcheck.json'
folder-path: 'website/docs'
file-extension: '.markdown'
folder-path: 'docs'
file-extension: '.md'

View file

@ -8,7 +8,7 @@ on:
types: ['opened', 'synchronize']
paths:
- .github/workflows/website-lint.yaml
- website/docs/**
- docs/**
env:
GO_VERSION: "1.16"
@ -16,6 +16,32 @@ env:
DOCKER_CE_VERSION: "5:20.10.5~3-0~ubuntu-focal"
jobs:
website-generation:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: actions/setup-go@v2
with:
go-version: '1.16'
- name: Setup tools
run: make setup
- name: Generate the website
run: make website-generation
- name: Verify Changed files
uses: tj-actions/verify-changed-files@v6.1
id: verify-changed-files
with:
files: |
docs/**/*.md
- name: Display changed files
if: steps.verify-changed-files.outputs.files_changed == 'true'
run: |
echo "Changed files: ${{ steps.verify_changed_files.outputs.changed_files }}"
- name: Fail if files have changed
if: steps.verify-changed-files.outputs.files_changed == 'true'
run: |
echo "Generated website was not up-to-date. Please run 'make website-generation' locally, commit, and push again";
exit 1;
website-lint-spellcheck-tffmt:
runs-on: ubuntu-20.04
steps:
@ -23,25 +49,17 @@ jobs:
- uses: actions/setup-go@v2
with:
go-version: '1.16'
- run: cat /etc/issue
- run: bash scripts/gogetcookie.sh
# locally: docker run -it ubuntu-20.04 bash (https://ubuntu.pkgs.org/20.04/docker-ce-stable-amd64/)
- run: sudo apt-get update
- run: sudo apt-get -y install apt-transport-https ca-certificates curl gnupg-agent software-properties-common
- run: curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
- run: sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
- run: sudo apt-get update
# list available docker versions: apt-cache policy docker-ce
- run: sudo apt-get -y install docker-ce=${DOCKER_CE_VERSION}
- run: docker version
- run: make setup
- run: make website-lint
- name: Setup tools
run: make setup
- name: Lint website
run: make website-lint
markdown-lint:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: avto-dev/markdown-lint@v1
with:
args: 'website/docs'
args: 'docs'
config: '.markdownlint.yml'

3
.gitignore vendored
View file

@ -40,3 +40,6 @@ dist
# testing
testing
testing-mirror/registry.terraform.io/kreuzwerker/docker
# lint error outputs
markdown-link-check-*.txt

View file

@ -2,13 +2,5 @@
"ignorePatterns": [
],
"replacementPatterns": [
{
"pattern": "^/docs/providers/docker/r/(.*).html",
"replacement": "/github/workspace/website/docs/r/$1.html.markdown"
},
{
"pattern": "^/docs/providers/docker/d/(.*).html",
"replacement": "/github/workspace/website/docs/d/$1.html.markdown"
}
]
}

View file

@ -6,17 +6,11 @@ default: true
# Disabled Rules
# https://github.com/DavidAnson/markdownlint/blob/master/doc/Rules.md
MD001: false
MD004: false
MD007: false
MD009: false
MD010: false
MD012: false
MD013: false
MD014: false
MD022: false
MD031: false
MD032: false
MD023: false
MD024: false
MD033: false
MD034: false
MD047: false

View file

@ -68,16 +68,13 @@ TF_LOG=INFO TF_ACC=1 go test -v ./internal/provider -run ^TestAccDockerImage_dat
make testacc_cleanup
```
Furthermore, we recommened running the linters for the code and the documentation:
Furthermore, run the linters for the code:
```sh
# install all the dependencies
make setup
# lint the go code
make golangci-lint
make website-link-check
make website-lint
# you can also use this command to fix most errors automatically
make website-lint-fix
```
In case you need to run the GitHub actions setup locally in a docker container and run the tests there,
@ -89,6 +86,27 @@ make testacc_setup
TF_LOG=DEBUG TF_ACC=1 go test -v ./internal/provider -run ^TestAccDockerContainer_nostart$
```
### Update the documentation
Furthermore, run the generation and linters for the documentation:
```sh
# install all the dependencies
make setup
# generate or update the documentation
make website-generation
# lint the documentation
make website-link-check
make website-lint
# you can also use this command to fix most errors automatically
make website-lint-fix
```
The documentation is generated based on the tool [terraform-plugin-docs](https://github.com/hashicorp/terraform-plugin-docs):
- The content of the `Description` attribute is parsed of each resource
- All the templates for the resources are located in `templates`.
### Test against current terraform IaC descriptions
In order to extend the provider and test it with `terraform`, build the provider as mentioned above with:

View file

@ -12,6 +12,7 @@ setup:
cd tools && GO111MODULE=on go install github.com/client9/misspell/cmd/misspell
cd tools && GO111MODULE=on go install github.com/katbyte/terrafmt
cd tools && GO111MODULE=on go install github.com/golangci/golangci-lint/cmd/golangci-lint
cd tools && GO111MODULE=on go install github.com/hashicorp/terraform-plugin-docs/cmd/tfplugindocs
rm -f .git/hooks/commit-msg \
&& curl --fail -o .git/hooks/commit-msg https://raw.githubusercontent.com/hazcod/semantic-commit-hook/master/commit-msg \
&& chmod 500 .git/hooks/commit-msg
@ -63,30 +64,33 @@ test-compile:
fi
go test -c $(TEST) $(TESTARGS)
website-generation:
go generate
website-link-check:
@scripts/markdown-link-check.sh
website-lint:
@echo "==> Checking website against linters..."
@misspell -error -source=text website/ || (echo; \
@misspell -error -source=text docs/ || (echo; \
echo "Unexpected mispelling found in website files."; \
echo "To automatically fix the misspelling, run 'make website-lint-fix' and commit the changes."; \
exit 1)
@docker run -v $(PWD):/markdown 06kellyjac/markdownlint-cli website/docs/ || (echo; \
@docker run -v $(PWD):/markdown 06kellyjac/markdownlint-cli docs/ || (echo; \
echo "Unexpected issues found in website Markdown files."; \
echo "To apply any automatic fixes, run 'make website-lint-fix' and commit the changes."; \
exit 1)
@terrafmt diff ./website --check --pattern '*.markdown' --quiet || (echo; \
@terrafmt diff ./docs --check --pattern '*.md' --quiet || (echo; \
echo "Unexpected differences in website HCL formatting."; \
echo "To see the full differences, run: terrafmt diff ./website --pattern '*.markdown'"; \
echo "To see the full differences, run: terrafmt diff ./docs --pattern '*.md'"; \
echo "To automatically fix the formatting, run 'make website-lint-fix' and commit the changes."; \
exit 1)
website-lint-fix:
@echo "==> Applying automatic website linter fixes..."
@misspell -w -source=text website/
@docker run -v $(PWD):/markdown 06kellyjac/markdownlint-cli --fix website/docs/
@terrafmt fmt ./website --pattern '*.markdown'
@misspell -w -source=text docs/
@docker run -v $(PWD):/markdown 06kellyjac/markdownlint-cli --fix docs/
@terrafmt fmt ./docs --pattern '*.md'
.PHONY: build test testacc vet fmt fmtcheck errcheck test-compile website-link-check website-lint website-lint-fix

View file

@ -0,0 +1,47 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "docker_network Data Source - terraform-provider-docker"
subcategory: ""
description: |-
docker_network provides details about a specific Docker Network.
---
# docker_network (Data Source)
`docker_network` provides details about a specific Docker Network.
## Example Usage
```terraform
data "docker_network" "main" {
name = "main"
}
```
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- **name** (String) The name of the Docker network.
### Read-Only
- **driver** (String) The driver of the Docker network. Possible values are `bridge`, `host`, `overlay`, `macvlan`. See [network docs](https://docs.docker.com/network/#network-drivers) for more details.
- **id** (String) The ID of this resource.
- **internal** (Boolean) If `true`, the network is internal.
- **ipam_config** (Set of Object) The IPAM configuration options (see [below for nested schema](#nestedatt--ipam_config))
- **options** (Map of String) Only available with bridge networks. See [bridge options docs](https://docs.docker.com/engine/reference/commandline/network_create/#bridge-driver-options) for more details.
- **scope** (String) Scope of the network. One of `swarm`, `global`, or `local`.
<a id="nestedatt--ipam_config"></a>
### Nested Schema for `ipam_config`
Read-Only:
- **aux_address** (Map of String)
- **gateway** (String)
- **ip_range** (String)
- **subnet** (String)

View file

@ -0,0 +1,43 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "docker_plugin Data Source - terraform-provider-docker"
subcategory: ""
description: |-
Reads the local Docker plugin. The plugin must be installed locally.
---
# docker_plugin (Data Source)
Reads the local Docker plugin. The plugin must be installed locally.
## Example Usage
```terraform
### With alias
data "docker_plugin" "by_alias" {
alias = "sample-volume-plugin:latest"
}
### With ID
data "docker_plugin" "by_id" {
id = "e9a9db917b3bfd6706b5d3a66d4bceb9f"
}
```
<!-- schema generated by tfplugindocs -->
## Schema
### Optional
- **alias** (String) The alias of the Docker plugin. If the tag is omitted, `:latest` is complemented to the attribute value.
- **id** (String) The ID of the plugin, which has precedence over the `alias` of both are given
### Read-Only
- **enabled** (Boolean) If `true` the plugin is enabled
- **env** (Set of String) The environment variables in the form of `KEY=VALUE`, e.g. `DEBUG=0`
- **grant_all_permissions** (Boolean) If true, grant all permissions necessary to run the plugin
- **name** (String) The plugin name. If the tag is omitted, `:latest` is complemented to the attribute value.
- **plugin_reference** (String) The Docker Plugin Reference

View file

@ -0,0 +1,41 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "docker_registry_image Data Source - terraform-provider-docker"
subcategory: ""
description: |-
Reads the image metadata from a Docker Registry. Used in conjunction with the docker_image ../resources/image.md resource to keep an image up to date on the latest available version of the tag.
---
# docker_registry_image (Data Source)
Reads the image metadata from a Docker Registry. Used in conjunction with the [docker_image](../resources/image.md) resource to keep an image up to date on the latest available version of the tag.
## Example Usage
```terraform
data "docker_registry_image" "ubuntu" {
name = "ubuntu:precise"
}
resource "docker_image" "ubuntu" {
name = data.docker_registry_image.ubuntu.name
pull_triggers = [data.docker_registry_image.ubuntu.sha256_digest]
}
```
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- **name** (String) The name of the Docker image, including any tags. e.g. `alpine:latest`
### Optional
- **id** (String) The ID of this resource.
### Read-Only
- **sha256_digest** (String) The content digest of the image, as stored in the registry.

201
docs/index.md Normal file
View file

@ -0,0 +1,201 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
layout: ""
page_title: "Provider: Docker"
description: |-
The Docker provider is used to interact with Docker resources, like containers, images, service etc.
---
# Docker Provider
The Docker provider is used to interact with Docker containers and images.
It uses the Docker API to manage the lifecycle of Docker containers. Because
the Docker provider uses the Docker API, it is immediately compatible not
only with single server Docker but Swarm and any additional Docker-compatible
API hosts.
Use the navigation to the left to read about the available resources.
## Example Usage
Terraform 0.13 and later:
```terraform
terraform {
required_providers {
docker = {
source = "kreuzwerker/docker"
version = "2.11.0"
}
}
}
provider "docker" {
host = "unix:///var/run/docker.sock"
}
# Pulls the image
resource "docker_image" "ubuntu" {
name = "ubuntu:latest"
}
# Create a container
resource "docker_container" "foo" {
image = docker_image.ubuntu.latest
name = "foo"
}
```
Terraform 0.12 and earlier:
```terraform
provider "docker" {
version = "~> 2.11.0"
host = "unix:///var/run/docker.sock"
}
# Pulls the image
resource "docker_image" "ubuntu" {
name = "ubuntu:latest"
}
# Create a container
resource "docker_container" "foo" {
image = docker_image.ubuntu.latest
name = "foo"
}
```
-> **Note**
You can also use the `ssh` protocol to connect to the docker host on a remote machine.
The configuration would look as follows:
```terraform
terraform {
required_providers {
docker = {
source = "kreuzwerker/docker"
version = "2.11.0"
}
}
}
provider "docker" {
host = "unix:///var/run/docker.sock"
}
# Pulls the image
resource "docker_image" "ubuntu" {
name = "ubuntu:latest"
}
# Create a container
resource "docker_container" "foo" {
image = docker_image.ubuntu.latest
name = "foo"
}
```
## Registry credentials
Registry credentials can be provided on a per-registry basis with the `registry_auth`
field, passing either a config file or the username/password directly.
-> **Note**
The location of the config file is on the machine terraform runs on, nevertheless if the specified docker host is on another machine.
```terraform
provider "docker" {
host = "tcp://localhost:2376"
registry_auth {
address = "registry.hub.docker.com"
config_file = pathexpand("~/.docker/config.json")
}
registry_auth {
address = "registry.my.company.com"
config_file_content = var.plain_content_of_config_file
}
registry_auth {
address = "quay.io:8181"
username = "someuser"
password = "somepass"
}
}
data "docker_registry_image" "quay" {
name = "myorg/privateimage"
}
data "docker_registry_image" "quay" {
name = "quay.io:8181/myorg/privateimage"
}
```
-> **Note**
When passing in a config file either the corresponding `auth` string of the repository is read or the os specific
[credential helpers](https://github.com/docker/docker-credential-helpers#available-programs) are
used to retrieve the authentication credentials.
You can still use the environment variables `DOCKER_REGISTRY_USER` and `DOCKER_REGISTRY_PASS`.
An example content of the file `~/.docker/config.json` on macOS may look like follows:
```json
{
"auths": {
"repo.mycompany:8181": {
"auth": "dXNlcjpwYXNz="
},
"otherrepo.other-company:8181": {}
},
"credsStore": "osxkeychain"
}
```
## Certificate information
Specify certificate information either with a directory or
directly with the content of the files for connecting to the Docker host via TLS.
```terraform
provider "docker" {
host = "tcp://your-host-ip:2376/"
# -> specify either
cert_path = pathexpand("~/.docker")
# -> or the following
ca_material = file(pathexpand("~/.docker/ca.pem")) # this can be omitted
cert_material = file(pathexpand("~/.docker/cert.pem"))
key_material = file(pathexpand("~/.docker/key.pem"))
}
```
<!-- schema generated by tfplugindocs -->
## Schema
### Optional
- **ca_material** (String) PEM-encoded content of Docker host CA certificate
- **cert_material** (String) PEM-encoded content of Docker client certificate
- **cert_path** (String) Path to directory with Docker TLS config
- **host** (String) The Docker daemon address
- **key_material** (String) PEM-encoded content of Docker client private key
- **registry_auth** (Block List, Max: 1) (see [below for nested schema](#nestedblock--registry_auth))
<a id="nestedblock--registry_auth"></a>
### Nested Schema for `registry_auth`
Required:
- **address** (String) Address of the registry
Optional:
- **config_file** (String) Path to docker json file for registry auth
- **config_file_content** (String) Plain content of the docker json file for registry auth
- **password** (String, Sensitive) Password for the registry
- **username** (String) Username for the registry

138
docs/resources/config.md Normal file
View file

@ -0,0 +1,138 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "docker_config Resource - terraform-provider-docker"
subcategory: ""
description: |-
Manages the configs of a Docker service in a swarm.
---
<!-- Bug: Type and Name are switched -->
# docker_config (Resource)
Manages the configs of a Docker service in a swarm.
## Example Usage
### Basic
```terraform
resource "docker_config" "foo_config" {
name = "foo_config"
data = base64encode("{\"a\": \"b\"}")
}
```
### Advanced
#### Dynamically set config with a template
In this example you can use the `${var.foo_port}` variable to dynamically
set the `${port}` variable in the `foo.configs.json.tpl` template and create
the data of the `foo_config` with the help of the `base64encode` interpolation
function.
The file `foo.config.json.tpl` has the following content:
```gojson
{
"server": {
"public_port": ${port}
}
}
```
and the resource uses it as follows:
```terraform
resource "docker_config" "foo_config" {
name = "foo_config"
data = base64encode(
templatefile("${path.cwd}/foo.config.json.tpl",
{
port = 8080
}
)
)
}
```
#### Update config with no downtime
To update a `config`, Terraform will destroy the existing resource and create a replacement.
To effectively use a `docker_config` resource with a `docker_service` resource, it's recommended
to specify `create_before_destroy` in a `lifecycle` block. Provide a unique `name` attribute,
for example with one of the interpolation functions `uuid` or `timestamp` as shown
in the example below. The reason is this [issue](https://github.com/moby/moby/issues/35803).
```terraform
resource "docker_config" "service_config" {
name = "${var.service_name}-config-${replace(timestamp(), ":", ".")}"
data = base64encode(
templatefile("${path.cwd}/foo.config.json.tpl",
{
port = 8080
}
)
)
lifecycle {
ignore_changes = ["name"]
create_before_destroy = true
}
}
resource "docker_service" "service" {
# ... other attributes omitted for brevity
configs = [
{
config_id = docker_config.service_config.id
config_name = docker_config.service_config.name
file_name = "/root/configs/configs.json"
},
]
}
```
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- **data** (String) Base64-url-safe-encoded config data
- **name** (String) User-defined name of the config
### Optional
- **id** (String) The ID of this resource.
## Import
Import is supported using the following syntax by providing the `id`:
```shell
#!/bin/bash
terraform import docker_config.foo id
```
### Example
Assuming you created a `config` as follows
```shell
#!/bin/bash
printf '{"a":"b"}' | docker config create foo -
# prints the id
08c26c477474478d971139f750984775a7f019dbe8a2e7f09d66a187c009e66d
```
you provide the definition for the resource as follows
```terraform
resource "docker_config" "foo" {
name = "foo"
data = base64encode("{\"a\": \"b\"}")
}
```
then the import command is as follows
```shell
#!/bin/bash
terraform import docker_config.foo 08c26c477474478d971139f750984775a7f019dbe8a2e7f09d66a187c009e66d
```

331
docs/resources/container.md Normal file
View file

@ -0,0 +1,331 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "docker_container Resource - terraform-provider-docker"
subcategory: ""
description: |-
Manages the lifecycle of a Docker container.
---
<!-- Bug: Type and Name are switched -->
# docker_container (Resource)
Manages the lifecycle of a Docker container.
## Example Usage
```terraform
# Start a container
resource "docker_container" "ubuntu" {
name = "foo"
image = docker_image.ubuntu.latest
}
# Find the latest Ubuntu precise image.
resource "docker_image" "ubuntu" {
name = "ubuntu:precise"
}
```
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- **image** (String) The ID of the image to back this container. The easiest way to get this value is to use the `docker_image` resource as is shown in the example.
- **name** (String) The name of the container.
### Optional
- **attach** (Boolean) If `true` attach to the container after its creation and waits the end of its execution. Defaults to `false`.
- **capabilities** (Block Set, Max: 1) Add or drop certrain linux capabilities. (see [below for nested schema](#nestedblock--capabilities))
- **command** (List of String) The command to use to start the container. For example, to run `/usr/bin/myprogram -f baz.conf` set the command to be `["/usr/bin/myprogram","-","baz.con"]`.
- **cpu_set** (String) A comma-separated list or hyphen-separated range of CPUs a container can use, e.g. `0-1`.
- **cpu_shares** (Number) CPU shares (relative weight) for the container.
- **destroy_grace_seconds** (Number) If defined will attempt to stop the container before destroying. Container will be destroyed after `n` seconds or on successful stop.
- **devices** (Block Set) Bind devices to the container. (see [below for nested schema](#nestedblock--devices))
- **dns** (Set of String) DNS servers to use.
- **dns_opts** (Set of String) DNS options used by the DNS provider(s), see `resolv.conf` documentation for valid list of options.
- **dns_search** (Set of String) DNS search domains that are used when bare unqualified hostnames are used inside of the container.
- **domainname** (String) Domain name of the container.
- **entrypoint** (List of String) The command to use as the Entrypoint for the container. The Entrypoint allows you to configure a container to run as an executable. For example, to run `/usr/bin/myprogram` when starting a container, set the entrypoint to be `"/usr/bin/myprogra"]`.
- **env** (Set of String) Environment variables to set in the form of `KEY=VALUE`, e.g. `DEBUG=0`
- **group_add** (Set of String) Additional groups for the container user
- **healthcheck** (Block List, Max: 1) A test to perform to check that the container is healthy (see [below for nested schema](#nestedblock--healthcheck))
- **host** (Block Set) Additional hosts to add to the container. (see [below for nested schema](#nestedblock--host))
- **hostname** (String) Hostname of the container.
- **id** (String) The ID of this resource.
- **init** (Boolean) Configured whether an init process should be injected for this container. If unset this will default to the `dockerd` defaults.
- **ipc_mode** (String) IPC sharing mode for the container. Possible values are: `none`, `private`, `shareable`, `container:<name|id>` or `host`.
- **labels** (Block Set) User-defined key/value metadata (see [below for nested schema](#nestedblock--labels))
- **links** (Set of String, Deprecated) Set of links for link based connectivity between containers that are running on the same host.
- **log_driver** (String) The logging driver to use for the container. Defaults to `json-file`.
- **log_opts** (Map of String) Key/value pairs to use as options for the logging driver.
- **logs** (Boolean) Save the container logs (`attach` must be enabled). Defaults to `false`.
- **max_retry_count** (Number) The maximum amount of times to an attempt a restart when `restart` is set to 'on-failure'.
- **memory** (Number) The memory limit for the container in MBs.
- **memory_swap** (Number) The total memory limit (memory + swap) for the container in MBs. This setting may compute to `-1` after `terraform apply` if the target host doesn't support memory swap, when that is the case docker will use a soft limitation.
- **mounts** (Block Set) Specification for mounts to be added to containers created as part of the service. (see [below for nested schema](#nestedblock--mounts))
- **must_run** (Boolean) If `true`, then the Docker container will be kept running. If `false`, then as long as the container exists, Terraform assumes it is successful. Defaults to `true`.
- **network_alias** (Set of String, Deprecated) Set an alias for the container in all specified networks
- **network_mode** (String) Network mode of the container.
- **networks** (Set of String, Deprecated) ID of the networks in which the container is.
- **networks_advanced** (Block Set) The networks the container is attached to (see [below for nested schema](#nestedblock--networks_advanced))
- **pid_mode** (String) he PID (Process) Namespace mode for the container. Either `container:<name|id>` or `host`.
- **ports** (Block List) Publish a container's port(s) to the host. (see [below for nested schema](#nestedblock--ports))
- **privileged** (Boolean) If `true`, the container runs in privileged mode.
- **publish_all_ports** (Boolean) Publish all ports of the container.
- **read_only** (Boolean) If `true`, the container will be started as readonly. Defaults to `false`.
- **remove_volumes** (Boolean) If `true`, it will remove anonymous volumes associated with the container. Defaults to `true`.
- **restart** (String) The restart policy for the container. Must be one of 'no', 'on-failure', 'always', 'unless-stopped'. Defaults to `no`.
- **rm** (Boolean) If `true`, then the container will be automatically removed after his execution. Terraform won't check this container after creation. Defaults to `false`.
- **security_opts** (Set of String) List of string values to customize labels for MLS systems, such as SELinux. See https://docs.docker.com/engine/reference/run/#security-configuration.
- **shm_size** (Number) Size of `/dev/shm` in MBs.
- **start** (Boolean) If `true`, then the Docker container will be started after creation. If `false`, then the container is only created. Defaults to `true`.
- **stdin_open** (Boolean) If `true`, keep STDIN open even if not attached (`docker run -i`). Defaults to `false`.
- **sysctls** (Map of String) A map of kernel parameters (sysctls) to set in the container.
- **tmpfs** (Map of String) A map of container directories which should be replaced by `tmpfs mounts`, and their corresponding mount options.
- **tty** (Boolean) If `true`, allocate a pseudo-tty (`docker run -t`). Defaults to `false`.
- **ulimit** (Block Set) Ulimit options to add. (see [below for nested schema](#nestedblock--ulimit))
- **upload** (Block Set) Specifies files to upload to the container before starting it. Only one of `content` or `content_base64` can be set and at least one of them has to be set. (see [below for nested schema](#nestedblock--upload))
- **user** (String) User used for run the first process. Format is `user` or `user:group` which user and group can be passed literraly or by name.
- **userns_mode** (String) Sets the usernamespace mode for the container when usernamespace remapping option is enabled.
- **volumes** (Block Set) Spec for mounting volumes in the container. (see [below for nested schema](#nestedblock--volumes))
- **working_dir** (String) The working directory for commands to run in.
### Read-Only
- **bridge** (String) The network bridge of the container as read from its NetworkSettings.
- **container_logs** (String) The logs of the container if its execution is done (`attach` must be disabled).
- **exit_code** (Number) The exit code of the container if its execution is done (`must_run` must be disabled).
- **gateway** (String, Deprecated) The network gateway of the container.
- **ip_address** (String, Deprecated) The IP address of the container.
- **ip_prefix_length** (Number, Deprecated) The IP prefix length of the container.
- **network_data** (List of Object) The data of the networks the container is connected to. (see [below for nested schema](#nestedatt--network_data))
<a id="nestedblock--capabilities"></a>
### Nested Schema for `capabilities`
Optional:
- **add** (Set of String) List of linux capabilities to add.
- **drop** (Set of String) List of linux capabilities to drop.
<a id="nestedblock--devices"></a>
### Nested Schema for `devices`
Required:
- **host_path** (String) The path on the host where the device is located.
Optional:
- **container_path** (String) The path in the container where the device will be bound.
- **permissions** (String) The cgroup permissions given to the container to access the device. Defaults to `rwm`.
<a id="nestedblock--healthcheck"></a>
### Nested Schema for `healthcheck`
Required:
- **test** (List of String) Command to run to check health. For example, to run `curl -f localhost/health` set the command to be `["CMD", "curl", "-f", "localhost/health"]`.
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`.
<a id="nestedblock--host"></a>
### Nested Schema for `host`
Required:
- **host** (String) Hostname to add
- **ip** (String) IP address this hostname should resolve to.
<a id="nestedblock--labels"></a>
### Nested Schema for `labels`
Required:
- **label** (String) Name of the label
- **value** (String) Value of the label
<a id="nestedblock--mounts"></a>
### Nested Schema for `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](#nestedblock--mounts--bind_options))
- **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](#nestedblock--mounts--tmpfs_options))
- **volume_options** (Block List, Max: 1) Optional configuration for the volume type. (see [below for nested schema](#nestedblock--mounts--volume_options))
<a id="nestedblock--mounts--bind_options"></a>
### Nested Schema for `mounts.bind_options`
Optional:
- **propagation** (String) A propagation mode with the value.
<a id="nestedblock--mounts--tmpfs_options"></a>
### Nested Schema for `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.
<a id="nestedblock--mounts--volume_options"></a>
### Nested Schema for `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](#nestedblock--mounts--volume_options--labels))
- **no_copy** (Boolean) Populate volume with data from the target.
<a id="nestedblock--mounts--volume_options--labels"></a>
### Nested Schema for `mounts.volume_options.labels`
Required:
- **label** (String) Name of the label
- **value** (String) Value of the label
<a id="nestedblock--networks_advanced"></a>
### Nested Schema for `networks_advanced`
Required:
- **name** (String) The name of the network.
Optional:
- **aliases** (Set of String) The network aliases of the container in the specific network.
- **ipv4_address** (String) The IPV4 address of the container in the specific network.
- **ipv6_address** (String) The IPV6 address of the container in the specific network.
<a id="nestedblock--ports"></a>
### Nested Schema for `ports`
Required:
- **internal** (Number) Port within the container.
Optional:
- **external** (Number) Port exposed out of the container. If not given a free random port `>= 32768` will be used.
- **ip** (String) IP address/mask that can access this port. Defaults to `0.0.0.0`.
- **protocol** (String) Protocol that can be used over this port. Defaults to `tcp`.
<a id="nestedblock--ulimit"></a>
### Nested Schema for `ulimit`
Required:
- **hard** (Number) The hard limit
- **name** (String) The name of the ulimit
- **soft** (Number) The soft limit
<a id="nestedblock--upload"></a>
### Nested Schema for `upload`
Required:
- **file** (String) Path to the file in the container where is upload goes to
Optional:
- **content** (String) Literal string value to use as the object content, which will be uploaded as UTF-8-encoded text. Conflicts with `content_base64` & `source`
- **content_base64** (String) Base64-encoded data that will be decoded and uploaded as raw bytes for the object content. This allows safely uploading non-UTF8 binary data, but is recommended only for larger binary content such as the result of the `base64encode` interpolation function. See [here](https://github.com/terraform-providers/terraform-provider-docker/issues/48#issuecomment-374174588) for the reason. Conflicts with `content` & `source`
- **executable** (Boolean) If `true`, the file will be uploaded with user executable permission. Defaults to `false`.
- **source** (String) A filename that references a file which will be uploaded as the object content. This allows for large file uploads that do not get stored in state. Conflicts with `content` & `content_base64`
- **source_hash** (String) If using `source`, this will force an update if the file content has updated but the filename has not.
<a id="nestedblock--volumes"></a>
### Nested Schema for `volumes`
Optional:
- **container_path** (String) The path in the container where the volume will be mounted.
- **from_container** (String) The container where the volume is coming from.
- **host_path** (String) The path on the host where the volume is coming from.
- **read_only** (Boolean) If `true`, this volume will be readonly. Defaults to `false`.
- **volume_name** (String) The name of the docker volume which should be mounted.
<a id="nestedatt--network_data"></a>
### Nested Schema for `network_data`
Read-Only:
- **gateway** (String)
- **global_ipv6_address** (String)
- **global_ipv6_prefix_length** (Number)
- **ip_address** (String)
- **ip_prefix_length** (Number)
- **ipv6_gateway** (String)
- **network_name** (String)
## Import
Import is supported using the following syntax by providing the `id`:
```shell
#!/bin/bash
terraform import docker_container.foo id
```
### Example
Assuming you created a `container` as follows
```shell
#!/bin/bash
docker run --name foo -p8080:80 -d nginx
# prints the container ID
9a550c0f0163d39d77222d3efd58701b625d47676c25c686c95b5b92d1cba6fd
```
you provide the definition for the resource as follows
```terraform
resource "docker_container" "foo" {
name = "foo"
image = "nginx"
ports {
internal = "80"
external = "8080"
}
}
```
then the import command is as follows
```shell
#!/bin/bash
terraform import docker_container.foo 9a550c0f0163d39d77222d3efd58701b625d47676c25c686c95b5b92d1cba6fd
```

102
docs/resources/image.md Normal file
View file

@ -0,0 +1,102 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "docker_image Resource - terraform-provider-docker"
subcategory: ""
description: |-
Pulls a Docker image to a given Docker host from a Docker Registry.
This resource will not pull new layers of the image automatically unless used in conjunction with dockerregistryimage registry_image.md data source to update the pull_triggers field.
---
<!-- Bug: Type and Name are switched -->
# docker_image (Resource)
Pulls a Docker image to a given Docker host from a Docker Registry.
This resource will *not* pull new layers of the image automatically unless used in conjunction with [docker_registry_image](registry_image.md) data source to update the `pull_triggers` field.
## Example Usage
### Basic
Finds and downloads the latest `ubuntu:precise` image but does not check
for further updates of the image
```terraform
resource "docker_image" "ubuntu" {
name = "ubuntu:precise"
}
```
### Dynamic updates
To be able to update an update dynamically when the `sha256` sum changes,
you need to use it in combination with `docker_registry_image` as follows:
```terraform
data "docker_registry_image" "ubuntu" {
name = "ubuntu:precise"
}
resource "docker_image" "ubuntu" {
name = data.docker_registry_image.ubuntu.name
pull_triggers = [data.docker_registry_image.ubuntu.sha256_digest]
}
```
### Build
You can also use the resource to build and image.
In thid case the image "zoo" and "zoo:develop" are built.
```terraform
resource "docker_image" "zoo" {
name = "zoo"
build {
path = "."
tag = ["zoo:develop"]
build_arg = {
foo : "zoo"
}
label = {
author : "zoo"
}
}
}
```
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- **name** (String) The name of the Docker image, including any tags or SHA256 repo digests.
### Optional
- **build** (Block Set, Max: 1) Configuration to build an image. Please see [docker build command reference](https://docs.docker.com/engine/reference/commandline/build/#options) too. (see [below for nested schema](#nestedblock--build))
- **force_remove** (Boolean) If true, then the image is removed forcibly when the resource is destroyed.
- **id** (String) The ID of this resource.
- **keep_locally** (Boolean) If true, then the Docker image won't be deleted on destroy operation. If this is false, it will delete the image from the docker local storage on destroy operation.
- **pull_trigger** (String, Deprecated) A value which cause an image pull when changed
- **pull_triggers** (Set of String) List of values which cause an image pull when changed. This is used to store the image digest from the registry when using the [docker_registry_image](../data-sources/registry_image.md).
### Read-Only
- **latest** (String) The ID of the image.
- **output** (String, Deprecated)
<a id="nestedblock--build"></a>
### Nested Schema for `build`
Required:
- **path** (String) Context path
Optional:
- **build_arg** (Map of String) Set build-time variables
- **dockerfile** (String) Name of the Dockerfile. Defaults to `Dockerfile`.
- **force_remove** (Boolean) Always remove intermediate containers
- **label** (Map of String) Set metadata for an image
- **no_cache** (Boolean) Do not use cache when building the image
- **remove** (Boolean) Remove intermediate containers after a successful build. Defaults to `true`.
- **tag** (List of String) Name and optionally a tag in the 'name:tag' format
- **target** (String) Set the target build stage to build

98
docs/resources/network.md Normal file
View file

@ -0,0 +1,98 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "docker_network Resource - terraform-provider-docker"
subcategory: ""
description: |-
docker_network provides details about a specific Docker Network.
---
<!-- Bug: Type and Name are switched -->
# docker_network (Resource)
`docker_network` provides details about a specific Docker Network.
## Example Usage
```terraform
resource "docker_network" "private_network" {
name = "my_network"
}
```
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- **name** (String) The name of the Docker network.
### Optional
- **attachable** (Boolean) Enable manual container attachment to the network.
- **check_duplicate** (Boolean) Requests daemon to check for networks with same name.
- **driver** (String) The driver of the Docker network. Possible values are `bridge`, `host`, `overlay`, `macvlan`. See [network docs](https://docs.docker.com/network/#network-drivers) for more details.
- **id** (String) The ID of this resource.
- **ingress** (Boolean) Create swarm routing-mesh network. Defaults to `false`.
- **internal** (Boolean) Whether the network is internal.
- **ipam_config** (Block Set) The IPAM configuration options (see [below for nested schema](#nestedblock--ipam_config))
- **ipam_driver** (String) Driver used by the custom IP scheme of the network. Defaults to `default`
- **ipv6** (Boolean) Enable IPv6 networking. Defaults to `false`.
- **labels** (Block Set) User-defined key/value metadata (see [below for nested schema](#nestedblock--labels))
- **options** (Map of String) Only available with bridge networks. See [bridge options docs](https://docs.docker.com/engine/reference/commandline/network_create/#bridge-driver-options) for more details.
### Read-Only
- **scope** (String) Scope of the network. One of `swarm`, `global`, or `local`.
<a id="nestedblock--ipam_config"></a>
### Nested Schema for `ipam_config`
Optional:
- **aux_address** (Map of String) Auxiliary IPv4 or IPv6 addresses used by Network driver
- **gateway** (String) The IP address of the gateway
- **ip_range** (String) The ip range in CIDR form
- **subnet** (String) The subnet in CIDR form
<a id="nestedblock--labels"></a>
### Nested Schema for `labels`
Required:
- **label** (String) Name of the label
- **value** (String) Value of the label
## Import
Import is supported using the following syntax by providing the `id`:
```shell
#!/bin/bash
terraform import docker_network.foo id
```
### Example
Assuming you created a `network` as follows
```shell
#!/bin/bash
docker network create foo
# prints the long ID
87b57a9b91ecab2db2a6dbf38df74c67d7c7108cbe479d6576574ec2cd8c2d73
```
you provide the definition for the resource as follows
```terraform
resource "docker_network" "foo" {
name = "foo"
}
```
then the import command is as follows
```shell
#!/bin/bash
terraform import docker_network.foo 87b57a9b91ecab2db2a6dbf38df74c67d7c7108cbe479d6576574ec2cd8c2d73
```

72
docs/resources/plugin.md Normal file
View file

@ -0,0 +1,72 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "docker_plugin Resource - terraform-provider-docker"
subcategory: ""
description: |-
Manages the lifecycle of a Docker plugin.
---
<!-- Bug: Type and Name are switched -->
# docker_plugin (Resource)
Manages the lifecycle of a Docker plugin.
## Example Usage
```terraform
resource "docker_plugin" "sample-volume-plugin" {
name = "docker.io/tiborvass/sample-volume-plugin:latest"
}
resource "docker_plugin" "sample-volume-plugin" {
name = "tiborvass/sample-volume-plugin"
alias = "sample-volume-plugin"
enabled = false
grant_all_permissions = true
force_destroy = true
enable_timeout = 60
force_disable = true
env = [
"DEBUG=1"
]
}
```
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- **name** (String) Docker Plugin name
### Optional
- **alias** (String) Docker Plugin alias
- **enable_timeout** (Number) HTTP client timeout to enable the plugin
- **enabled** (Boolean) If `true` the plugin is enabled. Defaults to `true`
- **env** (Set of String) The environment variables in the form of `KEY=VALUE`, e.g. `DEBUG=0`
- **force_destroy** (Boolean) If true, then the plugin is destroyed forcibly
- **force_disable** (Boolean) If true, then the plugin is disabled forcibly
- **grant_all_permissions** (Boolean) If true, grant all permissions necessary to run the plugin
- **grant_permissions** (Block Set) Grant specific permissions only (see [below for nested schema](#nestedblock--grant_permissions))
- **id** (String) The ID of this resource.
### Read-Only
- **plugin_reference** (String) Docker Plugin Reference
<a id="nestedblock--grant_permissions"></a>
### Nested Schema for `grant_permissions`
Required:
- **name** (String) The name of the permission
- **value** (Set of String) The value of the permission
## Import
Import is supported using the following syntax:
```shell
#!/bin/bash
terraform import docker_plugin.sample-volume-plugin "$(docker plugin inspect -f {{.ID}} tiborvass/sample-volume-plugin:latest)"
```

View file

@ -0,0 +1,108 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "docker_registry_image Resource - terraform-provider-docker"
subcategory: ""
description: |-
Manages the lifecycle of docker image/tag in a registry.
---
<!-- Bug: Type and Name are switched -->
# docker_registry_image (Resource)
Manages the lifecycle of docker image/tag in a registry.
## Example Usage
```terraform
resource "docker_registry_image" "helloworld" {
name = "helloworld:1.0"
build {
context = "pathToContextFolder"
}
}
```
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- **name** (String) The name of the Docker image.
### Optional
- **build** (Block List, Max: 1) Definition for building the image (see [below for nested schema](#nestedblock--build))
- **id** (String) The ID of this resource.
- **keep_remotely** (Boolean) If true, then the Docker image won't be deleted on destroy operation. If this is false, it will delete the image from the docker registry on destroy operation. Defaults to `false`
### Read-Only
- **sha256_digest** (String) The sha256 digest of the image.
<a id="nestedblock--build"></a>
### Nested Schema for `build`
Required:
- **context** (String) The path to the context folder
Optional:
- **auth_config** (Block List) The configuration for the autentication (see [below for nested schema](#nestedblock--build--auth_config))
- **build_args** (Map of String) Pairs for build-time variables in the form TODO
- **build_id** (String) BuildID is an optional identifier that can be passed together with the build request. The
- **cache_from** (List of String) Images to consider as cache sources
- **cgroup_parent** (String) Optional parent cgroup for the container
- **cpu_period** (Number) The length of a CPU period in microseconds
- **cpu_quota** (Number) Microseconds of CPU time that the container can get in a CPU period
- **cpu_set_cpus** (String) CPUs in which to allow execution (e.g., `0-3`, `0`, `1`)
- **cpu_set_mems** (String) MEMs in which to allow execution (`0-3`, `0`, `1`)
- **cpu_shares** (Number) CPU shares (relative weight)
- **dockerfile** (String) Dockerfile file. Defaults to `Dockerfile`
- **extra_hosts** (List of String) A list of hostnames/IP mappings to add to the containers /etc/hosts file. Specified in the form ["hostname:IP"]
- **force_remove** (Boolean) Always remove intermediate containers
- **isolation** (String) Isolation represents the isolation technology of a container. The supported values are
- **labels** (Map of String) User-defined key/value metadata
- **memory** (Number) Set memory limit for build
- **memory_swap** (Number) Total memory (memory + swap), -1 to enable unlimited swap
- **network_mode** (String) Set the networking mode for the RUN instructions during build
- **no_cache** (Boolean) Do not use the cache when building the image
- **platform** (String) Set platform if server is multi-platform capable
- **pull_parent** (Boolean) Attempt to pull the image even if an older image exists locally
- **remote_context** (String) A Git repository URI or HTTP/HTTPS context URI
- **remove** (Boolean) Remove intermediate containers after a successful build (default behavior)
- **security_opt** (List of String) The security options
- **session_id** (String) Set an ID for the build session
- **shm_size** (Number) Size of /dev/shm in bytes. The size must be greater than 0
- **squash** (Boolean) If true the new layers are squashed into a new image with a single new layer
- **suppress_output** (Boolean) Suppress the build output and print image ID on success
- **target** (String) Set the target build stage to build
- **ulimit** (Block List) Configuration for ulimits (see [below for nested schema](#nestedblock--build--ulimit))
- **version** (String) Version of the unerlying builder to use
<a id="nestedblock--build--auth_config"></a>
### Nested Schema for `build.auth_config`
Required:
- **host_name** (String) hostname of the registry
Optional:
- **auth** (String) the auth token
- **email** (String) the user emal
- **identity_token** (String) the identity token
- **password** (String) the registry password
- **registry_token** (String) the registry token
- **server_address** (String) the server address
- **user_name** (String) the registry user name
<a id="nestedblock--build--ulimit"></a>
### Nested Schema for `build.ulimit`
Required:
- **hard** (Number) soft limit
- **name** (String) type of ulimit, e.g. `nofile`
- **soft** (Number) hard limit

89
docs/resources/secret.md Normal file
View file

@ -0,0 +1,89 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "docker_secret Resource - terraform-provider-docker"
subcategory: ""
description: |-
Manages the secrets of a Docker service in a swarm.
---
<!-- Bug: Type and Name are switched -->
# docker_secret (Resource)
Manages the secrets of a Docker service in a swarm.
## Example Usage
### Basic
```terraform
resource "docker_secret" "foo" {
name = "foo"
data = base64encode("{\"foo\": \"s3cr3t\"}")
}
```
### Update secret with no downtime
To update a `secret`, Terraform will destroy the existing resource and create a replacement.
To effectively use a `docker_secret` resource with a `docker_service` resource,
it's recommended to specify `create_before_destroy` in a `lifecycle` block. Provide a unique `name` attribute, for example
with one of the interpolation functions `uuid` or `timestamp` as shown
in the example below. The reason is [moby-35803](https://github.com/moby/moby/issues/35803).
```terraform
resource "docker_secret" "service_secret" {
name = "${var.service_name}-secret-${replace(timestamp(), ":", ".")}"
data = base64encode(
templatefile("${path.cwd}/foo.secret.json.tpl",
{
secret = "s3cr3t"
}
)
)
lifecycle {
ignore_changes = ["name"]
create_before_destroy = true
}
}
resource "docker_service" "service" {
# ...
secrets = [
{
secret_id = docker_secret.service_secret.id
secret_name = docker_secret.service_secret.name
file_name = "/root/configs/configs.json"
},
]
}
```
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- **data** (String, Sensitive) Base64-url-safe-encoded secret data
- **name** (String) User-defined name of the secret
### Optional
- **id** (String) The ID of this resource.
- **labels** (Block Set) User-defined key/value metadata (see [below for nested schema](#nestedblock--labels))
<a id="nestedblock--labels"></a>
### Nested Schema for `labels`
Required:
- **label** (String) Name of the label
- **value** (String) Value of the label
## Import
Import is supported using the following syntax:
```shell
#!/bin/bash
# Docker secret cannot be imported as the secret data, once set, is never exposed again.
```

722
docs/resources/service.md Normal file
View file

@ -0,0 +1,722 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "docker_service Resource - terraform-provider-docker"
subcategory: ""
description: |-
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.
---
<!-- Bug: Type and Name are switched -->
# docker_service (Resource)
This resource manages the lifecycle of a Docker service. By default, the creation, update and delete of services are detached.
With the [Converge Config](#convergeconfig) 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
```terraform
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:
```shell
#!/bin/bash
docker service create -d -p 8080 --name foo-service repo.mycompany.com:8080/foo-service:v1
```
### Advanced
The following configuration shows the full capabilities of a Docker Service,
with a `volume`, `config`, `secret` and `network`
```terraform
resource "docker_volume" "test_volume" {
name = "tftest-volume"
}
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 = "volume"
read_only = true
bind_options {
propagation = "private"
}
}
mounts {
# another mount
}
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 generated by tfplugindocs -->
## 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](#nestedblock--task_spec))
### Optional
- **auth** (Block List, Max: 1) Configuration for the authentication for pulling the images of the service (see [below for nested schema](#nestedblock--auth))
- **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](#nestedblock--converge_config))
- **endpoint_spec** (Block List, Max: 1) Properties that can be configured to access and load balance a service (see [below for nested schema](#nestedblock--endpoint_spec))
- **id** (String) The ID of this resource.
- **labels** (Block Set) User-defined key/value metadata (see [below for nested schema](#nestedblock--labels))
- **mode** (Block List, Max: 1) Scheduling mode for the service (see [below for nested schema](#nestedblock--mode))
- **rollback_config** (Block List, Max: 1) Specification for the rollback strategy of the service (see [below for nested schema](#nestedblock--rollback_config))
- **update_config** (Block List, Max: 1) Specification for the update strategy of the service (see [below for nested schema](#nestedblock--update_config))
<a id="nestedblock--task_spec"></a>
### Nested Schema for `task_spec`
Required:
- **container_spec** (Block List, Min: 1, Max: 1) The spec for each container (see [below for nested schema](#nestedblock--task_spec--container_spec))
Optional:
- **force_update** (Number) A counter that triggers an update even if no relevant parameters have been changed. See the [spec](https://github.com/docker/swarmkit/blob/master/api/specs.proto#L126).
- **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](#nestedblock--task_spec--log_driver))
- **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](#nestedblock--task_spec--placement))
- **resources** (Block List, Max: 1) Resource requirements which apply to each individual container created as part of the service (see [below for nested schema](#nestedblock--task_spec--resources))
- **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](#nestedblock--task_spec--restart_policy))
- **runtime** (String) Runtime is the type of runtime specified for the task executor. See the [types](https://github.com/moby/moby/blob/master/api/types/swarm/runtime.go).
<a id="nestedblock--task_spec--container_spec"></a>
### Nested Schema for `task_spec.container_spec`
Required:
- **image** (String) The image name to use for the containers of the service
Optional:
- **args** (List of String) Arguments to the command
- **command** (List of String) The command to be run in the image
- **configs** (Block Set) References to zero or more configs that will be exposed to the service (see [below for nested schema](#nestedblock--task_spec--container_spec--configs))
- **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](#nestedblock--task_spec--container_spec--dns_config))
- **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](#nestedblock--task_spec--container_spec--healthcheck))
- **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](#nestedblock--task_spec--container_spec--hosts))
- **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](#nestedblock--task_spec--container_spec--labels))
- **mounts** (Block Set) Specification for mounts to be added to containers created as part of the service (see [below for nested schema](#nestedblock--task_spec--container_spec--mounts))
- **privileges** (Block List, Max: 1) Security options for the container (see [below for nested schema](#nestedblock--task_spec--container_spec--privileges))
- **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](#nestedblock--task_spec--container_spec--secrets))
- **stop_grace_period** (String) Amount of time to wait for the container to terminate before forcefully removing it (ms|s|m|h)
- **stop_signal** (String) Signal to stop the container
- **user** (String) The user inside the container
<a id="nestedblock--task_spec--container_spec--configs"></a>
### 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`.
<a id="nestedblock--task_spec--container_spec--dns_config"></a>
### 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
<a id="nestedblock--task_spec--container_spec--healthcheck"></a>
### 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`.
<a id="nestedblock--task_spec--container_spec--hosts"></a>
### Nested Schema for `task_spec.container_spec.hosts`
Required:
- **host** (String) The name of the host
- **ip** (String) The ip of the host
<a id="nestedblock--task_spec--container_spec--labels"></a>
### Nested Schema for `task_spec.container_spec.labels`
Required:
- **label** (String) Name of the label
- **value** (String) Value of the label
<a id="nestedblock--task_spec--container_spec--mounts"></a>
### 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](#nestedblock--task_spec--container_spec--mounts--bind_options))
- **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](#nestedblock--task_spec--container_spec--mounts--tmpfs_options))
- **volume_options** (Block List, Max: 1) Optional configuration for the volume type (see [below for nested schema](#nestedblock--task_spec--container_spec--mounts--volume_options))
<a id="nestedblock--task_spec--container_spec--mounts--bind_options"></a>
### Nested Schema for `task_spec.container_spec.mounts.volume_options`
Optional:
- **propagation** (String) A propagation mode with the value
<a id="nestedblock--task_spec--container_spec--mounts--tmpfs_options"></a>
### Nested Schema for `task_spec.container_spec.mounts.volume_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
<a id="nestedblock--task_spec--container_spec--mounts--volume_options"></a>
### 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](#nestedblock--task_spec--container_spec--mounts--volume_options--labels))
- **no_copy** (Boolean) Populate volume with data from the target
<a id="nestedblock--task_spec--container_spec--mounts--volume_options--labels"></a>
### Nested Schema for `task_spec.container_spec.mounts.volume_options.labels`
Required:
- **label** (String) Name of the label
- **value** (String) Value of the label
<a id="nestedblock--task_spec--container_spec--privileges"></a>
### Nested Schema for `task_spec.container_spec.privileges`
Optional:
- **credential_spec** (Block List, Max: 1) CredentialSpec for managed service account (Windows only) (see [below for nested schema](#nestedblock--task_spec--container_spec--privileges--credential_spec))
- **se_linux_context** (Block List, Max: 1) SELinux labels of the container (see [below for nested schema](#nestedblock--task_spec--container_spec--privileges--se_linux_context))
<a id="nestedblock--task_spec--container_spec--privileges--credential_spec"></a>
### Nested Schema for `task_spec.container_spec.privileges.se_linux_context`
Optional:
- **file** (String) Load credential spec from this file
- **registry** (String) Load credential spec from this value in the Windows registry
<a id="nestedblock--task_spec--container_spec--privileges--se_linux_context"></a>
### 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
<a id="nestedblock--task_spec--container_spec--secrets"></a>
### 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
<a id="nestedblock--task_spec--log_driver"></a>
### 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
<a id="nestedblock--task_spec--placement"></a>
### 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](#nestedblock--task_spec--placement--platforms))
- **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
<a id="nestedblock--task_spec--placement--platforms"></a>
### Nested Schema for `task_spec.placement.platforms`
Required:
- **architecture** (String) The architecture, e.g. `amd64`
- **os** (String) The operation system, e.g. `linux`
<a id="nestedblock--task_spec--resources"></a>
### 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](#nestedblock--task_spec--resources--limits))
- **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](#nestedblock--task_spec--resources--reservation))
<a id="nestedblock--task_spec--resources--limits"></a>
### 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
<a id="nestedblock--task_spec--resources--reservation"></a>
### 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](#nestedblock--task_spec--resources--reservation--generic_resources))
- **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
<a id="nestedblock--task_spec--resources--reservation--generic_resources"></a>
### Nested Schema for `task_spec.resources.reservation.nano_cpus`
Optional:
- **discrete_resources_spec** (Set of String) The Integer resources
- **named_resources_spec** (Set of String) The String resources
<a id="nestedblock--task_spec--restart_policy"></a>
### 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)
<a id="nestedblock--auth"></a>
### 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
<a id="nestedblock--converge_config"></a>
### 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`
<a id="nestedblock--endpoint_spec"></a>
### 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](#nestedblock--endpoint_spec--ports))
<a id="nestedblock--endpoint_spec--ports"></a>
### 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
<a id="nestedblock--labels"></a>
### Nested Schema for `labels`
Required:
- **label** (String) Name of the label
- **value** (String) Value of the label
<a id="nestedblock--mode"></a>
### 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](#nestedblock--mode--replicated))
<a id="nestedblock--mode--replicated"></a>
### Nested Schema for `mode.replicated`
Optional:
- **replicas** (Number) The amount of replicas of the service. Defaults to `1`
<a id="nestedblock--rollback_config"></a>
### 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`
<a id="nestedblock--update_config"></a>
### 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 | 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`:
```shell
#!/bin/bash
terraform import docker_service.foo id
```
### Example
Assuming you created a `service` as follows
```shell
#!/bin/bash
docker service create --name foo -p 8080:80 nginx
# prints th ID
4pcphbxkfn2rffhbhe6czytgi
```
you provide the definition for the resource as follows
```terraform
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
```shell
#!/bin/bash
terraform import docker_service.foo 4pcphbxkfn2rffhbhe6czytgi
```

77
docs/resources/volume.md Normal file
View file

@ -0,0 +1,77 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "docker_volume Resource - terraform-provider-docker"
subcategory: ""
description: |-
Creates and destroys a volume in Docker. This can be used alongside docker_container container.md to prepare volumes that can be shared across containers.
---
<!-- Bug: Type and Name are switched -->
# docker_volume (Resource)
Creates and destroys a volume in Docker. This can be used alongside [docker_container](container.md) to prepare volumes that can be shared across containers.
## Example Usage
```terraform
resource "docker_volume" "shared_volume" {
name = "shared_volume"
}
```
<!-- schema generated by tfplugindocs -->
## Schema
### Optional
- **driver** (String) Driver type for the volume. Defaults to `local`.
- **driver_opts** (Map of String) Options specific to the driver.
- **id** (String) The ID of this resource.
- **labels** (Block Set) User-defined key/value metadata (see [below for nested schema](#nestedblock--labels))
- **name** (String) The name of the Docker volume (will be generated if not provided).
### Read-Only
- **mountpoint** (String) The mountpoint of the volume.
<a id="nestedblock--labels"></a>
### Nested Schema for `labels`
Required:
- **label** (String) Name of the label
- **value** (String) Value of the label
## Import
Import is supported using the following syntax by providing the `id`:
```shell
#!/bin/bash
terraform import docker_volume.foo id
```
### Example
Assuming you created a `volume` as follows
```shell
#!/bin/bash
docker volume create
# prints the long ID
524b0457aa2a87dd2b75c74c3e4e53f406974249e63ab3ed9bf21e5644f9dc7d
```
you provide the definition for the resource as follows
```terraform
resource "docker_volume" "foo" {
name = "524b0457aa2a87dd2b75c74c3e4e53f406974249e63ab3ed9bf21e5644f9dc7d"
}
```
then the import command is as follows
```shell
#!/bin/bash
terraform import docker_volume.foo 524b0457aa2a87dd2b75c74c3e4e53f406974249e63ab3ed9bf21e5644f9dc7d
```

9
examples/README.md Normal file
View file

@ -0,0 +1,9 @@
# Examples
This directory contains examples that are mostly used for documentation, but can also be run/tested manually via the Terraform CLI.
The document generation tool looks for files in the following locations by default. All other *.tf files besides the ones mentioned below are ignored by the documentation tool. This is useful for creating examples that can run and/or ar testable even if some parts are not relevant for the documentation.
* **provider/provider.tf** example file for the provider index page
* **data-sources/<full data source name>/data-source.tf** example file for the named data source page
* **resources/<full resource name>/resource.tf** example file for the named data source page

View file

@ -0,0 +1,3 @@
data "docker_network" "main" {
name = "main"
}

View file

@ -0,0 +1,9 @@
### With alias
data "docker_plugin" "by_alias" {
alias = "sample-volume-plugin:latest"
}
### With ID
data "docker_plugin" "by_id" {
id = "e9a9db917b3bfd6706b5d3a66d4bceb9f"
}

View file

@ -0,0 +1,8 @@
data "docker_registry_image" "ubuntu" {
name = "ubuntu:precise"
}
resource "docker_image" "ubuntu" {
name = data.docker_registry_image.ubuntu.name
pull_triggers = [data.docker_registry_image.ubuntu.sha256_digest]
}

View file

@ -0,0 +1,11 @@
provider "docker" {
host = "tcp://your-host-ip:2376/"
# -> specify either
cert_path = pathexpand("~/.docker")
# -> or the following
ca_material = file(pathexpand("~/.docker/ca.pem")) # this can be omitted
cert_material = file(pathexpand("~/.docker/cert.pem"))
key_material = file(pathexpand("~/.docker/key.pem"))
}

View file

@ -0,0 +1,27 @@
provider "docker" {
host = "tcp://localhost:2376"
registry_auth {
address = "registry.hub.docker.com"
config_file = pathexpand("~/.docker/config.json")
}
registry_auth {
address = "registry.my.company.com"
config_file_content = var.plain_content_of_config_file
}
registry_auth {
address = "quay.io:8181"
username = "someuser"
password = "somepass"
}
}
data "docker_registry_image" "quay" {
name = "myorg/privateimage"
}
data "docker_registry_image" "quay" {
name = "quay.io:8181/myorg/privateimage"
}

View file

@ -0,0 +1,9 @@
{
"auths": {
"repo.mycompany:8181": {
"auth": "dXNlcjpwYXNz="
},
"otherrepo.other-company:8181": {}
},
"credsStore": "osxkeychain"
}

View file

@ -0,0 +1,23 @@
terraform {
required_providers {
docker = {
source = "kreuzwerker/docker"
version = "2.11.0"
}
}
}
provider "docker" {
host = "unix:///var/run/docker.sock"
}
# Pulls the image
resource "docker_image" "ubuntu" {
name = "ubuntu:latest"
}
# Create a container
resource "docker_container" "foo" {
image = docker_image.ubuntu.latest
name = "foo"
}

View file

@ -0,0 +1,15 @@
provider "docker" {
version = "~> 2.11.0"
host = "unix:///var/run/docker.sock"
}
# Pulls the image
resource "docker_image" "ubuntu" {
name = "ubuntu:latest"
}
# Create a container
resource "docker_container" "foo" {
image = docker_image.ubuntu.latest
name = "foo"
}

View file

@ -0,0 +1,23 @@
terraform {
required_providers {
docker = {
source = "kreuzwerker/docker"
version = "2.11.0"
}
}
}
provider "docker" {
host = "unix:///var/run/docker.sock"
}
# Pulls the image
resource "docker_image" "ubuntu" {
name = "ubuntu:latest"
}
# Create a container
resource "docker_container" "foo" {
image = docker_image.ubuntu.latest
name = "foo"
}

View file

@ -0,0 +1,5 @@
{
"server": {
"public_port": ${port}
}
}

View file

@ -0,0 +1,4 @@
#!/bin/bash
printf '{"a":"b"}' | docker config create foo -
# prints the id
08c26c477474478d971139f750984775a7f019dbe8a2e7f09d66a187c009e66d

View file

@ -0,0 +1,2 @@
#!/bin/bash
terraform import docker_config.foo 08c26c477474478d971139f750984775a7f019dbe8a2e7f09d66a187c009e66d

View file

@ -0,0 +1,4 @@
resource "docker_config" "foo" {
name = "foo"
data = base64encode("{\"a\": \"b\"}")
}

View file

@ -0,0 +1,2 @@
#!/bin/bash
terraform import docker_config.foo id

View file

@ -0,0 +1,10 @@
resource "docker_config" "foo_config" {
name = "foo_config"
data = base64encode(
templatefile("${path.cwd}/foo.config.json.tpl",
{
port = 8080
}
)
)
}

View file

@ -0,0 +1,4 @@
resource "docker_config" "foo_config" {
name = "foo_config"
data = base64encode("{\"a\": \"b\"}")
}

View file

@ -0,0 +1,26 @@
resource "docker_config" "service_config" {
name = "${var.service_name}-config-${replace(timestamp(), ":", ".")}"
data = base64encode(
templatefile("${path.cwd}/foo.config.json.tpl",
{
port = 8080
}
)
)
lifecycle {
ignore_changes = ["name"]
create_before_destroy = true
}
}
resource "docker_service" "service" {
# ... other attributes omitted for brevity
configs = [
{
config_id = docker_config.service_config.id
config_name = docker_config.service_config.name
file_name = "/root/configs/configs.json"
},
]
}

View file

@ -0,0 +1,4 @@
#!/bin/bash
docker run --name foo -p8080:80 -d nginx
# prints the container ID
9a550c0f0163d39d77222d3efd58701b625d47676c25c686c95b5b92d1cba6fd

View file

@ -0,0 +1,2 @@
#!/bin/bash
terraform import docker_container.foo 9a550c0f0163d39d77222d3efd58701b625d47676c25c686c95b5b92d1cba6fd

View file

@ -0,0 +1,9 @@
resource "docker_container" "foo" {
name = "foo"
image = "nginx"
ports {
internal = "80"
external = "8080"
}
}

View file

@ -0,0 +1,2 @@
#!/bin/bash
terraform import docker_container.foo id

View file

@ -0,0 +1,10 @@
# Start a container
resource "docker_container" "ubuntu" {
name = "foo"
image = docker_image.ubuntu.latest
}
# Find the latest Ubuntu precise image.
resource "docker_image" "ubuntu" {
name = "ubuntu:precise"
}

View file

@ -0,0 +1,13 @@
resource "docker_image" "zoo" {
name = "zoo"
build {
path = "."
tag = ["zoo:develop"]
build_arg = {
foo : "zoo"
}
label = {
author : "zoo"
}
}
}

View file

@ -0,0 +1,8 @@
data "docker_registry_image" "ubuntu" {
name = "ubuntu:precise"
}
resource "docker_image" "ubuntu" {
name = data.docker_registry_image.ubuntu.name
pull_triggers = [data.docker_registry_image.ubuntu.sha256_digest]
}

View file

@ -0,0 +1,3 @@
resource "docker_image" "ubuntu" {
name = "ubuntu:precise"
}

View file

@ -0,0 +1,4 @@
#!/bin/bash
docker network create foo
# prints the long ID
87b57a9b91ecab2db2a6dbf38df74c67d7c7108cbe479d6576574ec2cd8c2d73

View file

@ -0,0 +1,2 @@
#!/bin/bash
terraform import docker_network.foo 87b57a9b91ecab2db2a6dbf38df74c67d7c7108cbe479d6576574ec2cd8c2d73

View file

@ -0,0 +1,3 @@
resource "docker_network" "foo" {
name = "foo"
}

View file

@ -0,0 +1,2 @@
#!/bin/bash
terraform import docker_network.foo id

View file

@ -0,0 +1,3 @@
resource "docker_network" "private_network" {
name = "my_network"
}

View file

@ -0,0 +1,2 @@
#!/bin/bash
terraform import docker_plugin.sample-volume-plugin "$(docker plugin inspect -f {{.ID}} tiborvass/sample-volume-plugin:latest)"

View file

@ -0,0 +1,16 @@
resource "docker_plugin" "sample-volume-plugin" {
name = "docker.io/tiborvass/sample-volume-plugin:latest"
}
resource "docker_plugin" "sample-volume-plugin" {
name = "tiborvass/sample-volume-plugin"
alias = "sample-volume-plugin"
enabled = false
grant_all_permissions = true
force_destroy = true
enable_timeout = 60
force_disable = true
env = [
"DEBUG=1"
]
}

View file

@ -0,0 +1,7 @@
resource "docker_registry_image" "helloworld" {
name = "helloworld:1.0"
build {
context = "pathToContextFolder"
}
}

View file

@ -0,0 +1,3 @@
{
"foo": "${secret}"
}

View file

@ -0,0 +1,3 @@
#!/bin/bash
# Docker secret cannot be imported as the secret data, once set, is never exposed again.

View file

@ -0,0 +1,4 @@
resource "docker_secret" "foo" {
name = "foo"
data = base64encode("{\"foo\": \"s3cr3t\"}")
}

View file

@ -0,0 +1,26 @@
resource "docker_secret" "service_secret" {
name = "${var.service_name}-secret-${replace(timestamp(), ":", ".")}"
data = base64encode(
templatefile("${path.cwd}/foo.secret.json.tpl",
{
secret = "s3cr3t"
}
)
)
lifecycle {
ignore_changes = ["name"]
create_before_destroy = true
}
}
resource "docker_service" "service" {
# ...
secrets = [
{
secret_id = docker_secret.service_secret.id
secret_name = docker_secret.service_secret.name
file_name = "/root/configs/configs.json"
},
]
}

View file

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

View file

@ -0,0 +1,2 @@
#!/bin/bash
terraform import docker_service.foo 4pcphbxkfn2rffhbhe6czytgi

View file

@ -0,0 +1,17 @@
resource "docker_service" "foo" {
name = "foo"
task_spec {
container_spec {
image = "nginx"
}
}
endpoint_spec {
ports {
target_port = "80"
published_port = "8080"
}
}
}

View file

@ -0,0 +1,2 @@
#!/bin/bash
terraform import docker_service.foo id

View file

@ -0,0 +1,210 @@
resource "docker_volume" "test_volume" {
name = "tftest-volume"
}
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 = "volume"
read_only = true
bind_options {
propagation = "private"
}
}
mounts {
# another mount
}
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
}
}
}

View file

@ -0,0 +1,2 @@
#!/bin/bash
docker service create -d -p 8080 --name foo-service repo.mycompany.com:8080/foo-service:v1

View file

@ -0,0 +1,15 @@
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"
}
}
}

View file

@ -0,0 +1,4 @@
#!/bin/bash
docker volume create
# prints the long ID
524b0457aa2a87dd2b75c74c3e4e53f406974249e63ab3ed9bf21e5644f9dc7d

View file

@ -0,0 +1,2 @@
#!/bin/bash
terraform import docker_volume.foo 524b0457aa2a87dd2b75c74c3e4e53f406974249e63ab3ed9bf21e5644f9dc7d

View file

@ -0,0 +1,3 @@
resource "docker_volume" "foo" {
name = "524b0457aa2a87dd2b75c74c3e4e53f406974249e63ab3ed9bf21e5644f9dc7d"
}

View file

@ -0,0 +1,2 @@
#!/bin/bash
terraform import docker_volume.foo id

View file

@ -0,0 +1,3 @@
resource "docker_volume" "shared_volume" {
name = "shared_volume"
}

View file

@ -13,11 +13,11 @@ resource "docker_image" "test" {
# scaffolding
variable "pub_key" {
type = "string"
type = string
}
provider "docker" {
version = "~> 1.2.0"
version = "~> 1.2.0"
}
resource "docker_image" "dind" {

1
go.mod
View file

@ -9,6 +9,7 @@ require (
github.com/docker/go-connections v0.4.0
github.com/docker/go-units v0.4.0
github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320
github.com/hashicorp/terraform-plugin-docs v0.4.0 // indirect
github.com/hashicorp/terraform-plugin-sdk/v2 v2.6.1
github.com/mitchellh/go-homedir v1.1.0
github.com/moby/buildkit v0.8.2 // indirect

520
go.sum

File diff suppressed because it is too large Load diff

View file

@ -12,69 +12,81 @@ import (
func dataSourceDockerNetwork() *schema.Resource {
return &schema.Resource{
Description: "`docker_network` provides details about a specific Docker Network.",
ReadContext: dataSourceDockerNetworkRead,
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Type: schema.TypeString,
Description: "The name of the Docker network.",
Required: true,
},
"id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"driver": {
Type: schema.TypeString,
Computed: true,
Type: schema.TypeString,
Description: "The driver of the Docker network. Possible values are `bridge`, `host`, `overlay`, `macvlan`. See [network docs](https://docs.docker.com/network/#network-drivers) for more details.",
Computed: true,
},
"options": {
Type: schema.TypeMap,
Computed: true,
Type: schema.TypeMap,
Description: "Only available with bridge networks. See [bridge options docs](https://docs.docker.com/engine/reference/commandline/network_create/#bridge-driver-options) for more details.",
Computed: true,
},
"internal": {
Type: schema.TypeBool,
Computed: true,
Type: schema.TypeBool,
Description: "If `true`, the network is internal.",
Computed: true,
},
"ipam_config": {
Type: schema.TypeSet,
Computed: true,
Type: schema.TypeSet,
Description: "The IPAM configuration options",
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"subnet": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Type: schema.TypeString,
Description: "The subnet in CIDR form",
Optional: true,
ForceNew: true,
},
"ip_range": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Type: schema.TypeString,
Description: "The ip range in CIDR form",
Optional: true,
ForceNew: true,
},
"gateway": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Type: schema.TypeString,
Description: "The IP address of the gateway",
Optional: true,
ForceNew: true,
},
"aux_address": {
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
Type: schema.TypeMap,
Description: "Auxiliary IPv4 or IPv6 addresses used by Network driver",
Optional: true,
ForceNew: true,
},
},
},
},
"scope": {
Type: schema.TypeString,
Computed: true,
Type: schema.TypeString,
Description: "Scope of the network. One of `swarm`, `global`, or `local`.",
Computed: true,
},
},
}

View file

@ -10,46 +10,52 @@ import (
func dataSourceDockerPlugin() *schema.Resource {
return &schema.Resource{
Description: "Reads the local Docker plugin. The plugin must be installed locally.",
Read: dataSourceDockerPluginRead,
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Optional: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
Type: schema.TypeString,
Description: "The ID of the plugin, which has precedence over the `alias` of both are given",
Optional: true,
},
"alias": {
Type: schema.TypeString,
Description: "The alias of the Docker plugin. If the tag is omitted, `:latest` is complemented to the attribute value.",
Optional: true,
Description: "Docker Plugin alias",
},
"name": {
Type: schema.TypeString,
Description: "The plugin name. If the tag is omitted, `:latest` is complemented to the attribute value.",
Computed: true,
},
"plugin_reference": {
Type: schema.TypeString,
Description: "Docker Plugin Reference",
Description: "The Docker Plugin Reference",
Computed: true,
},
"enabled": {
Type: schema.TypeBool,
Computed: true,
Type: schema.TypeBool,
Description: "If `true` the plugin is enabled",
Computed: true,
},
"grant_all_permissions": {
Type: schema.TypeBool,
Computed: true,
Description: "If true, grant all permissions necessary to run the plugin",
Computed: true,
},
"env": {
Type: schema.TypeSet,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
Type: schema.TypeSet,
Description: "The environment variables in the form of `KEY=VALUE`, e.g. `DEBUG=0`",
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
}
}
var errDataSourceKeyIsMissing = errors.New("One of id or alias must be assigned")
var errDataSourceKeyIsMissing = errors.New("one of id or alias must be assigned")
func getDataSourcePluginKey(d *schema.ResourceData) (string, error) {
id, idOK := d.GetOk("id")

View file

@ -19,17 +19,21 @@ import (
func dataSourceDockerRegistryImage() *schema.Resource {
return &schema.Resource{
Description: "Reads the image metadata from a Docker Registry. Used in conjunction with the [docker_image](../resources/image.md) resource to keep an image up to date on the latest available version of the tag.",
ReadContext: dataSourceDockerRegistryImageRead,
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Type: schema.TypeString,
Description: "The name of the Docker image, including any tags. e.g. `alpine:latest`",
Required: true,
},
"sha256_digest": {
Type: schema.TypeString,
Computed: true,
Type: schema.TypeString,
Description: "The content digest of the image, as stored in the registry.",
Computed: true,
},
},
}
@ -87,6 +91,7 @@ func getImageDigest(registry, image, tag, username, password string, fallback bo
// cuz we don't have a valid certs for this case
if env, okEnv := os.LookupEnv("TF_ACC"); okEnv {
if i, errConv := strconv.Atoi(env); errConv == nil && i >= 1 {
// DevSkim: ignore DS440000
cfg := &tls.Config{
InsecureSkipVerify: true,
}

View file

@ -220,7 +220,7 @@ func providerSetToRegistryAuth(authList []interface{}) (*AuthConfigs, error) {
}
authFileConfig, err := c.GetAuthConfig(registryHostname)
if err != nil {
return nil, fmt.Errorf("Couldn't find registry config for '%s' in file content", registryHostname)
return nil, fmt.Errorf("couldn't find registry config for '%s' in file content", registryHostname)
}
authConfig.Username = authFileConfig.Username
authConfig.Password = authFileConfig.Password
@ -278,7 +278,9 @@ func loadConfigFile(configData io.Reader) (*configfile.ConfigFile, error) {
// Copied from github.com/docker/docker/registry.ConvertToHostname to reduce dependencies.
func convertToHostname(url string) string {
stripped := url
// DevSkim: ignore DS137138
if strings.HasPrefix(url, "http://") {
// DevSkim: ignore DS137138
stripped = strings.TrimPrefix(url, "http://")
} else if strings.HasPrefix(url, "https://") {
stripped = strings.TrimPrefix(url, "https://")

View file

@ -12,6 +12,8 @@ import (
func resourceDockerConfig() *schema.Resource {
return &schema.Resource{
Description: "Manages the configs of a Docker service in a swarm.",
CreateContext: resourceDockerConfigCreate,
ReadContext: resourceDockerConfigRead,
DeleteContext: resourceDockerConfigDelete,
@ -31,7 +33,6 @@ func resourceDockerConfig() *schema.Resource {
Type: schema.TypeString,
Description: "Base64-url-safe-encoded config data",
Required: true,
Sensitive: true,
ForceNew: true,
ValidateDiagFunc: validateStringIsBase64Encoded(),
},

File diff suppressed because it is too large Load diff

View file

@ -849,7 +849,7 @@ func resourceDockerContainerDelete(ctx context.Context, d *schema.ResourceData,
func fetchDockerContainer(ctx context.Context, ID string, client *client.Client) (*types.Container, error) {
apiContainers, err := client.ContainerList(ctx, types.ContainerListOptions{All: true})
if err != nil {
return nil, fmt.Errorf("Error fetching container information from Docker: %s\n", err)
return nil, fmt.Errorf("error fetching container information from Docker: %s\n", err)
}
for _, apiContainer := range apiContainers {

View file

@ -452,12 +452,13 @@ func resourceDockerContainerV1() *schema.Resource {
},
"env": {
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
Type: schema.TypeSet,
Description: "The environment variables to in the form of `KEY=VALUE`, e.g. `DEBUG=0`",
Optional: true,
ForceNew: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"links": {
@ -807,7 +808,7 @@ func resourceDockerContainerMigrateState(
log.Println("[INFO] Found Docker Container State v0; migrating to v1")
return migrateDockerContainerMigrateStateV0toV1(is, meta)
default:
return is, fmt.Errorf("Unexpected schema version: %d", v)
return is, fmt.Errorf("unexpected schema version: %d", v)
}
}

View file

@ -199,9 +199,9 @@ func volumeSetToDockerVolumes(volumes *schema.Set) (map[string]struct{}, []strin
switch {
case len(fromContainer) == 0 && len(containerPath) == 0:
return retVolumeMap, retHostConfigBinds, retVolumeFromContainers, errors.New("Volume entry without container path or source container")
return retVolumeMap, retHostConfigBinds, retVolumeFromContainers, errors.New("volume entry without container path or source container")
case len(fromContainer) != 0 && len(containerPath) != 0:
return retVolumeMap, retHostConfigBinds, retVolumeFromContainers, errors.New("Both a container and a path specified in a volume entry")
return retVolumeMap, retHostConfigBinds, retVolumeFromContainers, errors.New("both a container and a path specified in a volume entry")
case len(fromContainer) != 0:
retVolumeFromContainers = append(retVolumeFromContainers, fromContainer)
case len(volumeName) != 0:

View file

@ -891,6 +891,7 @@ func TestAccDockerContainer_uploadAsBase64(t *testing.T) {
Config: testAccDockerContainerUploadBase64Config,
Check: resource.ComposeTestCheckFunc(
testAccContainerRunning("docker_container.foo", &c),
// DevSkim: ignore DS173237
testCheck("/terraform/test1.txt", "894fc3f56edf2d3a4c5fb5cb71df910f958a2ed8", "744"),
testCheck("/terraform/test2.txt", "foobar", "100644"),
resource.TestCheckResourceAttr("docker_container.foo", "name", "tf-test"),
@ -912,6 +913,7 @@ func TestAccDockerContainer_uploadAsBase64(t *testing.T) {
Config: testAccDockerContainerUploadBase64Config,
Check: resource.ComposeTestCheckFunc(
testAccContainerRunning("docker_container.foo", &c),
// DevSkim: ignore DS173237
testCheck("/terraform/test1.txt", "894fc3f56edf2d3a4c5fb5cb71df910f958a2ed8", "744"),
testCheck("/terraform/test2.txt", "foobar", "100644"),
resource.TestCheckResourceAttr("docker_container.foo", "name", "tf-test"),

View file

@ -6,6 +6,8 @@ import (
func resourceDockerImage() *schema.Resource {
return &schema.Resource{
Description: "Pulls a Docker image to a given Docker host from a Docker Registry.\n This resource will *not* pull new layers of the image automatically unless used in conjunction with [docker_registry_image](registry_image.md) data source to update the `pull_triggers` field.",
CreateContext: resourceDockerImageCreate,
ReadContext: resourceDockerImageRead,
UpdateContext: resourceDockerImageUpdate,
@ -13,22 +15,26 @@ func resourceDockerImage() *schema.Resource {
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
Type: schema.TypeString,
Description: "The name of the Docker image, including any tags or SHA256 repo digests.",
Required: true,
},
"latest": {
Type: schema.TypeString,
Computed: true,
Type: schema.TypeString,
Description: "The ID of the image.",
Computed: true,
},
"keep_locally": {
Type: schema.TypeBool,
Optional: true,
Type: schema.TypeBool,
Description: "If true, then the Docker image won't be deleted on destroy operation. If this is false, it will delete the image from the docker local storage on destroy operation.",
Optional: true,
},
"pull_trigger": {
Type: schema.TypeString,
Description: "A value which cause an image pull when changed",
Optional: true,
ForceNew: true,
ConflictsWith: []string{"pull_triggers"},
@ -36,29 +42,33 @@ func resourceDockerImage() *schema.Resource {
},
"pull_triggers": {
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
Type: schema.TypeSet,
Description: "List of values which cause an image pull when changed. This is used to store the image digest from the registry when using the [docker_registry_image](../data-sources/registry_image.md).",
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"output": {
Type: schema.TypeString,
Computed: true,
Type: schema.TypeString,
Deprecated: "Is unused and will be removed.",
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
Type: schema.TypeString,
Deprecated: "Is unused and will be removed.",
},
},
"force_remove": {
Type: schema.TypeBool,
Description: "Force remove the image when the resource is destroyed",
Description: "If true, then the image is removed forcibly when the resource is destroyed.",
Optional: true,
},
"build": {
Type: schema.TypeSet,
Description: "Configuration to build an image. Please see [docker build command reference](https://docs.docker.com/engine/reference/commandline/build/#options) too.",
Optional: true,
MaxItems: 1,
ConflictsWith: []string{"pull_triggers", "pull_trigger"},
@ -72,7 +82,7 @@ func resourceDockerImage() *schema.Resource {
},
"dockerfile": {
Type: schema.TypeString,
Description: "Name of the Dockerfile (Default is 'PATH/Dockerfile')",
Description: "Name of the Dockerfile. Defaults to `Dockerfile`.",
Optional: true,
Default: "Dockerfile",
ForceNew: true,
@ -92,7 +102,7 @@ func resourceDockerImage() *schema.Resource {
},
"remove": {
Type: schema.TypeBool,
Description: "Remove intermediate containers after a successful build (default true)",
Description: "Remove intermediate containers after a successful build. Defaults to `true`.",
Default: true,
Optional: true,
},

View file

@ -58,6 +58,7 @@ func resourceDockerImageRead(ctx context.Context, d *schema.ResourceData, meta i
foundImage := searchLocalImages(ctx, client, data, imageName)
if foundImage == nil {
log.Printf("[DEBUG] did not find image with name: %v", imageName)
d.SetId("")
return nil
}
@ -119,7 +120,7 @@ func removeImage(ctx context.Context, d *schema.ResourceData, client *client.Cli
imageName := d.Get("name").(string)
if imageName == "" {
return fmt.Errorf("Empty image name is not allowed")
return fmt.Errorf("empty image name is not allowed")
}
foundImage := searchLocalImages(ctx, client, data, imageName)
@ -140,7 +141,7 @@ func removeImage(ctx context.Context, d *schema.ResourceData, client *client.Cli
func fetchLocalImages(ctx context.Context, data *Data, client *client.Client) error {
images, err := client.ImageList(ctx, types.ImageListOptions{All: false})
if err != nil {
return fmt.Errorf("Unable to list Docker images: %s", err)
return fmt.Errorf("unable to list Docker images: %s", err)
}
if data.DockerImages == nil {
@ -246,7 +247,7 @@ func parseImageOptions(image string) internalPullImageOptions {
func findImage(ctx context.Context, imageName string, client *client.Client, authConfig *AuthConfigs) (*types.ImageSummary, error) {
if imageName == "" {
return nil, fmt.Errorf("Empty image name is not allowed")
return nil, fmt.Errorf("empty image name is not allowed")
}
var data Data
@ -261,7 +262,7 @@ func findImage(ctx context.Context, imageName string, client *client.Client, aut
}
if err := pullImage(ctx, &data, client, authConfig, imageName); err != nil {
return nil, fmt.Errorf("Unable to pull image %s: %s", imageName, err)
return nil, fmt.Errorf("unable to pull image %s: %s", imageName, err)
}
// update the data structure of the images
@ -274,7 +275,7 @@ func findImage(ctx context.Context, imageName string, client *client.Client, aut
return foundImage, nil
}
return nil, fmt.Errorf("Unable to find or pull image %s", imageName)
return nil, fmt.Errorf("unable to find or pull image %s", imageName)
}
func buildDockerImage(ctx context.Context, rawBuild map[string]interface{}, imageName string, client *client.Client) error {
@ -352,7 +353,7 @@ func decodeBuildMessages(response types.ImageBuildResponse) (string, error) {
var m jsonmessage.JSONMessage
err := dec.Decode(&m)
if err != nil {
return buf.String(), fmt.Errorf("Problem decoding message from docker daemon: %s", err)
return buf.String(), fmt.Errorf("problem decoding message from docker daemon: %s", err)
}
if err := m.Display(buf, false); err != nil {
@ -360,7 +361,7 @@ func decodeBuildMessages(response types.ImageBuildResponse) (string, error) {
}
if m.Error != nil {
buildErr = fmt.Errorf("Unable to build image")
buildErr = fmt.Errorf("unable to build image")
}
}
log.Printf("[DEBUG] %s", buf.String())

View file

@ -12,6 +12,8 @@ import (
func resourceDockerNetwork() *schema.Resource {
return &schema.Resource{
Description: "`docker_network` provides details about a specific Docker Network.",
CreateContext: resourceDockerNetworkCreate,
ReadContext: resourceDockerNetworkRead,
DeleteContext: resourceDockerNetworkDelete,
@ -21,108 +23,124 @@ func resourceDockerNetwork() *schema.Resource {
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Type: schema.TypeString,
Description: "The name of the Docker network.",
Required: true,
ForceNew: true,
},
"labels": {
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Elem: labelSchema,
Type: schema.TypeSet,
Description: "User-defined key/value metadata",
Optional: true,
ForceNew: true,
Elem: labelSchema,
},
"check_duplicate": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Type: schema.TypeBool,
Description: "Requests daemon to check for networks with same name.",
Optional: true,
ForceNew: true,
},
"driver": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
Type: schema.TypeString,
Description: "The driver of the Docker network. Possible values are `bridge`, `host`, `overlay`, `macvlan`. See [network docs](https://docs.docker.com/network/#network-drivers) for more details.",
Optional: true,
ForceNew: true,
Computed: true,
},
"options": {
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
Computed: true,
Type: schema.TypeMap,
Description: "Only available with bridge networks. See [bridge options docs](https://docs.docker.com/engine/reference/commandline/network_create/#bridge-driver-options) for more details.",
Optional: true,
ForceNew: true,
Computed: true,
},
"internal": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
ForceNew: true,
Type: schema.TypeBool,
Description: "Whether the network is internal.",
Optional: true,
Computed: true,
ForceNew: true,
},
"attachable": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Type: schema.TypeBool,
Description: "Enable manual container attachment to the network.",
Optional: true,
ForceNew: true,
},
"ingress": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Type: schema.TypeBool,
Description: "Create swarm routing-mesh network. Defaults to `false`.",
Optional: true,
ForceNew: true,
},
"ipv6": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Type: schema.TypeBool,
Description: "Enable IPv6 networking. Defaults to `false`.",
Optional: true,
ForceNew: true,
},
"ipam_driver": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "default",
Type: schema.TypeString,
Description: "Driver used by the custom IP scheme of the network. Defaults to `default`",
Default: "default",
Optional: true,
ForceNew: true,
},
"ipam_config": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
ForceNew: true,
Type: schema.TypeSet,
Description: "The IPAM configuration options",
Optional: true,
Computed: true,
ForceNew: true,
// DiffSuppressFunc: suppressIfIPAMConfigWithIpv6Changes(),
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"subnet": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Type: schema.TypeString,
Description: "The subnet in CIDR form",
Optional: true,
ForceNew: true,
},
"ip_range": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Type: schema.TypeString,
Description: "The ip range in CIDR form",
Optional: true,
ForceNew: true,
},
"gateway": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Type: schema.TypeString,
Description: "The IP address of the gateway",
Optional: true,
ForceNew: true,
},
"aux_address": {
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
Type: schema.TypeMap,
Description: "Auxiliary IPv4 or IPv6 addresses used by Network driver",
Optional: true,
ForceNew: true,
},
},
},
},
"scope": {
Type: schema.TypeString,
Computed: true,
Type: schema.TypeString,
Description: "Scope of the network. One of `swarm`, `global`, or `local`.",
Computed: true,
},
},
SchemaVersion: 1,

View file

@ -6,6 +6,8 @@ import (
func resourceDockerPlugin() *schema.Resource {
return &schema.Resource{
Description: "Manages the lifecycle of a Docker plugin.",
Create: resourceDockerPluginCreate,
Read: resourceDockerPluginRead,
Update: resourceDockerPluginUpdate,
@ -13,29 +15,31 @@ func resourceDockerPlugin() *schema.Resource {
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Description: "Docker Plugin name",
Required: true,
ForceNew: true,
Description: "Docker Plugin name",
DiffSuppressFunc: diffSuppressFuncPluginName,
ValidateFunc: validateFuncPluginName,
},
"alias": {
Type: schema.TypeString,
Description: "Docker Plugin alias",
Computed: true,
Optional: true,
ForceNew: true,
Description: "Docker Plugin alias",
DiffSuppressFunc: func(k, oldV, newV string, d *schema.ResourceData) bool {
return complementTag(oldV) == complementTag(newV)
},
},
"enabled": {
Type: schema.TypeBool,
Optional: true,
Default: true,
Type: schema.TypeBool,
Description: "If `true` the plugin is enabled. Defaults to `true`",
Default: true,
Optional: true,
},
"grant_all_permissions": {
Type: schema.TypeBool,
@ -45,18 +49,21 @@ func resourceDockerPlugin() *schema.Resource {
},
"grant_permissions": {
Type: schema.TypeSet,
Description: "Grant specific permissions only",
Optional: true,
ConflictsWith: []string{"grant_all_permissions"},
Set: dockerPluginGrantPermissionsSetFunc,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
Type: schema.TypeString,
Description: "The name of the permission",
Required: true,
},
"value": {
Type: schema.TypeSet,
Required: true,
Type: schema.TypeSet,
Description: "The value of the permission",
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
@ -65,10 +72,11 @@ func resourceDockerPlugin() *schema.Resource {
},
},
"env": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
Type: schema.TypeSet,
Description: "The environment variables in the form of `KEY=VALUE`, e.g. `DEBUG=0`",
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"plugin_reference": {
Type: schema.TypeString,
@ -77,18 +85,19 @@ func resourceDockerPlugin() *schema.Resource {
},
"force_destroy": {
Type: schema.TypeBool,
Optional: true,
Type: schema.TypeBool,
Description: "If true, then the plugin is destroyed forcibly",
Optional: true,
},
"enable_timeout": {
Type: schema.TypeInt,
Optional: true,
Description: "HTTP client timeout to enable the plugin",
Optional: true,
},
"force_disable": {
Type: schema.TypeBool,
Description: "If true, then the plugin is disabled forcibly",
Optional: true,
Description: "If true, then the plugin is disabled forcibly when the plugin is disabled",
},
},
}

View file

@ -8,6 +8,8 @@ import (
func resourceDockerRegistryImage() *schema.Resource {
return &schema.Resource{
Description: "Manages the lifecycle of docker image/tag in a registry.",
CreateContext: resourceDockerRegistryImageCreate,
ReadContext: resourceDockerRegistryImageRead,
DeleteContext: resourceDockerRegistryImageDelete,
@ -15,189 +17,226 @@ func resourceDockerRegistryImage() *schema.Resource {
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Type: schema.TypeString,
Description: "The name of the Docker image.",
Required: true,
ForceNew: true,
},
"keep_remotely": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Type: schema.TypeBool,
Description: "If true, then the Docker image won't be deleted on destroy operation. If this is false, it will delete the image from the docker registry on destroy operation. Defaults to `false`",
Default: false,
Optional: true,
},
"build": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Type: schema.TypeList,
Description: "Definition for building the image",
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"suppress_output": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Type: schema.TypeBool,
Description: "Suppress the build output and print image ID on success",
Optional: true,
ForceNew: true,
},
"remote_context": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Type: schema.TypeString,
Description: "A Git repository URI or HTTP/HTTPS context URI",
Optional: true,
ForceNew: true,
},
"no_cache": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Type: schema.TypeBool,
Description: "Do not use the cache when building the image",
Optional: true,
ForceNew: true,
},
"remove": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Type: schema.TypeBool,
Description: "Remove intermediate containers after a successful build (default behavior)",
Optional: true,
ForceNew: true,
},
"force_remove": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Type: schema.TypeBool,
Description: "Always remove intermediate containers",
Optional: true,
ForceNew: true,
},
"pull_parent": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Type: schema.TypeBool,
Description: "Attempt to pull the image even if an older image exists locally",
Optional: true,
ForceNew: true,
},
"isolation": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Type: schema.TypeString,
Description: "Isolation represents the isolation technology of a container. The supported values are ",
Optional: true,
ForceNew: true,
},
"cpu_set_cpus": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Type: schema.TypeString,
Description: "CPUs in which to allow execution (e.g., `0-3`, `0`, `1`)",
Optional: true,
ForceNew: true,
},
"cpu_set_mems": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Type: schema.TypeString,
Description: "MEMs in which to allow execution (`0-3`, `0`, `1`)",
Optional: true,
ForceNew: true,
},
"cpu_shares": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Type: schema.TypeInt,
Description: "CPU shares (relative weight)",
Optional: true,
ForceNew: true,
},
"cpu_quota": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Type: schema.TypeInt,
Description: "Microseconds of CPU time that the container can get in a CPU period",
Optional: true,
ForceNew: true,
},
"cpu_period": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Type: schema.TypeInt,
Description: "The length of a CPU period in microseconds",
Optional: true,
ForceNew: true,
},
"memory": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Type: schema.TypeInt,
Description: "Set memory limit for build",
Optional: true,
ForceNew: true,
},
"memory_swap": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Type: schema.TypeInt,
Description: "Total memory (memory + swap), -1 to enable unlimited swap",
Optional: true,
ForceNew: true,
},
"cgroup_parent": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Type: schema.TypeString,
Description: "Optional parent cgroup for the container",
Optional: true,
ForceNew: true,
},
"network_mode": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Type: schema.TypeString,
Description: "Set the networking mode for the RUN instructions during build",
Optional: true,
ForceNew: true,
},
"shm_size": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Type: schema.TypeInt,
Description: "Size of /dev/shm in bytes. The size must be greater than 0",
Optional: true,
ForceNew: true,
},
"dockerfile": {
Type: schema.TypeString,
Optional: true,
Default: "Dockerfile",
ForceNew: true,
Type: schema.TypeString,
Description: "Dockerfile file. Defaults to `Dockerfile`",
Default: "Dockerfile",
Optional: true,
ForceNew: true,
},
"ulimit": {
Type: schema.TypeList,
Optional: true,
Type: schema.TypeList,
Description: "Configuration for ulimits",
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Type: schema.TypeString,
Description: "type of ulimit, e.g. `nofile`",
Required: true,
ForceNew: true,
},
"hard": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
Type: schema.TypeInt,
Description: "soft limit",
Required: true,
ForceNew: true,
},
"soft": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
Type: schema.TypeInt,
Description: "hard limit",
Required: true,
ForceNew: true,
},
},
},
},
"build_args": {
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
Type: schema.TypeMap,
Description: "Pairs for build-time variables in the form TODO",
Optional: true,
ForceNew: true,
Elem: &schema.Schema{
Type: schema.TypeString,
Type: schema.TypeString,
Description: "The argument",
},
},
"auth_config": {
Type: schema.TypeList,
Optional: true,
Type: schema.TypeList,
Description: "The configuration for the autentication",
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"host_name": {
Type: schema.TypeString,
Required: true,
Type: schema.TypeString,
Description: "hostname of the registry",
Required: true,
},
"user_name": {
Type: schema.TypeString,
Optional: true,
Type: schema.TypeString,
Description: "the registry user name",
Optional: true,
},
"password": {
Type: schema.TypeString,
Optional: true,
Type: schema.TypeString,
Description: "the registry password",
Optional: true,
},
"auth": {
Type: schema.TypeString,
Optional: true,
Type: schema.TypeString,
Description: "the auth token",
Optional: true,
},
"email": {
Type: schema.TypeString,
Optional: true,
Type: schema.TypeString,
Description: "the user emal",
Optional: true,
},
"server_address": {
Type: schema.TypeString,
Optional: true,
Type: schema.TypeString,
Description: "the server address",
Optional: true,
},
"identity_token": {
Type: schema.TypeString,
Optional: true,
Type: schema.TypeString,
Description: "the identity token",
Optional: true,
},
"registry_token": {
Type: schema.TypeString,
Optional: true,
Type: schema.TypeString,
Description: "the registry token",
Optional: true,
},
},
},
},
"context": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Type: schema.TypeString,
Description: "The path to the context folder",
Required: true,
ForceNew: true,
StateFunc: func(val interface{}) string {
// the context hash is stored to identify changes in the context files
dockerContextTarPath, _ := buildDockerImageContextTar(val.(string))
@ -207,74 +246,89 @@ func resourceDockerRegistryImage() *schema.Resource {
},
},
"labels": {
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
Type: schema.TypeMap,
Description: "User-defined key/value metadata",
Optional: true,
ForceNew: true,
Elem: &schema.Schema{
Type: schema.TypeString,
Type: schema.TypeString,
Description: "The key/value pair",
},
},
"squash": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Type: schema.TypeBool,
Description: "If true the new layers are squashed into a new image with a single new layer",
Optional: true,
ForceNew: true,
},
"cache_from": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Type: schema.TypeList,
Description: "Images to consider as cache sources",
Optional: true,
ForceNew: true,
Elem: &schema.Schema{
Type: schema.TypeString,
Type: schema.TypeString,
Description: "The image",
},
},
"security_opt": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Type: schema.TypeList,
Description: "The security options",
Optional: true,
ForceNew: true,
Elem: &schema.Schema{
Type: schema.TypeString,
Type: schema.TypeString,
Description: "The option",
},
},
"extra_hosts": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Type: schema.TypeList,
Description: "A list of hostnames/IP mappings to add to the containers /etc/hosts file. Specified in the form [\"hostname:IP\"]",
Optional: true,
ForceNew: true,
Elem: &schema.Schema{
Type: schema.TypeString,
Type: schema.TypeString,
Description: "",
},
},
"target": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Type: schema.TypeString,
Description: "Set the target build stage to build",
Optional: true,
ForceNew: true,
},
"session_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Type: schema.TypeString,
Description: "Set an ID for the build session",
Optional: true,
ForceNew: true,
},
"platform": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Type: schema.TypeString,
Description: "Set platform if server is multi-platform capable",
Optional: true,
ForceNew: true,
},
"version": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Type: schema.TypeString,
Description: "Version of the unerlying builder to use",
Optional: true,
ForceNew: true,
},
"build_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Type: schema.TypeString,
Description: "BuildID is an optional identifier that can be passed together with the build request. The ",
Optional: true,
ForceNew: true,
},
},
},
},
"sha256_digest": {
Type: schema.TypeString,
Computed: true,
Type: schema.TypeString,
Description: "The sha256 digest of the image.",
Computed: true,
},
},
}

View file

@ -244,7 +244,7 @@ func buildDockerRegistryImage(ctx context.Context, client *client.Client, buildO
}
dockerContextTarPath, err := buildDockerImageContextTar(buildContext)
if err != nil {
return fmt.Errorf("Unable to build context %v", err)
return fmt.Errorf("unable to build context %v", err)
}
defer os.Remove(dockerContextTarPath)
dockerBuildContext, err := os.Open(dockerContextTarPath)
@ -271,12 +271,12 @@ func buildDockerImageContextTar(buildContext string) (string, error) {
// Create our Temp File: This will create a filename like /tmp/terraform-provider-docker-123456.tar
tmpFile, err := ioutil.TempFile(os.TempDir(), "terraform-provider-docker-*.tar")
if err != nil {
return "", fmt.Errorf("Cannot create temporary file - %v", err.Error())
return "", fmt.Errorf("cannot create temporary file - %v", err.Error())
}
defer tmpFile.Close()
if _, err = os.Stat(buildContext); err != nil {
return "", fmt.Errorf("Unable to read build context - %v", err.Error())
return "", fmt.Errorf("unable to read build context - %v", err.Error())
}
tw := tar.NewWriter(tmpFile)
@ -402,6 +402,7 @@ func deleteDockerRegistryImage(pushOpts internalPushImageOptions, sha256Digest,
// cuz we don't have a valid certs for this case
if env, okEnv := os.LookupEnv("TF_ACC"); okEnv {
if i, errConv := strconv.Atoi(env); errConv == nil && i >= 1 {
// DevSkim: ignore DS440000
cfg := &tls.Config{
InsecureSkipVerify: true,
}
@ -504,7 +505,7 @@ func getImageDigestWithFallback(opts internalPushImageOptions, username, passwor
if err != nil {
digest, err = getImageDigest(opts.Registry, opts.Repository, opts.Tag, username, password, true)
if err != nil {
return "", fmt.Errorf("Unable to get digest: %s", err)
return "", fmt.Errorf("unable to get digest: %s", err)
}
}
return digest, nil

View file

@ -57,6 +57,7 @@ func TestAccDockerRegistryImageResource_mapping(t *testing.T) {
Soft: int64(2),
}), "Ulimits")
assert(len(options.BuildArgs) == 1, "BuildArgs")
// DevSkim: ignore DS137138
assert(*options.BuildArgs["HTTP_PROXY"] == "http://10.20.30.2:1234", "BuildArgs")
assert(len(options.AuthConfigs) == 1, "AuthConfigs")
assert(reflect.DeepEqual(options.AuthConfigs["foo.host"], types.AuthConfig{

View file

@ -12,6 +12,8 @@ import (
func resourceDockerSecret() *schema.Resource {
return &schema.Resource{
Description: "Manages the secrets of a Docker service in a swarm.",
CreateContext: resourceDockerSecretCreate,
ReadContext: resourceDockerSecretRead,
DeleteContext: resourceDockerSecretDelete,
@ -34,10 +36,11 @@ func resourceDockerSecret() *schema.Resource {
},
"labels": {
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Elem: labelSchema,
Type: schema.TypeSet,
Description: "User-defined key/value metadata",
Optional: true,
ForceNew: true,
Elem: labelSchema,
},
},
SchemaVersion: 1,
@ -75,9 +78,10 @@ func resourceDockerSecretV0() *schema.Resource {
},
"labels": {
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
Type: schema.TypeMap,
Description: "User-defined key/value metadata",
Optional: true,
ForceNew: true,
},
},
}
@ -119,7 +123,7 @@ func resourceDockerSecretRead(ctx context.Context, d *schema.ResourceData, meta
d.SetId(secret.ID)
d.Set("name", secret.Spec.Name)
// Note mavogel: secret data is not exposed via the API
// TODO next major if we do not explicitly do not store it in the state we could import it, but BC
// TODO next major if we do not explicitly store it in the state we could import it, but BC
// d.Set("data", base64.StdEncoding.EncodeToString(secret.Spec.Data))
return nil
}

View file

@ -12,6 +12,8 @@ import (
// https://docs.docker.com/engine/api/v1.32/#operation/ServiceCreate
func resourceDockerService() *schema.Resource {
return &schema.Resource{
Description: "This resource manages the lifecycle of a Docker service. By default, the creation, update and delete of services are detached.\n With the [Converge Config](#convergeconfig) 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.",
CreateContext: resourceDockerServiceCreate,
ReadContext: resourceDockerServiceRead,
UpdateContext: resourceDockerServiceUpdate,
@ -22,25 +24,29 @@ func resourceDockerService() *schema.Resource {
Schema: map[string]*schema.Schema{
"auth": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
MaxItems: 1,
Type: schema.TypeList,
Description: "Configuration for the authentication for pulling the images of the service",
Optional: true,
ForceNew: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"server_address": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Type: schema.TypeString,
Description: "The address of the server for the authentication",
Required: true,
ForceNew: true,
},
"username": {
Type: schema.TypeString,
Description: "The username",
Optional: true,
ForceNew: true,
DefaultFunc: schema.EnvDefaultFunc("DOCKER_REGISTRY_USER", ""),
},
"password": {
Type: schema.TypeString,
Description: "The password",
Optional: true,
ForceNew: true,
DefaultFunc: schema.EnvDefaultFunc("DOCKER_REGISTRY_PASS", ""),
@ -323,30 +329,30 @@ func resourceDockerService() *schema.Resource {
},
"interval": {
Type: schema.TypeString,
Description: "Time between running the check (ms|s|m|h)",
Optional: true,
Description: "Time between running the check (ms|s|m|h). Defaults to `0s`.",
Default: "0s",
Optional: true,
ValidateDiagFunc: validateDurationGeq0(),
},
"timeout": {
Type: schema.TypeString,
Description: "Maximum time to allow one check to run (ms|s|m|h)",
Optional: true,
Description: "Maximum time to allow one check to run (ms|s|m|h). Defaults to `0s`.",
Default: "0s",
Optional: true,
ValidateDiagFunc: validateDurationGeq0(),
},
"start_period": {
Type: schema.TypeString,
Description: "Start period for the container to initialize before counting retries towards unstable (ms|s|m|h)",
Optional: true,
Description: "Start period for the container to initialize before counting retries towards unstable (ms|s|m|h). Defaults to `0s`.",
Default: "0s",
Optional: true,
ValidateDiagFunc: validateDurationGeq0(),
},
"retries": {
Type: schema.TypeInt,
Description: "Consecutive failures needed to report unhealthy",
Optional: true,
Description: "Consecutive failures needed to report unhealthy. Defaults to `0`",
Default: 0,
Optional: true,
ValidateDiagFunc: validateIntegerGeqThan(0),
},
},
@ -360,15 +366,17 @@ func resourceDockerService() *schema.Resource {
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ip": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Type: schema.TypeString,
Description: "The ip of the host",
Required: true,
ForceNew: true,
},
"host": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Type: schema.TypeString,
Description: "The name of the host",
Required: true,
ForceNew: true,
},
},
},
@ -425,21 +433,21 @@ func resourceDockerService() *schema.Resource {
},
"file_uid": {
Type: schema.TypeString,
Description: "Represents the file UID",
Optional: true,
Description: "Represents the file UID. Defaults to `0`",
Default: "0",
Optional: true,
},
"file_gid": {
Type: schema.TypeString,
Description: "Represents the file GID",
Optional: true,
Description: "Represents the file GID. Defaults to `0`",
Default: "0",
Optional: true,
},
"file_mode": {
Type: schema.TypeInt,
Description: "Represents represents the FileMode of the file",
Optional: true,
Description: "Represents represents the FileMode of the file. Defaults to `0o444`",
Default: 0o444,
Optional: true,
ValidateDiagFunc: validateIntegerGeqThan(0),
},
},
@ -468,21 +476,21 @@ func resourceDockerService() *schema.Resource {
},
"file_uid": {
Type: schema.TypeString,
Description: "Represents the file UID",
Optional: true,
Description: "Represents the file UID. Defaults to `0`.",
Default: "0",
Optional: true,
},
"file_gid": {
Type: schema.TypeString,
Description: "Represents the file GID",
Optional: true,
Description: "Represents the file GID. Defaults to `0`.",
Default: "0",
Optional: true,
},
"file_mode": {
Type: schema.TypeInt,
Description: "Represents represents the FileMode of the file",
Optional: true,
Description: "Represents represents the FileMode of the file. Defaults to `0o444`.",
Default: 0o444,
Optional: true,
ValidateDiagFunc: validateIntegerGeqThan(0),
},
},
@ -490,9 +498,9 @@ func resourceDockerService() *schema.Resource {
},
"isolation": {
Type: schema.TypeString,
Description: "Isolation technology of the containers running the service. (Windows only)",
Optional: true,
Description: "Isolation technology of the containers running the service. (Windows only). Defaults to `default`.",
Default: "default",
Optional: true,
ValidateDiagFunc: validateStringMatchesPattern(`^(default|process|hyperv)$`),
},
},
@ -515,7 +523,7 @@ func resourceDockerService() *schema.Resource {
Schema: map[string]*schema.Schema{
"nano_cpus": {
Type: schema.TypeInt,
Description: "CPU shares in units of 1/1e9 (or 10^-9) of the CPU. Should be at least 1000000",
Description: "CPU shares in units of `1/1e9` (or `10^-9`) of the CPU. Should be at least 1000000",
Optional: true,
},
"memory_bytes": {
@ -545,7 +553,7 @@ func resourceDockerService() *schema.Resource {
},
"generic_resources": {
Type: schema.TypeList,
Description: "User-defined resources can be either Integer resources (e.g, SSD=3) or String resources (e.g, GPU=UUID1)",
Description: "User-defined resources can be either Integer resources (e.g, `SSD=3`) or String resources (e.g, GPU=UUID1)",
MaxItems: 1,
Optional: true,
Elem: &schema.Resource{
@ -593,13 +601,13 @@ func resourceDockerService() *schema.Resource {
},
"max_attempts": {
Type: schema.TypeInt,
Description: "Maximum attempts to restart a given container before giving up (default value is 0, which is ignored)",
Description: "Maximum attempts to restart a given container before giving up (default value is `0`, which is ignored)",
Optional: true,
ValidateDiagFunc: validateIntegerGeqThan(0),
},
"window": {
Type: schema.TypeString,
Description: "The time window used to evaluate the restart policy (default value is 0, which is unbounded) (ms|s|m|h)",
Description: "The time window used to evaluate the restart policy (default value is `0`, which is unbounded) (ms|s|m|h)",
Optional: true,
ValidateDiagFunc: validateDurationGeq0(),
},
@ -616,7 +624,7 @@ func resourceDockerService() *schema.Resource {
Schema: map[string]*schema.Schema{
"constraints": {
Type: schema.TypeSet,
Description: "An array of constraints. e.g.: node.role==manager",
Description: "An array of constraints. e.g.: `node.role==manager`",
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
@ -630,7 +638,7 @@ func resourceDockerService() *schema.Resource {
},
"max_replicas": {
Type: schema.TypeInt,
Description: "Maximum number of replicas for per node (default value is 0, which is unlimited)",
Description: "Maximum number of replicas for per node (default value is `0`, which is unlimited)",
Optional: true,
ValidateDiagFunc: validateIntegerGeqThan(0),
},
@ -642,12 +650,12 @@ func resourceDockerService() *schema.Resource {
Schema: map[string]*schema.Schema{
"architecture": {
Type: schema.TypeString,
Description: "The architecture, e.g. amd64",
Description: "The architecture, e.g. `amd64`",
Required: true,
},
"os": {
Type: schema.TypeString,
Description: "The operation system, e.g. linux",
Description: "The operation system, e.g. `linux`",
Required: true,
},
},
@ -658,14 +666,14 @@ func resourceDockerService() *schema.Resource {
},
"force_update": {
Type: schema.TypeInt,
Description: "A counter that triggers an update even if no relevant parameters have been changed. See https://github.com/docker/swarmkit/blob/master/api/specs.proto#L126",
Description: "A counter that triggers an update even if no relevant parameters have been changed. See the [spec](https://github.com/docker/swarmkit/blob/master/api/specs.proto#L126).",
Optional: true,
Computed: true,
ValidateDiagFunc: validateIntegerGeqThan(0),
},
"runtime": {
Type: schema.TypeString,
Description: "Runtime is the type of runtime specified for the task executor. See https://github.com/moby/moby/blob/master/api/types/swarm/runtime.go",
Description: "Runtime is the type of runtime specified for the task executor. See the [types](https://github.com/moby/moby/blob/master/api/types/swarm/runtime.go).",
Optional: true,
Computed: true,
ValidateDiagFunc: validateStringMatchesPattern("^(container|plugin)$"),
@ -721,9 +729,9 @@ func resourceDockerService() *schema.Resource {
Schema: map[string]*schema.Schema{
"replicas": {
Type: schema.TypeInt,
Description: "The amount of replicas of the service",
Optional: true,
Description: "The amount of replicas of the service. Defaults to `1`",
Default: 1,
Optional: true,
ValidateDiagFunc: validateIntegerGeqThan(0),
},
},
@ -731,9 +739,9 @@ func resourceDockerService() *schema.Resource {
},
"global": {
Type: schema.TypeBool,
Description: "The global service mode",
Optional: true,
Description: "The global service mode. Defaults to `false`",
Default: false,
Optional: true,
ConflictsWith: []string{"mode.0.replicated", "converge_config"},
},
},
@ -748,44 +756,44 @@ func resourceDockerService() *schema.Resource {
Schema: map[string]*schema.Schema{
"parallelism": {
Type: schema.TypeInt,
Description: "Maximum number of tasks to be updated in one iteration",
Optional: true,
Description: "Maximum number of tasks to be updated in one iteration. Defaults to `1`",
Default: 1,
Optional: true,
ValidateDiagFunc: validateIntegerGeqThan(0),
},
"delay": {
Type: schema.TypeString,
Description: "Delay between task updates (ns|us|ms|s|m|h)",
Optional: true,
Description: "Delay between task updates (ns|us|ms|s|m|h). Defaults to `0s`.",
Default: "0s",
Optional: true,
ValidateDiagFunc: validateDurationGeq0(),
},
"failure_action": {
Type: schema.TypeString,
Description: "Action on update failure: pause | continue | rollback",
Optional: true,
Description: "Action on update failure: pause | continue | rollback. Defaults to `pause`.",
Default: "pause",
Optional: true,
ValidateDiagFunc: validateStringMatchesPattern("^(pause|continue|rollback)$"),
},
"monitor": {
Type: schema.TypeString,
Description: "Duration after each task update to monitor for failure (ns|us|ms|s|m|h)",
Optional: true,
Description: "Duration after each task update to monitor for failure (ns|us|ms|s|m|h). Defaults to `5s`.",
Default: "5s",
Optional: true,
ValidateDiagFunc: validateDurationGeq0(),
},
"max_failure_ratio": {
Type: schema.TypeString,
Description: "Failure rate to tolerate during an update",
Optional: true,
Description: "Failure rate to tolerate during an update. Defaults to `0.0`.",
Default: "0.0",
Optional: true,
ValidateDiagFunc: validateStringIsFloatRatio(),
},
"order": {
Type: schema.TypeString,
Description: "Update order: either 'stop-first' or 'start-first'",
Optional: true,
Description: "Update order: either 'stop-first' or 'start-first'. Defaults to `stop-first`.",
Default: "stop-first",
Optional: true,
ValidateDiagFunc: validateStringMatchesPattern("^(stop-first|start-first)$"),
},
},
@ -800,44 +808,44 @@ func resourceDockerService() *schema.Resource {
Schema: map[string]*schema.Schema{
"parallelism": {
Type: schema.TypeInt,
Description: "Maximum number of tasks to be rollbacked in one iteration",
Optional: true,
Description: "Maximum number of tasks to be rollbacked in one iteration. Defaults to `1`",
Default: 1,
Optional: true,
ValidateDiagFunc: validateIntegerGeqThan(0),
},
"delay": {
Type: schema.TypeString,
Description: "Delay between task rollbacks (ns|us|ms|s|m|h)",
Optional: true,
Description: "Delay between task rollbacks (ns|us|ms|s|m|h). Defaults to `0s`.",
Default: "0s",
Optional: true,
ValidateDiagFunc: validateDurationGeq0(),
},
"failure_action": {
Type: schema.TypeString,
Description: "Action on rollback failure: pause | continue",
Optional: true,
Description: "Action on rollback failure: pause | continue. Defaults to `pause`.",
Default: "pause",
Optional: true,
ValidateDiagFunc: validateStringMatchesPattern("(pause|continue)"),
},
"monitor": {
Type: schema.TypeString,
Description: "Duration after each task rollback to monitor for failure (ns|us|ms|s|m|h)",
Optional: true,
Description: "Duration after each task rollback to monitor for failure (ns|us|ms|s|m|h). Defaults to `5s`.",
Default: "5s",
Optional: true,
ValidateDiagFunc: validateDurationGeq0(),
},
"max_failure_ratio": {
Type: schema.TypeString,
Description: "Failure rate to tolerate during a rollback",
Optional: true,
Description: "Failure rate to tolerate during a rollback. Defaults to `0.0`.",
Default: "0.0",
Optional: true,
ValidateDiagFunc: validateStringIsFloatRatio(),
},
"order": {
Type: schema.TypeString,
Description: "Rollback order: either 'stop-first' or 'start-first'",
Optional: true,
Description: "Rollback order: either 'stop-first' or 'start-first'. Defaults to `stop-first`.",
Default: "stop-first",
Optional: true,
ValidateDiagFunc: validateStringMatchesPattern("(stop-first|start-first)"),
},
},
@ -871,9 +879,9 @@ func resourceDockerService() *schema.Resource {
},
"protocol": {
Type: schema.TypeString,
Description: "Rrepresents the protocol of a port: 'tcp', 'udp' or 'sctp'",
Optional: true,
Description: "Rrepresents the protocol of a port: 'tcp', 'udp' or 'sctp'. Defaults to `tcp`.",
Default: "tcp",
Optional: true,
ValidateDiagFunc: validateStringMatchesPattern(`^(tcp|udp|sctp)$`),
},
"target_port": {
@ -889,9 +897,9 @@ func resourceDockerService() *schema.Resource {
},
"publish_mode": {
Type: schema.TypeString,
Description: "Represents the mode in which the port is to be published: 'ingress' or 'host'",
Optional: true,
Description: "Represents the mode in which the port is to be published: 'ingress' or 'host'. Defaults to `ingress`.",
Default: "ingress",
Optional: true,
ValidateDiagFunc: validateStringMatchesPattern(`^(host|ingress)$`),
},
},
@ -910,16 +918,16 @@ func resourceDockerService() *schema.Resource {
Schema: map[string]*schema.Schema{
"delay": {
Type: schema.TypeString,
Description: "The interval to check if the desired state is reached (ms|s). Default: 7s",
Optional: true,
Description: "The interval to check if the desired state is reached (ms|s). Defaults to `7s`.",
Default: "7s",
Optional: true,
ValidateDiagFunc: validateDurationGeq0(),
},
"timeout": {
Type: schema.TypeString,
Description: "The timeout of the service to reach the desired state (s|m). Default: 3m",
Optional: true,
Description: "The timeout of the service to reach the desired state (s|m). Defaults to `3m`",
Default: "3m",
Optional: true,
ValidateDiagFunc: validateDurationGeq0(),
},
},

View file

@ -594,6 +594,7 @@ func authToServiceAuth(auths []interface{}) types.AuthConfig {
// fromRegistryAuth extract the desired AuthConfiguration for the given image
func fromRegistryAuth(image string, authConfigs map[string]types.AuthConfig) types.AuthConfig {
// Remove normalized prefixes to simplify substring
// DevSkim: ignore DS137138
image = strings.Replace(strings.Replace(image, "http://", "", 1), "https://", "", 1)
// Get the registry with optional port
lastBin := strings.Index(image, "/")

View file

@ -21,6 +21,8 @@ const (
func resourceDockerVolume() *schema.Resource {
return &schema.Resource{
Description: "Creates and destroys a volume in Docker. This can be used alongside [docker_container](container.md) to prepare volumes that can be shared across containers.",
CreateContext: resourceDockerVolumeCreate,
ReadContext: resourceDockerVolumeRead,
DeleteContext: resourceDockerVolumeDelete,
@ -30,31 +32,36 @@ func resourceDockerVolume() *schema.Resource {
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Type: schema.TypeString,
Description: "The name of the Docker volume (will be generated if not provided).",
Optional: true,
Computed: true,
ForceNew: true,
},
"labels": {
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Elem: labelSchema,
Type: schema.TypeSet,
Description: "User-defined key/value metadata",
Optional: true,
ForceNew: true,
Elem: labelSchema,
},
"driver": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Type: schema.TypeString,
Description: "Driver type for the volume. Defaults to `local`.",
Optional: true,
Computed: true,
ForceNew: true,
},
"driver_opts": {
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
Type: schema.TypeMap,
Description: "Options specific to the driver.",
Optional: true,
ForceNew: true,
},
"mountpoint": {
Type: schema.TypeString,
Computed: true,
Type: schema.TypeString,
Description: "The mountpoint of the volume.",
Computed: true,
},
},
SchemaVersion: 1,

10
main.go
View file

@ -9,6 +9,16 @@ import (
"github.com/terraform-providers/terraform-provider-docker/internal/provider"
)
// Run "go generate" to format example terraform files and generate the docs for the registry/website
// If you do not have terraform installed, you can remove the formatting command, but its suggested to
// ensure the documentation is formatted properly.
//go:generate terraform fmt -recursive ./examples/
// Run the docs generation tool, check its repository for more information on how it works and how docs
// can be customized.
//go:generate go run github.com/hashicorp/terraform-plugin-docs/cmd/tfplugindocs
var (
// these will be set by the goreleaser configuration
// to appropriate values for the compiled binary

63
templates/index.md.tmpl Normal file
View file

@ -0,0 +1,63 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
layout: ""
page_title: "Provider: Docker"
description: |-
The Docker provider is used to interact with Docker resources, like containers, images, service etc.
---
# Docker Provider
The Docker provider is used to interact with Docker containers and images.
It uses the Docker API to manage the lifecycle of Docker containers. Because
the Docker provider uses the Docker API, it is immediately compatible not
only with single server Docker but Swarm and any additional Docker-compatible
API hosts.
Use the navigation to the left to read about the available resources.
## Example Usage
Terraform 0.13 and later:
{{tffile "examples/provider/provider-tf13.tf"}}
Terraform 0.12 and earlier:
{{tffile "examples/provider/provider-tf12.tf"}}
-> **Note**
You can also use the `ssh` protocol to connect to the docker host on a remote machine.
The configuration would look as follows:
{{tffile "examples/provider/provider-ssh.tf"}}
## Registry credentials
Registry credentials can be provided on a per-registry basis with the `registry_auth`
field, passing either a config file or the username/password directly.
-> **Note**
The location of the config file is on the machine terraform runs on, nevertheless if the specified docker host is on another machine.
{{tffile "examples/provider/provider-credentials.tf"}}
-> **Note**
When passing in a config file either the corresponding `auth` string of the repository is read or the os specific
[credential helpers](https://github.com/docker/docker-credential-helpers#available-programs) are
used to retrieve the authentication credentials.
You can still use the environment variables `DOCKER_REGISTRY_USER` and `DOCKER_REGISTRY_PASS`.
An example content of the file `~/.docker/config.json` on macOS may look like follows:
{{codefile "json" "examples/provider/provider-docker-config.json"}}
## Certificate information
Specify certificate information either with a directory or
directly with the content of the files for connecting to the Docker host via TLS.
{{tffile "examples/provider/provider-cert.tf"}}
{{ .SchemaMarkdown | trimspace }}

View file

@ -0,0 +1,63 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "{{.Type}} {{.Name}} - {{.ProviderName}}"
subcategory: ""
description: |-
{{ .Description | plainmarkdown | trimspace | prefixlines " " }}
---
<!-- Bug: Type and Name are switched -->
# {{.Type}} ({{.Name}})
{{ .Description | trimspace }}
## Example Usage
### Basic
{{tffile "examples/resources/docker_config/resource-basic.tf"}}
### Advanced
#### Dynamically set config with a template
In this example you can use the `${var.foo_port}` variable to dynamically
set the `${port}` variable in the `foo.configs.json.tpl` template and create
the data of the `foo_config` with the help of the `base64encode` interpolation
function.
The file `foo.config.json.tpl` has the following content:
{{codefile "gojson" "examples/resources/docker_config/foo.config.json.tpl" }}
and the resource uses it as follows:
{{tffile "examples/resources/docker_config/resource-advanced.tf"}}
#### Update config with no downtime
To update a `config`, Terraform will destroy the existing resource and create a replacement.
To effectively use a `docker_config` resource with a `docker_service` resource, it's recommended
to specify `create_before_destroy` in a `lifecycle` block. Provide a unique `name` attribute,
for example with one of the interpolation functions `uuid` or `timestamp` as shown
in the example below. The reason is this [issue](https://github.com/moby/moby/issues/35803).
{{tffile "examples/resources/docker_config/resource-no-downtime.tf"}}
{{ .SchemaMarkdown | trimspace }}
## Import
Import is supported using the following syntax by providing the `id`:
{{codefile "shell" "examples/resources/docker_config/import.sh" }}
### Example
Assuming you created a `config` as follows
{{codefile "shell" "examples/resources/docker_config/import-create.sh" }}
you provide the definition for the resource as follows
{{tffile "examples/resources/docker_config/import-resource.tf" }}
then the import command is as follows
{{codefile "shell" "examples/resources/docker_config/import-resource.sh" }}

View file

@ -0,0 +1,37 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "{{.Type}} {{.Name}} - {{.ProviderName}}"
subcategory: ""
description: |-
{{ .Description | plainmarkdown | trimspace | prefixlines " " }}
---
<!-- Bug: Type and Name are switched -->
# {{.Type}} ({{.Name}})
{{ .Description | trimspace }}
## Example Usage
{{tffile "examples/resources/docker_container/resource.tf"}}
{{ .SchemaMarkdown | trimspace }}
## Import
Import is supported using the following syntax by providing the `id`:
{{codefile "shell" "examples/resources/docker_container/import.sh" }}
### Example
Assuming you created a `container` as follows
{{codefile "shell" "examples/resources/docker_container/import-create.sh" }}
you provide the definition for the resource as follows
{{tffile "examples/resources/docker_container/import-resource.tf" }}
then the import command is as follows
{{codefile "shell" "examples/resources/docker_container/import-resource.sh" }}

View file

@ -0,0 +1,36 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "{{.Type}} {{.Name}} - {{.ProviderName}}"
subcategory: ""
description: |-
{{ .Description | plainmarkdown | trimspace | prefixlines " " }}
---
<!-- Bug: Type and Name are switched -->
# {{.Type}} ({{.Name}})
{{ .Description | trimspace }}
## Example Usage
### Basic
Finds and downloads the latest `ubuntu:precise` image but does not check
for further updates of the image
{{tffile "examples/resources/docker_image/resource.tf"}}
### Dynamic updates
To be able to update an update dynamically when the `sha256` sum changes,
you need to use it in combination with `docker_registry_image` as follows:
{{tffile "examples/resources/docker_image/resource-dynamic.tf"}}
### Build
You can also use the resource to build and image.
In thid case the image "zoo" and "zoo:develop" are built.
{{tffile "examples/resources/docker_image/resource-build.tf"}}
{{ .SchemaMarkdown | trimspace }}

View file

@ -0,0 +1,37 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "{{.Type}} {{.Name}} - {{.ProviderName}}"
subcategory: ""
description: |-
{{ .Description | plainmarkdown | trimspace | prefixlines " " }}
---
<!-- Bug: Type and Name are switched -->
# {{.Type}} ({{.Name}})
{{ .Description | trimspace }}
## Example Usage
{{tffile "examples/resources/docker_network/resource.tf"}}
{{ .SchemaMarkdown | trimspace }}
## Import
Import is supported using the following syntax by providing the `id`:
{{codefile "shell" "examples/resources/docker_network/import.sh" }}
### Example
Assuming you created a `network` as follows
{{codefile "shell" "examples/resources/docker_network/import-create.sh" }}
you provide the definition for the resource as follows
{{tffile "examples/resources/docker_network/import-resource.tf" }}
then the import command is as follows
{{codefile "shell" "examples/resources/docker_network/import-resource.sh" }}

Some files were not shown because too many files have changed in this diff Show more