docker_container – manage docker containers
docker_container – manage docker containers
New in version 2.1.
Synopsis
- Manage the life cycle of docker containers.
- Supports check mode. Run with
--check
and--diff
to view config difference and list of actions to be taken.
Requirements
The below requirements are needed on the host that executes this module.
- Docker API >= 1.20
- Docker SDK for Python: Please note that the docker-py Python module has been superseded by docker (see here for details). For Python 2.6,
docker-py
must be used. Otherwise, it is recommended to install thedocker
Python module. Note that both modules should not be installed at the same time. Also note that when both modules are installed and one of them is uninstalled, the other might no longer function and a reinstall of it is required. - Docker SDK for Python >= 1.8.0 (use docker-py for Python 2.6)
Parameters
Parameter | Choices/Defaults | Comments | |
---|---|---|---|
api_version string |
Default: "auto" |
The version of the Docker API running on the Docker Host. Defaults to the latest version of the API supported by Docker SDK for Python and the docker daemon. If the value is not specified in the task, the value of environment variable
| |
auto_remove boolean added in 2.4 |
|
Enable auto-removal of the container on daemon side when the container's process exits. | |
blkio_weight integer |
Block IO (relative weight), between 10 and 1000. | ||
ca_cert path |
Use a CA certificate when performing server verification by providing the path to a CA certificate file. If the value is not specified in the task and the environment variable
| ||
cap_drop list added in 2.7 |
List of capabilities to drop from the container. | ||
capabilities list |
List of capabilities to add to the container. | ||
cleanup boolean added in 2.2 |
|
Use with detach=false to remove the container after successful execution. | |
client_cert path |
Path to the client's TLS certificate file. If the value is not specified in the task and the environment variable
| ||
client_key path |
Path to the client's TLS key file. If the value is not specified in the task and the environment variable
| ||
command raw |
Command to execute when the container starts. A command may be either a string or a list. Prior to version 2.4, strings were split on commas. | ||
comparisons dictionary added in 2.8 |
Allows to specify how properties of existing containers are compared with module options to decide whether the container should be recreated / updated or not. Only options which correspond to the state of a container as handled by the Docker daemon can be specified, as well as Must be a dictionary specifying for an option one of the keys If
The wildcard option See the examples for details. | ||
cpu_period integer |
Limit CPU CFS (Completely Fair Scheduler) period. | ||
cpu_quota integer |
Limit CPU CFS (Completely Fair Scheduler) quota. | ||
cpu_shares integer |
CPU shares (relative weight). | ||
cpuset_cpus string |
CPUs in which to allow execution | ||
cpuset_mems string |
Memory nodes (MEMs) in which to allow execution | ||
debug boolean |
|
Debug mode | |
detach boolean |
|
Enable detached mode to leave the container running in background. If disabled, the task will reflect the status of the container run (failed if the command failed). | |
device_read_bps list added in 2.8 |
List of device path and read rate (bytes per second) from device. | ||
path string / required |
Device path in the container. | ||
rate string / required |
Device read limit in format Number is a positive integer. Unit can be one of Omitting the unit defaults to bytes. | ||
device_read_iops list added in 2.8 |
List of device and read rate (IO per second) from device. | ||
path string / required |
Device path in the container. | ||
rate integer / required |
Device read limit. Must be a positive integer. | ||
device_write_bps list added in 2.8 |
List of device and write rate (bytes per second) to device. | ||
path string / required |
Device path in the container. | ||
rate string / required |
Device read limit in format Number is a positive integer. Unit can be one of Omitting the unit defaults to bytes. | ||
device_write_iops list added in 2.8 |
List of device and write rate (IO per second) to device. | ||
path string / required |
Device path in the container. | ||
rate integer / required |
Device read limit. Must be a positive integer. | ||
devices list |
List of host device bindings to add to the container. Each binding is a mapping expressed in the format | ||
dns_opts list |
List of DNS options. | ||
dns_search_domains list |
List of custom DNS search domains. | ||
dns_servers list |
List of custom DNS servers. | ||
docker_host string |
Default: "unix://var/run/docker.sock" |
The URL or Unix socket path used to connect to the Docker API. To connect to a remote host, provide the TCP connection string. For example, If the value is not specified in the task, the value of environment variable
| |
domainname string added in 2.5 |
Container domainname. | ||
entrypoint list |
Command that overwrites the default | ||
env dictionary |
Dictionary of key,value pairs. Values which might be parsed as numbers, booleans or other types by the YAML parser must be quoted (e.g. | ||
env_file path added in 2.2 |
Path to a file, present on the target, containing environment variables FOO=BAR. If variable also present in env, then the env value will override. | ||
etc_hosts dictionary |
Dict of host-to-IP mappings, where each host name is a key in the dictionary. Each host name will be added to the container's | ||
exposed_ports list |
List of additional container ports which informs Docker that the container listens on the specified network ports at runtime. If the port is already exposed using
| ||
force_kill boolean |
|
Use the kill command when stopping a running container.
| |
groups list |
List of additional group names and/or IDs that the container process will run as. | ||
healthcheck dictionary added in 2.8 |
Configure a check that is run to determine whether or not containers for this service are "healthy". See the docs for the HEALTHCHECK Dockerfile instruction for details on how healthchecks work. interval, timeout and start_period are specified as durations. They accept duration as a string in a format that look like: | ||
interval string |
Time between running the check. The default used by the Docker daemon is | ||
retries integer |
Consecutive number of failures needed to report unhealthy. The default used by the Docker daemon is | ||
start_period string |
Start period for the container to initialize before starting health-retries countdown. The default used by the Docker daemon is | ||
test raw |
Command to run to check health. Must be either a string or a list. If it is a list, the first item must be one of | ||
timeout string |
Maximum time to allow one check to run. The default used by the Docker daemon is | ||
hostname string |
The container's hostname. | ||
ignore_image boolean added in 2.2 |
|
When state is
| |
image string |
Repository path and tag used to create the container. If an image is not found or pull is true, the image will be pulled from the registry. If no tag is included, Can also be an image ID. If this is the case, the image is assumed to be available locally. The pull option is ignored for this case. | ||
init boolean added in 2.6 |
|
Run an init inside the container that forwards signals and reaps processes. This option requires Docker API >= 1.25. | |
interactive boolean |
|
Keep stdin open after a container is launched, even if not attached. | |
ipc_mode string |
Set the IPC mode for the container. Can be one of | ||
keep_volumes boolean |
|
Retain volumes associated with a removed container. | |
kernel_memory string |
Kernel memory limit in format Omitting the unit defaults to bytes. | ||
kill_signal string |
Override default signal used to kill a running container. | ||
labels dictionary |
Dictionary of key value pairs. | ||
links list |
List of name aliases for linked containers in the format Setting this will force container to be restarted. | ||
log_driver string |
Specify the logging driver. Docker uses See here for possible choices. | ||
log_options dictionary |
Dictionary of options specific to the chosen log_driver. See https://docs.docker.com/engine/admin/logging/overview/ for details.
| ||
mac_address string |
Container MAC address (e.g. 92:d0:c6:0a:29:33). | ||
memory string |
Default: "0" |
Memory limit in format Omitting the unit defaults to bytes. | |
memory_reservation string |
Memory soft limit in format Omitting the unit defaults to bytes. | ||
memory_swap string |
Total memory limit (memory + swap) in format Omitting the unit defaults to bytes. | ||
memory_swappiness integer |
Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100. If not set, the value will be remain the same if container exists and will be inherited from the host machine if it is (re-)created. | ||
name string / required |
Assign a name to a new container or match an existing container. When identifying an existing container name may be a name or a long or short container ID. | ||
network_mode string |
Connect the container to a network. Choices are | ||
networks list added in 2.2 |
List of networks the container belongs to. For examples of the data structure and usage see EXAMPLES below. To remove a container from one or more networks, use the purge_networks option. Note that as opposed to | ||
aliases list |
List of aliases for this container in this network. These names can be used in the network to reach this container. | ||
ipv4_address string |
The container's IPv4 address in this network. | ||
ipv6_address string |
The container's IPv6 address in this network. | ||
links list |
A list of containers to link to. | ||
name string / required |
The network's name. | ||
networks_cli_compatible boolean added in 2.8 |
|
When networks are provided to the module via the networks option, the module behaves differently than If networks_cli_compatible is set to Note that docker CLI also sets network_mode to the name of the first network added if Current value is | |
oom_killer boolean |
|
Whether or not to disable OOM Killer for the container. | |
oom_score_adj integer added in 2.2 |
An integer value containing the score given to the container in order to tune OOM killer preferences. | ||
output_logs boolean added in 2.7 |
|
If set to true, output of the container command will be printed. Only effective when log_driver is set to | |
paused boolean |
|
Use with the started state to pause running processes inside the container. | |
pid_mode string |
Set the PID namespace mode for the container. Note that Docker SDK for Python < 2.0 only supports | ||
pids_limit integer added in 2.8 |
Set PIDs limit for the container. It accepts an integer value. Set | ||
privileged boolean |
|
Give extended privileges to the container. | |
published_ports list |
List of ports to publish from the container to the host. Use docker CLI syntax: Port ranges can be used for source and destination ports. If two ranges with different lengths are specified, the shorter range will be used. Bind addresses must be either IPv4 or IPv6 addresses. Hostnames are *not* allowed. This is different from the A value of If networks parameter is provided, will inspect each network to see if there exists a bridge network with optional parameter
| ||
pull boolean |
|
If true, always pull the latest version of an image. Otherwise, will only pull an image when missing.
| |
purge_networks boolean added in 2.2 |
|
Remove the container from ALL networks not included in networks parameter. Any default networks such as | |
read_only boolean |
|
Mount the container's root file system as read-only. | |
recreate boolean |
|
Use with present and started states to force the re-creation of an existing container. | |
restart boolean |
|
Use with started state to force a matching container to be stopped and restarted. | |
restart_policy string |
|
Container restart policy. Place quotes around | |
restart_retries integer |
Use with restart policy to control maximum number of restart attempts. | ||
runtime string added in 2.8 |
Runtime to use for the container. | ||
security_opts list |
List of security options in the form of | ||
shm_size string |
Size of Omitting the unit defaults to bytes. If you omit the size entirely, Docker daemon uses | ||
ssl_version string |
Provide a valid SSL version number. Default value determined by ssl.py module. If the value is not specified in the task, the value of environment variable | ||
state string |
|
To control what will be taken into account when comparing configuration, see the comparisons option. To avoid that the image version will be taken into account, you can also use the ignore_image option. Use the recreate option to always force re-creation of a matching container, even if it is running. If the container should be killed instead of stopped in case it needs to be stopped for recreation, or because state is Use keep_volumes to retain volumes associated with a removed container. | |
stop_signal string |
Override default signal used to stop the container. | ||
stop_timeout integer |
Number of seconds to wait for the container to stop before sending When the container is stopped, will be used as a timeout for stopping the container. In case the container has a custom | ||
sysctls dictionary added in 2.4 |
Dictionary of key,value pairs. | ||
timeout integer |
Default: 60 |
The maximum amount of time in seconds to wait on a response from the API. If the value is not specified in the task, the value of environment variable | |
tls boolean |
|
Secure the connection to the API by using TLS without verifying the authenticity of the Docker host server. Note that if validate_certs is set to If the value is not specified in the task, the value of environment variable | |
tls_hostname string |
Default: "localhost" |
When verifying the authenticity of the Docker Host server, provide the expected name of the server. If the value is not specified in the task, the value of environment variable | |
tmpfs list added in 2.4 |
Mount a tmpfs directory. | ||
trust_image_content boolean |
|
If | |
tty boolean |
|
Allocate a pseudo-TTY. | |
ulimits list |
List of ulimit options. A ulimit is specified as | ||
user string |
Sets the username or UID used and optionally the groupname or GID for the specified command. Can be of the forms | ||
userns_mode string added in 2.5 |
Set the user namespace mode for the container. Currently, the only valid value are | ||
uts string |
Set the UTS namespace mode for the container. | ||
validate_certs boolean |
|
Secure the connection to the API by using TLS and verifying the authenticity of the Docker host server. If the value is not specified in the task, the value of environment variable
| |
volume_driver string |
The container volume driver. | ||
volumes list |
List of volumes to mount within the container. Use docker CLI-style syntax: Mount modes can be a comma-separated list of various modes such as SELinux hosts can additionally use Note that Ansible 2.7 and earlier only supported one mode, which had to be one of | ||
volumes_from list |
List of container names or IDs to get volumes from. | ||
working_dir string added in 2.4 |
Path to the working directory. |
Notes
Note
- For most config changes, the container needs to be recreated, i.e. the existing container has to be destroyed and a new one created. This can cause unexpected data loss and downtime. You can use the comparisons option to prevent this.
- If the module needs to recreate the container, it will only use the options provided to the module to create the new container (except image). Therefore, always specify all options relevant to the container.
- When restart is set to
true
, the module will only restart the container if no config changes are detected. Please note that several options have default values; if the container to be restarted uses different values for these options, it will be recreated instead. The options with default values which can cause this are auto_remove, detach, init, interactive, memory, paused, privileged, read_only and tty. - Connect to the Docker daemon by providing parameters with each task or by defining environment variables. You can define
DOCKER_HOST
,DOCKER_TLS_HOSTNAME
,DOCKER_API_VERSION
,DOCKER_CERT_PATH
,DOCKER_SSL_VERSION
,DOCKER_TLS
,DOCKER_TLS_VERIFY
andDOCKER_TIMEOUT
. If you are using docker machine, run the script shipped with the product that sets up the environment. It will set these variables for you. See https://docker-py.readthedocs.io/en/stable/machine/ for more details. - When connecting to Docker daemon with TLS, you might need to install additional Python packages. For the Docker SDK for Python, version 2.4 or newer, this can be done by installing
docker[tls]
with pip. - Note that the Docker SDK for Python only allows to specify the path to the Docker configuration for very few functions. In general, it will use
$HOME/.docker/config.json
if theDOCKER_CONFIG
environment variable is not specified, and use$DOCKER_CONFIG/config.json
otherwise.
Examples
- name: Create a data container
docker_container:
name: mydata
image: busybox
volumes:
- /data
- name: Re-create a redis container
docker_container:
name: myredis
image: redis
command: redis-server --appendonly yes
state: present
recreate: yes
exposed_ports:
- 6379
volumes_from:
- mydata
- name: Restart a container
docker_container:
name: myapplication
image: someuser/appimage
state: started
restart: yes
links:
- "myredis:aliasedredis"
devices:
- "/dev/sda:/dev/xvda:rwm"
ports:
- "8080:9000"
- "127.0.0.1:8081:9001/udp"
env:
SECRET_KEY: "ssssh"
# Values which might be parsed as numbers, booleans or other types by the YAML parser need to be quoted
BOOLEAN_KEY: "yes"
- name: Container present
docker_container:
name: mycontainer
state: present
image: ubuntu:14.04
command: sleep infinity
- name: Stop a container
docker_container:
name: mycontainer
state: stopped
- name: Start 4 load-balanced containers
docker_container:
name: "container{{ item }}"
recreate: yes
image: someuser/anotherappimage
command: sleep 1d
with_sequence: count=4
- name: remove container
docker_container:
name: ohno
state: absent
- name: Syslogging output
docker_container:
name: myservice
image: busybox
log_driver: syslog
log_options:
syslog-address: tcp://my-syslog-server:514
syslog-facility: daemon
# NOTE: in Docker 1.13+ the "syslog-tag" option was renamed to "tag" for
# older docker installs, use "syslog-tag" instead
tag: myservice
- name: Create db container and connect to network
docker_container:
name: db_test
image: "postgres:latest"
networks:
- name: "{{ docker_network_name }}"
- name: Start container, connect to network and link
docker_container:
name: sleeper
image: ubuntu:14.04
networks:
- name: TestingNet
ipv4_address: "172.1.1.100"
aliases:
- sleepyzz
links:
- db_test:db
- name: TestingNet2
- name: Start a container with a command
docker_container:
name: sleepy
image: ubuntu:14.04
command: ["sleep", "infinity"]
- name: Add container to networks
docker_container:
name: sleepy
networks:
- name: TestingNet
ipv4_address: 172.1.1.18
links:
- sleeper
- name: TestingNet2
ipv4_address: 172.1.10.20
- name: Update network with aliases
docker_container:
name: sleepy
networks:
- name: TestingNet
aliases:
- sleepyz
- zzzz
- name: Remove container from one network
docker_container:
name: sleepy
networks:
- name: TestingNet2
purge_networks: yes
- name: Remove container from all networks
docker_container:
name: sleepy
purge_networks: yes
- name: Start a container and use an env file
docker_container:
name: agent
image: jenkinsci/ssh-slave
env_file: /var/tmp/jenkins/agent.env
- name: Create a container with limited capabilities
docker_container:
name: sleepy
image: ubuntu:16.04
command: sleep infinity
capabilities:
- sys_time
cap_drop:
- all
- name: Finer container restart/update control
docker_container:
name: test
image: ubuntu:18.04
env:
arg1: "true"
arg2: "whatever"
volumes:
- /tmp:/tmp
comparisons:
image: ignore # don't restart containers with older versions of the image
env: strict # we want precisely this environment
volumes: allow_more_present # if there are more volumes, that's ok, as long as `/tmp:/tmp` is there
- name: Finer container restart/update control II
docker_container:
name: test
image: ubuntu:18.04
env:
arg1: "true"
arg2: "whatever"
comparisons:
'*': ignore # by default, ignore *all* options (including image)
env: strict # except for environment variables; there, we want to be strict
- name: Start container with healthstatus
docker_container:
name: nginx-proxy
image: nginx:1.13
state: started
healthcheck:
# Check if nginx server is healthy by curl'ing the server.
# If this fails or timeouts, the healthcheck fails.
test: ["CMD", "curl", "--fail", "http://nginx.host.com"]
interval: 1m30s
timeout: 10s
retries: 3
start_period: 30s
- name: Remove healthcheck from container
docker_container:
name: nginx-proxy
image: nginx:1.13
state: started
healthcheck:
# The "NONE" check needs to be specified
test: ["NONE"]
- name: start container with block device read limit
docker_container:
name: test
image: ubuntu:18.04
state: started
device_read_bps:
# Limit read rate for /dev/sda to 20 mebibytes per second
- path: /dev/sda
rate: 20M
device_read_iops:
# Limit read rate for /dev/sdb to 300 IO per second
- path: /dev/sdb
rate: 300
Return Values
Common return values are documented here, the following are the fields unique to this module:
Key | Returned | Description |
---|---|---|
container dictionary |
always |
Facts representing the current state of the container. Matches the docker inspection output. Note that facts are part of the registered vars since Ansible 2.8. For compatibility reasons, the facts are also accessible directly as Before 2.3 this was Empty if state is If detached is
Sample: { "AppArmorProfile": "", "Args": [], "Config": { "AttachStderr": false, "AttachStdin": false, "AttachStdout": false, "Cmd": [ "/usr/bin/supervisord" ], "Domainname": "", "Entrypoint": null, "Env": [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ], "ExposedPorts": { "443/tcp": {}, "80/tcp": {} }, "Hostname": "8e47bf643eb9", "Image": "lnmp_nginx:v1", "Labels": {}, "OnBuild": null, "OpenStdin": false, "StdinOnce": false, "Tty": false, "User": "", "Volumes": { "/tmp/lnmp/nginx-sites/logs/": {} }, ... } |
Status
- This module is not guaranteed to have a backwards compatible interface. [preview]
- This module is maintained by the Ansible Community. [community]
Authors
- Cove Schneider (@cove)
- Joshua Conner (@joshuaconner)
- Pavel Antonov (@softzilla)
- Thomas Steinbach (@ThomasSteinbach)
- Philippe Jandot (@zfil)
- Daan Oosterveld (@dusdanig)
- Chris Houseknecht (@chouseknecht)
- Kassian Sun (@kassiansun)
- Felix Fontein (@felixfontein)
© 2012–2018 Michael DeHaan
© 2018–2019 Red Hat, Inc.
Licensed under the GNU General Public License version 3.
https://docs.ansible.com/ansible/2.8/modules/docker_container_module.html