2014-01-15 15:52:17 +01:00
|
|
|
#!/usr/bin/python
|
2013-11-03 21:48:03 +01:00
|
|
|
|
|
|
|
# (c) 2013, Cove Schneider
|
2014-02-26 00:24:46 +01:00
|
|
|
# (c) 2014, Joshua Conner <joshua.conner@gmail.com>
|
2014-01-22 13:04:19 +01:00
|
|
|
# (c) 2014, Pavel Antonov <antonov@adwz.ru>
|
2013-10-14 00:07:27 +02:00
|
|
|
#
|
2013-11-03 21:48:03 +01:00
|
|
|
# This file is part of Ansible,
|
2013-10-14 00:07:27 +02:00
|
|
|
#
|
2013-11-03 21:48:03 +01:00
|
|
|
# Ansible is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
2013-10-14 00:07:27 +02:00
|
|
|
#
|
2013-11-03 21:48:03 +01:00
|
|
|
# Ansible is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
2013-10-14 00:07:27 +02:00
|
|
|
#
|
2013-11-03 21:48:03 +01:00
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
|
|
|
######################################################################
|
2013-10-14 00:07:27 +02:00
|
|
|
|
|
|
|
DOCUMENTATION = '''
|
|
|
|
---
|
|
|
|
module: docker
|
2013-11-19 00:55:49 +01:00
|
|
|
version_added: "1.4"
|
2013-10-14 00:07:27 +02:00
|
|
|
short_description: manage docker containers
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- Manage the life cycle of docker containers.
|
2013-10-14 00:07:27 +02:00
|
|
|
options:
|
|
|
|
count:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- Number of matching containers that should be in the desired state.
|
2013-10-14 00:07:27 +02:00
|
|
|
default: 1
|
|
|
|
image:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- Container image used to match and launch containers.
|
2013-10-14 00:07:27 +02:00
|
|
|
required: true
|
2014-12-12 17:01:08 +01:00
|
|
|
pull:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- Control when container images are updated from the C(docker_url) registry.
|
|
|
|
If "missing," images will be pulled only when missing from the host;
|
|
|
|
if '"always," the registry will be checked for a newer version of the
|
|
|
|
image' each time the task executes.
|
2014-12-12 17:01:08 +01:00
|
|
|
default: missing
|
|
|
|
choices: [ "missing", "always" ]
|
|
|
|
version_added: "1.9"
|
2015-10-02 00:09:08 +02:00
|
|
|
entrypoint:
|
|
|
|
description:
|
|
|
|
- Corresponds to ``--entrypoint`` option of ``docker run`` command and
|
|
|
|
``ENTRYPOINT`` directive of Dockerfile.
|
|
|
|
Used to match and launch containers.
|
|
|
|
default: null
|
|
|
|
required: false
|
2015-12-19 06:28:01 +01:00
|
|
|
version_added: "2.1"
|
2013-10-14 00:07:27 +02:00
|
|
|
command:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- Command used to match and launch containers.
|
2013-10-14 00:07:27 +02:00
|
|
|
default: null
|
2014-01-22 13:04:19 +01:00
|
|
|
name:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- Name used to match and uniquely name launched containers. Explicit names
|
|
|
|
are used to uniquely identify a single container or to link among
|
|
|
|
containers. Mutually exclusive with a "count" other than "1".
|
2014-01-22 13:04:19 +01:00
|
|
|
default: null
|
2014-02-26 02:04:01 +01:00
|
|
|
version_added: "1.5"
|
2013-10-14 00:07:27 +02:00
|
|
|
ports:
|
|
|
|
description:
|
2015-06-17 18:39:14 +02:00
|
|
|
- "List containing private to public port mapping specification.
|
|
|
|
Use docker 'CLI-style syntax: C(8000), C(9000:8000), or C(0.0.0.0:9000:8000)'
|
|
|
|
where 8000 is a container port, 9000 is a host port, and 0.0.0.0 is - a host interface.
|
|
|
|
The container ports need to be exposed either in the Dockerfile or via the C(expose) option."
|
2013-10-14 00:07:27 +02:00
|
|
|
default: null
|
2014-02-26 02:04:01 +01:00
|
|
|
version_added: "1.5"
|
2014-02-26 00:24:46 +01:00
|
|
|
expose:
|
2014-01-22 13:04:19 +01:00
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- List of additional container ports to expose for port mappings or links.
|
|
|
|
If the port is already exposed using EXPOSE in a Dockerfile, you don't
|
|
|
|
need to expose it again.
|
2014-01-22 13:04:19 +01:00
|
|
|
default: null
|
2014-02-26 02:04:01 +01:00
|
|
|
version_added: "1.5"
|
2014-02-26 00:24:46 +01:00
|
|
|
publish_all_ports:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- Publish all exposed ports to the host interfaces.
|
2014-02-26 02:04:01 +01:00
|
|
|
default: false
|
|
|
|
version_added: "1.5"
|
2013-10-14 00:07:27 +02:00
|
|
|
volumes:
|
|
|
|
description:
|
2015-11-12 09:42:26 +01:00
|
|
|
- List of volumes to mount within the container
|
|
|
|
- 'Use docker CLI-style syntax: C(/host:/container[:mode])'
|
2015-12-12 19:04:01 +01:00
|
|
|
- You can specify a read mode for the mount with either C(ro) or C(rw).
|
|
|
|
Starting at version 2.1, SELinux hosts can additionally use C(z) or C(Z)
|
|
|
|
mount options to use a shared or private label for the volume.
|
2013-10-14 00:07:27 +02:00
|
|
|
default: null
|
|
|
|
volumes_from:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- List of names of containers to mount volumes from.
|
2013-10-14 00:07:27 +02:00
|
|
|
default: null
|
2014-02-26 00:24:46 +01:00
|
|
|
links:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- List of other containers to link within this container with an optional
|
|
|
|
- 'alias. Use docker CLI-style syntax: C(redis:myredis).'
|
2014-02-26 00:24:46 +01:00
|
|
|
default: null
|
2014-02-26 02:04:01 +01:00
|
|
|
version_added: "1.5"
|
2015-11-03 15:11:18 +01:00
|
|
|
devices:
|
|
|
|
description:
|
|
|
|
- List of host devices to expose to container
|
|
|
|
default: null
|
|
|
|
required: false
|
2015-12-19 01:33:48 +01:00
|
|
|
version_added: "2.1"
|
2015-05-23 00:36:38 +02:00
|
|
|
log_driver:
|
|
|
|
description:
|
|
|
|
- You can specify a different logging driver for the container than for the daemon.
|
|
|
|
"json-file" Default logging driver for Docker. Writes JSON messages to file.
|
|
|
|
docker logs command is available only for this logging driver.
|
2015-09-23 17:54:51 +02:00
|
|
|
"none" disables any logging for the container.
|
2015-05-23 00:36:38 +02:00
|
|
|
"syslog" Syslog logging driver for Docker. Writes log messages to syslog.
|
|
|
|
docker logs command is not available for this logging driver.
|
2015-09-23 17:54:51 +02:00
|
|
|
"journald" Journald logging driver for Docker. Writes log messages to "journald".
|
|
|
|
"gelf" Graylog Extended Log Format (GELF) logging driver for Docker. Writes log messages to a GELF endpoint likeGraylog or Logstash.
|
|
|
|
"fluentd" Fluentd logging driver for Docker. Writes log messages to "fluentd" (forward input).
|
2015-05-28 19:36:20 +02:00
|
|
|
If not defined explicitly, the Docker daemon's default ("json-file") will apply.
|
2015-05-23 00:36:38 +02:00
|
|
|
Requires docker >= 1.6.0.
|
|
|
|
required: false
|
|
|
|
default: json-file
|
|
|
|
choices:
|
|
|
|
- json-file
|
|
|
|
- none
|
|
|
|
- syslog
|
2015-09-23 17:54:51 +02:00
|
|
|
- journald
|
|
|
|
- gelf
|
|
|
|
- fluentd
|
2015-06-25 17:29:42 +02:00
|
|
|
version_added: "2.0"
|
2015-09-08 17:19:26 +02:00
|
|
|
log_opt:
|
|
|
|
description:
|
2015-10-28 12:35:14 +01:00
|
|
|
- Additional options to pass to the logging driver selected above. See Docker `log-driver
|
2015-10-04 03:50:15 +02:00
|
|
|
<https://docs.docker.com/reference/logging/overview/>` documentation for more information.
|
2015-09-08 17:19:26 +02:00
|
|
|
Requires docker >=1.7.0.
|
|
|
|
required: false
|
|
|
|
default: null
|
|
|
|
version_added: "2.0"
|
2013-10-14 00:07:27 +02:00
|
|
|
memory_limit:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- RAM allocated to the container as a number of bytes or as a human-readable
|
|
|
|
string like "512MB". Leave as "0" to specify no limit.
|
2014-12-12 17:01:08 +01:00
|
|
|
default: 0
|
2013-10-14 00:07:27 +02:00
|
|
|
docker_url:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- URL of the host running the docker daemon. This will default to the env
|
|
|
|
var DOCKER_HOST if unspecified.
|
2014-12-12 17:01:08 +01:00
|
|
|
default: ${DOCKER_HOST} or unix://var/run/docker.sock
|
2015-03-12 04:27:29 +01:00
|
|
|
use_tls:
|
2014-12-12 17:01:08 +01:00
|
|
|
description:
|
2015-03-12 04:27:29 +01:00
|
|
|
- Whether to use tls to connect to the docker server. "no" means not to
|
|
|
|
use tls (and ignore any other tls related parameters). "encrypt" means
|
|
|
|
to use tls to encrypt the connection to the server. "verify" means to
|
|
|
|
also verify that the server's certificate is valid for the server
|
|
|
|
(this both verifies the certificate against the CA and that the
|
|
|
|
certificate was issued for that host. If this is unspecified, tls will
|
|
|
|
only be used if one of the other tls options require it.
|
|
|
|
choices: [ "no", "encrypt", "verify" ]
|
|
|
|
version_added: "1.9"
|
|
|
|
tls_client_cert:
|
|
|
|
description:
|
|
|
|
- Path to the PEM-encoded certificate used to authenticate docker client.
|
|
|
|
If specified tls_client_key must be valid
|
2014-12-12 17:01:08 +01:00
|
|
|
default: ${DOCKER_CERT_PATH}/cert.pem
|
2015-03-12 04:27:29 +01:00
|
|
|
version_added: "1.9"
|
|
|
|
tls_client_key:
|
2014-12-12 17:01:08 +01:00
|
|
|
description:
|
2015-03-12 04:27:29 +01:00
|
|
|
- Path to the PEM-encoded key used to authenticate docker client. If
|
|
|
|
specified tls_client_cert must be valid
|
2014-12-12 17:01:08 +01:00
|
|
|
default: ${DOCKER_CERT_PATH}/key.pem
|
2015-03-12 04:27:29 +01:00
|
|
|
version_added: "1.9"
|
|
|
|
tls_ca_cert:
|
2014-12-12 17:01:08 +01:00
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- Path to a PEM-encoded certificate authority to secure the Docker connection.
|
2015-03-12 04:27:29 +01:00
|
|
|
This has no effect if use_tls is encrypt.
|
2014-12-12 17:01:08 +01:00
|
|
|
default: ${DOCKER_CERT_PATH}/ca.pem
|
2015-03-12 04:27:29 +01:00
|
|
|
version_added: "1.9"
|
|
|
|
tls_hostname:
|
|
|
|
description:
|
|
|
|
- A hostname to check matches what's supplied in the docker server's
|
|
|
|
certificate. If unspecified, the hostname is taken from the docker_url.
|
|
|
|
default: Taken from docker_url
|
|
|
|
version_added: "1.9"
|
2014-06-13 20:23:25 +02:00
|
|
|
docker_api_version:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- Remote API version to use. This defaults to the current default as
|
|
|
|
specified by docker-py.
|
2014-06-13 20:23:25 +02:00
|
|
|
default: docker-py default remote API version
|
2014-08-08 22:03:34 +02:00
|
|
|
version_added: "1.8"
|
2014-11-20 00:21:01 +01:00
|
|
|
docker_user:
|
|
|
|
description:
|
|
|
|
- Username or UID to use within the container
|
|
|
|
required: false
|
2015-07-21 03:18:49 +02:00
|
|
|
default: null
|
2014-11-20 00:21:01 +01:00
|
|
|
version_added: "2.0"
|
2013-10-14 00:07:27 +02:00
|
|
|
username:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- Remote API username.
|
2013-10-14 00:07:27 +02:00
|
|
|
default: null
|
|
|
|
password:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- Remote API password.
|
2013-10-14 00:07:27 +02:00
|
|
|
default: null
|
2014-12-10 03:23:59 +01:00
|
|
|
email:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- Remote API email.
|
2014-12-10 03:23:59 +01:00
|
|
|
default: null
|
2013-10-14 00:07:27 +02:00
|
|
|
hostname:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- Container hostname.
|
2013-10-14 00:07:27 +02:00
|
|
|
default: null
|
2015-02-11 08:25:24 +01:00
|
|
|
domainname:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- Container domain name.
|
2015-02-11 08:25:24 +01:00
|
|
|
default: null
|
2013-10-14 00:07:27 +02:00
|
|
|
env:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- Pass a dict of environment variables to the container.
|
2013-10-14 00:07:27 +02:00
|
|
|
default: null
|
|
|
|
dns:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- List of custom DNS servers for the container.
|
2013-10-14 00:07:27 +02:00
|
|
|
required: false
|
|
|
|
default: null
|
|
|
|
detach:
|
|
|
|
description:
|
2015-03-30 21:52:17 +02:00
|
|
|
- Enable detached mode to leave the container running in background. If
|
|
|
|
disabled, fail unless the process exits cleanly.
|
2013-10-14 00:07:27 +02:00
|
|
|
default: true
|
2015-03-27 18:07:35 +01:00
|
|
|
signal:
|
2015-07-21 02:53:59 +02:00
|
|
|
version_added: "2.0"
|
2015-03-27 18:07:35 +01:00
|
|
|
description:
|
|
|
|
- With the state "killed", you can alter the signal sent to the
|
|
|
|
container.
|
|
|
|
required: false
|
|
|
|
default: KILL
|
2013-10-14 00:07:27 +02:00
|
|
|
state:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- Assert the container's desired state. "present" only asserts that the
|
|
|
|
matching containers exist. "started" asserts that the matching
|
|
|
|
containers both exist and are running, but takes no action if any
|
2015-03-28 00:36:10 +01:00
|
|
|
configuration has changed. "reloaded" (added in Ansible 1.9) asserts that all matching
|
2015-03-07 06:51:51 +01:00
|
|
|
containers are running and restarts any that have any images or
|
|
|
|
configuration out of date. "restarted" unconditionally restarts (or
|
|
|
|
starts) the matching containers. "stopped" and '"killed" stop and kill
|
|
|
|
all matching containers. "absent" stops and then' removes any matching
|
|
|
|
containers.
|
2013-10-14 00:07:27 +02:00
|
|
|
required: false
|
2015-02-17 22:27:00 +01:00
|
|
|
default: started
|
2014-12-12 17:01:08 +01:00
|
|
|
choices:
|
2015-03-07 06:51:51 +01:00
|
|
|
- present
|
|
|
|
- started
|
|
|
|
- reloaded
|
|
|
|
- restarted
|
|
|
|
- stopped
|
|
|
|
- killed
|
|
|
|
- absent
|
2013-10-14 00:07:27 +02:00
|
|
|
privileged:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- Whether the container should run in privileged mode or not.
|
2013-10-14 00:07:27 +02:00
|
|
|
default: false
|
|
|
|
lxc_conf:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- LXC configuration parameters, such as C(lxc.aa_profile:unconfined).
|
2014-02-26 00:24:46 +01:00
|
|
|
default: null
|
2014-03-18 12:57:01 +01:00
|
|
|
stdin_open:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- Keep stdin open after a container is launched.
|
2014-03-18 12:57:01 +01:00
|
|
|
default: false
|
|
|
|
version_added: "1.6"
|
|
|
|
tty:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- Allocate a pseudo-tty within the container.
|
2014-03-18 12:57:01 +01:00
|
|
|
default: false
|
|
|
|
version_added: "1.6"
|
2014-05-15 00:29:54 +02:00
|
|
|
net:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- 'Network mode for the launched container: bridge, none, container:<name|id>'
|
|
|
|
- or host. Requires docker >= 0.11.
|
2014-05-15 00:29:54 +02:00
|
|
|
default: false
|
2014-08-08 20:16:08 +02:00
|
|
|
version_added: "1.8"
|
2015-03-04 06:32:15 +01:00
|
|
|
pid:
|
|
|
|
description:
|
2015-03-13 15:31:55 +01:00
|
|
|
- Set the PID namespace mode for the container (currently only supports 'host'). Requires docker-py >= 1.0.0 and docker >= 1.5.0
|
2015-03-04 06:32:15 +01:00
|
|
|
required: false
|
2015-03-06 10:13:32 +01:00
|
|
|
default: None
|
2015-03-04 06:32:15 +01:00
|
|
|
aliases: []
|
2015-03-06 10:13:32 +01:00
|
|
|
version_added: "1.9"
|
2014-08-18 17:37:07 +02:00
|
|
|
registry:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- Remote registry URL to pull images from.
|
2014-12-12 17:01:08 +01:00
|
|
|
default: DockerHub
|
2014-08-18 17:37:07 +02:00
|
|
|
aliases: []
|
|
|
|
version_added: "1.8"
|
2015-07-21 14:24:07 +02:00
|
|
|
read_only:
|
|
|
|
description:
|
|
|
|
- Mount the container's root filesystem as read only
|
2015-09-05 00:59:19 +02:00
|
|
|
default: null
|
2015-07-21 14:24:07 +02:00
|
|
|
aliases: []
|
2015-07-22 08:28:16 +02:00
|
|
|
version_added: "2.0"
|
2014-10-19 22:15:48 +02:00
|
|
|
restart_policy:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- Container restart policy.
|
2016-01-12 00:14:37 +01:00
|
|
|
- The 'unless-stopped' choice is only available starting in Ansible 2.1 and for Docker 1.9 and above.
|
2015-11-18 10:02:51 +01:00
|
|
|
choices: ["no", "on-failure", "always", "unless-stopped"]
|
2014-12-12 17:01:08 +01:00
|
|
|
default: null
|
2014-10-19 22:15:48 +02:00
|
|
|
version_added: "1.9"
|
|
|
|
restart_policy_retry:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- Maximum number of times to restart a container. Leave as "0" for unlimited
|
|
|
|
retries.
|
2014-12-12 17:01:08 +01:00
|
|
|
default: 0
|
2014-10-19 22:15:48 +02:00
|
|
|
version_added: "1.9"
|
2015-04-07 09:08:43 +02:00
|
|
|
extra_hosts:
|
2015-07-30 19:04:30 +02:00
|
|
|
version_added: "2.0"
|
2015-04-07 09:08:43 +02:00
|
|
|
description:
|
|
|
|
- Dict of custom host-to-IP mappings to be defined in the container
|
2014-12-14 04:56:30 +01:00
|
|
|
insecure_registry:
|
|
|
|
description:
|
2015-03-07 06:51:51 +01:00
|
|
|
- Use insecure private registry by HTTP instead of HTTPS. Needed for
|
|
|
|
docker-py >= 0.5.0.
|
2014-12-14 04:56:30 +01:00
|
|
|
default: false
|
|
|
|
version_added: "1.9"
|
2014-11-24 23:08:12 +01:00
|
|
|
cpu_set:
|
2014-11-24 22:55:14 +01:00
|
|
|
description:
|
|
|
|
- CPUs in which to allow execution. Requires docker-py >= 0.6.0.
|
|
|
|
required: false
|
|
|
|
default: null
|
2015-07-21 02:09:36 +02:00
|
|
|
version_added: "2.0"
|
2014-10-18 15:25:07 +02:00
|
|
|
cap_add:
|
|
|
|
description:
|
|
|
|
- Add capabilities for the container. Requires docker-py >= 0.5.0.
|
|
|
|
required: false
|
|
|
|
default: false
|
|
|
|
version_added: "2.0"
|
|
|
|
cap_drop:
|
|
|
|
description:
|
|
|
|
- Drop capabilities for the container. Requires docker-py >= 0.5.0.
|
|
|
|
required: false
|
|
|
|
default: false
|
|
|
|
aliases: []
|
|
|
|
version_added: "2.0"
|
2015-09-25 22:58:20 +02:00
|
|
|
labels:
|
|
|
|
description:
|
|
|
|
- Set container labels. Requires docker >= 1.6 and docker-py >= 1.2.0.
|
2015-11-04 10:43:03 +01:00
|
|
|
required: false
|
2015-09-25 22:58:20 +02:00
|
|
|
default: null
|
2015-12-19 02:57:17 +01:00
|
|
|
version_added: "2.1"
|
2015-09-24 07:15:59 +02:00
|
|
|
stop_timeout:
|
|
|
|
description:
|
|
|
|
- How many seconds to wait for the container to stop before killing it.
|
|
|
|
required: false
|
|
|
|
default: 10
|
|
|
|
version_added: "2.0"
|
2016-01-09 19:01:02 +01:00
|
|
|
timeout:
|
|
|
|
description:
|
|
|
|
- Docker daemon response timeout in seconds.
|
|
|
|
required: false
|
|
|
|
default: 60
|
|
|
|
version_added: "2.1"
|
2015-11-26 15:49:18 +01:00
|
|
|
cpu_shares:
|
|
|
|
description:
|
|
|
|
- CPU shares (relative weight). Requires docker-py >= 0.6.0.
|
|
|
|
required: false
|
|
|
|
default: 0
|
2016-01-12 14:27:33 +01:00
|
|
|
version_added: "2.1"
|
2015-11-26 15:49:18 +01:00
|
|
|
|
2014-11-24 22:55:14 +01:00
|
|
|
author:
|
2015-06-15 20:41:22 +02:00
|
|
|
- "Cove Schneider (@cove)"
|
|
|
|
- "Joshua Conner (@joshuaconner)"
|
|
|
|
- "Pavel Antonov (@softzilla)"
|
|
|
|
- "Ash Wilson (@smashwilson)"
|
2015-11-06 19:53:33 +01:00
|
|
|
- "Thomas Steinbach (@ThomasSteinbach)"
|
2015-11-07 06:18:46 +01:00
|
|
|
- "Philippe Jandot (@zfil)"
|
2015-05-11 21:15:53 +02:00
|
|
|
requirements:
|
|
|
|
- "python >= 2.6"
|
|
|
|
- "docker-py >= 0.3.0"
|
|
|
|
- "The docker server >= 0.10.0"
|
2013-10-14 00:07:27 +02:00
|
|
|
'''
|
|
|
|
|
2013-10-14 05:34:14 +02:00
|
|
|
EXAMPLES = '''
|
2014-12-12 17:01:08 +01:00
|
|
|
# Containers are matched either by name (if provided) or by an exact match of
|
|
|
|
# the image they were launched with and the command they're running. The module
|
|
|
|
# can accept either a name to target a container uniquely, or a count to operate
|
|
|
|
# on multiple containers at once when it makes sense to do so.
|
|
|
|
|
|
|
|
# Ensure that a data container with the name "mydata" exists. If no container
|
|
|
|
# by this name exists, it will be created, but not started.
|
|
|
|
|
|
|
|
- name: data container
|
|
|
|
docker:
|
|
|
|
name: mydata
|
|
|
|
image: busybox
|
|
|
|
state: present
|
|
|
|
volumes:
|
|
|
|
- /data
|
|
|
|
|
|
|
|
# Ensure that a Redis server is running, using the volume from the data
|
|
|
|
# container. Expose the default Redis port.
|
|
|
|
|
|
|
|
- name: redis container
|
|
|
|
docker:
|
|
|
|
name: myredis
|
|
|
|
image: redis
|
|
|
|
command: redis-server --appendonly yes
|
|
|
|
state: started
|
|
|
|
expose:
|
|
|
|
- 6379
|
|
|
|
volumes_from:
|
|
|
|
- mydata
|
|
|
|
|
|
|
|
# Ensure that a container of your application server is running. This will:
|
|
|
|
# - pull the latest version of your application image from DockerHub.
|
|
|
|
# - ensure that a container is running with the specified name and exact image.
|
|
|
|
# If any configuration options have changed, the existing container will be
|
|
|
|
# stopped and removed, and a new one will be launched in its place.
|
|
|
|
# - link this container to the existing redis container launched above with
|
|
|
|
# an alias.
|
2015-12-19 01:33:48 +01:00
|
|
|
# - grant the container read write permissions for the host's /dev/sda device
|
2015-11-03 15:11:18 +01:00
|
|
|
# through a node named /dev/xvda
|
2014-12-12 17:01:08 +01:00
|
|
|
# - bind TCP port 9000 within the container to port 8080 on all interfaces
|
|
|
|
# on the host.
|
|
|
|
# - bind UDP port 9001 within the container to port 8081 on the host, only
|
|
|
|
# listening on localhost.
|
|
|
|
# - set the environment variable SECRET_KEY to "ssssh".
|
|
|
|
|
|
|
|
- name: application container
|
|
|
|
docker:
|
|
|
|
name: myapplication
|
|
|
|
image: someuser/appimage
|
|
|
|
state: reloaded
|
|
|
|
pull: always
|
|
|
|
links:
|
|
|
|
- "myredis:aliasedredis"
|
2015-11-03 15:11:18 +01:00
|
|
|
devices:
|
|
|
|
- "/dev/sda:/dev/xvda:rwm"
|
2014-12-12 17:01:08 +01:00
|
|
|
ports:
|
|
|
|
- "8080:9000"
|
|
|
|
- "127.0.0.1:8081:9001/udp"
|
|
|
|
env:
|
|
|
|
SECRET_KEY: ssssh
|
|
|
|
|
|
|
|
# Ensure that exactly five containers of another server are running with this
|
|
|
|
# exact image and command. If fewer than five are running, more will be launched;
|
|
|
|
# if more are running, the excess will be stopped.
|
|
|
|
|
|
|
|
- name: load-balanced containers
|
|
|
|
docker:
|
|
|
|
state: reloaded
|
|
|
|
count: 5
|
|
|
|
image: someuser/anotherappimage
|
|
|
|
command: sleep 1d
|
|
|
|
|
|
|
|
# Unconditionally restart a service container. This may be useful within a
|
|
|
|
# handler, for example.
|
|
|
|
|
|
|
|
- name: application service
|
|
|
|
docker:
|
|
|
|
name: myservice
|
|
|
|
image: someuser/serviceimage
|
|
|
|
state: restarted
|
|
|
|
|
|
|
|
# Stop all containers running the specified image.
|
|
|
|
|
|
|
|
- name: obsolete container
|
|
|
|
docker:
|
|
|
|
image: someuser/oldandbusted
|
|
|
|
state: stopped
|
|
|
|
|
|
|
|
# Stop and remove a container with the specified name.
|
|
|
|
|
|
|
|
- name: obsolete container
|
|
|
|
docker:
|
|
|
|
name: ohno
|
|
|
|
image: someuser/oldandbusted
|
|
|
|
state: absent
|
2015-09-08 17:19:26 +02:00
|
|
|
|
|
|
|
# Example Syslogging Output
|
|
|
|
|
|
|
|
- name: myservice container
|
|
|
|
docker:
|
|
|
|
name: myservice
|
|
|
|
image: someservice/someimage
|
|
|
|
state: reloaded
|
|
|
|
log_driver: syslog
|
|
|
|
log_opt:
|
|
|
|
syslog-address: tcp://my-syslog-server:514
|
|
|
|
syslog-facility: daemon
|
|
|
|
syslog-tag: myservice
|
2013-10-14 05:34:14 +02:00
|
|
|
'''
|
|
|
|
|
2014-02-26 00:24:46 +01:00
|
|
|
HAS_DOCKER_PY = True
|
2015-07-28 04:32:32 +02:00
|
|
|
DEFAULT_DOCKER_API_VERSION = None
|
2016-01-09 19:01:02 +01:00
|
|
|
DEFAULT_TIMEOUT_SECONDS = 60
|
2014-02-26 00:24:46 +01:00
|
|
|
|
|
|
|
import sys
|
2014-12-12 17:14:24 +01:00
|
|
|
import json
|
2015-02-17 22:27:00 +01:00
|
|
|
import os
|
|
|
|
import shlex
|
2014-02-26 00:24:46 +01:00
|
|
|
from urlparse import urlparse
|
2013-10-14 00:07:27 +02:00
|
|
|
try:
|
|
|
|
import docker.client
|
2014-04-11 18:08:55 +02:00
|
|
|
import docker.utils
|
2015-07-16 21:25:39 +02:00
|
|
|
import docker.errors
|
2015-03-16 19:58:03 +01:00
|
|
|
from requests.exceptions import RequestException
|
|
|
|
except ImportError:
|
2014-02-26 00:24:46 +01:00
|
|
|
HAS_DOCKER_PY = False
|
|
|
|
|
2014-11-14 17:46:32 +01:00
|
|
|
if HAS_DOCKER_PY:
|
|
|
|
try:
|
|
|
|
from docker.errors import APIError as DockerAPIError
|
|
|
|
except ImportError:
|
|
|
|
from docker.client import APIError as DockerAPIError
|
2015-04-30 16:46:41 +02:00
|
|
|
try:
|
|
|
|
# docker-py 1.2+
|
|
|
|
import docker.constants
|
|
|
|
DEFAULT_DOCKER_API_VERSION = docker.constants.DEFAULT_DOCKER_API_VERSION
|
2016-01-09 19:01:02 +01:00
|
|
|
DEFAULT_TIMEOUT_SECONDS = docker.constants.DEFAULT_TIMEOUT_SECONDS
|
2015-04-30 16:46:41 +02:00
|
|
|
except (ImportError, AttributeError):
|
|
|
|
# docker-py less than 1.2
|
|
|
|
DEFAULT_DOCKER_API_VERSION = docker.client.DEFAULT_DOCKER_API_VERSION
|
2016-01-09 19:01:02 +01:00
|
|
|
DEFAULT_TIMEOUT_SECONDS = docker.client.DEFAULT_TIMEOUT_SECONDS
|
2014-04-17 00:42:56 +02:00
|
|
|
|
2013-10-14 00:07:27 +02:00
|
|
|
|
|
|
|
def _human_to_bytes(number):
|
|
|
|
suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
|
|
|
|
|
|
|
|
if isinstance(number, int):
|
|
|
|
return number
|
|
|
|
if number[-1] == suffixes[0] and number[-2].isdigit():
|
|
|
|
return number[:-1]
|
|
|
|
|
|
|
|
i = 1
|
|
|
|
for each in suffixes[1:]:
|
|
|
|
if number[-len(each):] == suffixes[i]:
|
|
|
|
return int(number[:-len(each)]) * (1024 ** i)
|
|
|
|
i = i + 1
|
|
|
|
|
2015-05-11 21:15:53 +02:00
|
|
|
raise ValueError('Could not convert %s to integer' % (number,))
|
2013-10-14 00:07:27 +02:00
|
|
|
|
2015-02-17 22:27:00 +01:00
|
|
|
|
2013-10-14 00:07:27 +02:00
|
|
|
def _ansible_facts(container_list):
|
2013-10-14 22:49:53 +02:00
|
|
|
return {"docker_containers": container_list}
|
2013-10-14 00:07:27 +02:00
|
|
|
|
2015-02-17 22:27:00 +01:00
|
|
|
|
2013-10-24 07:56:02 +02:00
|
|
|
def _docker_id_quirk(inspect):
|
|
|
|
# XXX: some quirk in docker
|
|
|
|
if 'ID' in inspect:
|
|
|
|
inspect['Id'] = inspect['ID']
|
|
|
|
del inspect['ID']
|
|
|
|
return inspect
|
|
|
|
|
2014-11-14 17:46:32 +01:00
|
|
|
|
|
|
|
def get_split_image_tag(image):
|
|
|
|
# If image contains a host or org name, omit that from our check
|
|
|
|
if '/' in image:
|
|
|
|
registry, resource = image.rsplit('/', 1)
|
|
|
|
else:
|
|
|
|
registry, resource = None, image
|
|
|
|
|
|
|
|
# now we can determine if image has a tag
|
|
|
|
if ':' in resource:
|
|
|
|
resource, tag = resource.split(':', 1)
|
|
|
|
if registry:
|
|
|
|
resource = '/'.join((registry, resource))
|
|
|
|
else:
|
|
|
|
tag = "latest"
|
|
|
|
resource = image
|
|
|
|
|
|
|
|
return resource, tag
|
|
|
|
|
2015-03-24 16:07:12 +01:00
|
|
|
def normalize_image(image):
|
|
|
|
"""
|
|
|
|
Normalize a Docker image name to include the implied :latest tag.
|
|
|
|
"""
|
|
|
|
|
|
|
|
return ":".join(get_split_image_tag(image))
|
|
|
|
|
2015-02-17 22:27:00 +01:00
|
|
|
|
|
|
|
def is_running(container):
|
|
|
|
'''Return True if an inspected container is in a state we consider "running."'''
|
|
|
|
|
|
|
|
return container['State']['Running'] == True and not container['State'].get('Ghost', False)
|
|
|
|
|
|
|
|
|
2014-12-18 20:23:44 +01:00
|
|
|
def get_docker_py_versioninfo():
|
|
|
|
if hasattr(docker, '__version__'):
|
|
|
|
# a '__version__' attribute was added to the module but not until
|
|
|
|
# after 0.3.0 was pushed to pypi. If it's there, use it.
|
|
|
|
version = []
|
|
|
|
for part in docker.__version__.split('.'):
|
|
|
|
try:
|
|
|
|
version.append(int(part))
|
|
|
|
except ValueError:
|
|
|
|
for idx, char in enumerate(part):
|
|
|
|
if not char.isdigit():
|
|
|
|
nondigit = part[idx:]
|
|
|
|
digit = part[:idx]
|
2015-07-16 03:05:13 +02:00
|
|
|
break
|
2014-12-18 20:23:44 +01:00
|
|
|
if digit:
|
|
|
|
version.append(int(digit))
|
|
|
|
if nondigit:
|
|
|
|
version.append(nondigit)
|
|
|
|
elif hasattr(docker.Client, '_get_raw_response_socket'):
|
|
|
|
# HACK: if '__version__' isn't there, we check for the existence of
|
|
|
|
# `_get_raw_response_socket` in the docker.Client class, which was
|
|
|
|
# added in 0.3.0
|
|
|
|
version = (0, 3, 0)
|
|
|
|
else:
|
|
|
|
# This is untrue but this module does not function with a version less
|
|
|
|
# than 0.3.0 so it's okay to lie here.
|
|
|
|
version = (0,)
|
|
|
|
|
2014-12-24 03:04:04 +01:00
|
|
|
return tuple(version)
|
2014-12-18 20:23:44 +01:00
|
|
|
|
2015-02-17 22:27:00 +01:00
|
|
|
|
2014-12-18 20:23:44 +01:00
|
|
|
def check_dependencies(module):
|
|
|
|
"""
|
|
|
|
Ensure `docker-py` >= 0.3.0 is installed, and call module.fail_json with a
|
|
|
|
helpful error message if it isn't.
|
|
|
|
"""
|
|
|
|
if not HAS_DOCKER_PY:
|
|
|
|
module.fail_json(msg="`docker-py` doesn't seem to be installed, but is required for the Ansible Docker module.")
|
|
|
|
else:
|
|
|
|
versioninfo = get_docker_py_versioninfo()
|
|
|
|
if versioninfo < (0, 3, 0):
|
|
|
|
module.fail_json(msg="The Ansible Docker module requires `docker-py` >= 0.3.0.")
|
|
|
|
|
|
|
|
|
2014-12-18 22:43:55 +01:00
|
|
|
class DockerManager(object):
|
2014-02-26 00:24:46 +01:00
|
|
|
|
2015-02-17 22:27:00 +01:00
|
|
|
counters = dict(
|
|
|
|
created=0, started=0, stopped=0, killed=0, removed=0, restarted=0, pulled=0
|
|
|
|
)
|
|
|
|
reload_reasons = []
|
2014-12-18 20:23:44 +01:00
|
|
|
_capabilities = set()
|
2015-02-17 22:27:00 +01:00
|
|
|
|
2014-12-18 20:23:44 +01:00
|
|
|
# Map optional parameters to minimum (docker-py version, server APIVersion)
|
|
|
|
# docker-py version is a tuple of ints because we have to compare them
|
|
|
|
# server APIVersion is passed to a docker-py function that takes strings
|
|
|
|
_cap_ver_req = {
|
2015-11-03 15:11:18 +01:00
|
|
|
'devices': ((0, 7, 0), '1.2'),
|
2014-12-18 20:23:44 +01:00
|
|
|
'dns': ((0, 3, 0), '1.10'),
|
2014-12-26 05:31:06 +01:00
|
|
|
'volumes_from': ((0, 3, 0), '1.10'),
|
2014-12-18 20:23:44 +01:00
|
|
|
'restart_policy': ((0, 5, 0), '1.14'),
|
2015-04-07 09:08:43 +02:00
|
|
|
'extra_hosts': ((0, 7, 0), '1.3.1'),
|
2015-03-13 15:31:55 +01:00
|
|
|
'pid': ((1, 0, 0), '1.17'),
|
2015-05-23 00:36:38 +02:00
|
|
|
'log_driver': ((1, 2, 0), '1.18'),
|
2015-09-08 17:19:26 +02:00
|
|
|
'log_opt': ((1, 2, 0), '1.18'),
|
2015-04-27 10:58:20 +02:00
|
|
|
'host_config': ((0, 7, 0), '1.15'),
|
2015-06-29 22:15:25 +02:00
|
|
|
'cpu_set': ((0, 6, 0), '1.14'),
|
2014-10-18 15:25:07 +02:00
|
|
|
'cap_add': ((0, 5, 0), '1.14'),
|
|
|
|
'cap_drop': ((0, 5, 0), '1.14'),
|
2015-07-23 16:45:01 +02:00
|
|
|
'read_only': ((1, 0, 0), '1.17'),
|
2015-09-25 22:58:20 +02:00
|
|
|
'labels': ((1, 2, 0), '1.18'),
|
2015-09-24 07:15:59 +02:00
|
|
|
'stop_timeout': ((0, 5, 0), '1.0'),
|
2014-12-18 21:45:13 +01:00
|
|
|
# Clientside only
|
|
|
|
'insecure_registry': ((0, 5, 0), '0.0')
|
2014-12-18 20:23:44 +01:00
|
|
|
}
|
2013-10-14 00:07:27 +02:00
|
|
|
|
|
|
|
def __init__(self, module):
|
|
|
|
self.module = module
|
2014-02-26 00:24:46 +01:00
|
|
|
|
2013-10-24 07:56:02 +02:00
|
|
|
self.binds = None
|
|
|
|
self.volumes = None
|
|
|
|
if self.module.params.get('volumes'):
|
|
|
|
self.binds = {}
|
2015-03-12 12:55:14 +01:00
|
|
|
self.volumes = []
|
2014-03-18 21:13:12 +01:00
|
|
|
vols = self.module.params.get('volumes')
|
2013-10-24 07:56:02 +02:00
|
|
|
for vol in vols:
|
|
|
|
parts = vol.split(":")
|
2014-12-21 16:10:39 +01:00
|
|
|
# regular volume
|
|
|
|
if len(parts) == 1:
|
2015-03-12 12:55:14 +01:00
|
|
|
self.volumes.append(parts[0])
|
2013-10-24 07:56:02 +02:00
|
|
|
# host mount (e.g. /mnt:/tmp, bind mounts host's /tmp to /mnt in the container)
|
2014-12-21 16:10:39 +01:00
|
|
|
elif 2 <= len(parts) <= 3:
|
|
|
|
# default to read-write
|
2015-11-11 15:44:01 +01:00
|
|
|
mode = 'rw'
|
2015-06-29 22:15:25 +02:00
|
|
|
# with supplied bind mode
|
2014-12-21 16:10:39 +01:00
|
|
|
if len(parts) == 3:
|
2015-11-12 09:42:26 +01:00
|
|
|
if parts[2] not in ["rw", "rw,Z", "rw,z", "z,rw", "Z,rw", "Z", "z", "ro", "ro,Z", "ro,z", "z,ro", "Z,ro"]:
|
|
|
|
self.module.fail_json(msg='invalid bind mode ' + parts[2])
|
2014-12-21 16:10:39 +01:00
|
|
|
else:
|
2015-11-11 15:44:01 +01:00
|
|
|
mode = parts[2]
|
|
|
|
self.binds[parts[0]] = {'bind': parts[1], 'mode': mode }
|
2013-10-24 07:56:02 +02:00
|
|
|
else:
|
2014-12-21 16:10:39 +01:00
|
|
|
self.module.fail_json(msg='volumes support 1 to 3 arguments')
|
2013-10-24 07:56:02 +02:00
|
|
|
|
|
|
|
self.lxc_conf = None
|
|
|
|
if self.module.params.get('lxc_conf'):
|
|
|
|
self.lxc_conf = []
|
2014-03-18 21:13:12 +01:00
|
|
|
options = self.module.params.get('lxc_conf')
|
2013-10-24 07:56:02 +02:00
|
|
|
for option in options:
|
2015-04-28 17:33:26 +02:00
|
|
|
parts = option.split(':', 1)
|
2013-10-24 07:56:02 +02:00
|
|
|
self.lxc_conf.append({"Key": parts[0], "Value": parts[1]})
|
|
|
|
|
2014-02-26 00:24:46 +01:00
|
|
|
self.exposed_ports = None
|
|
|
|
if self.module.params.get('expose'):
|
2014-03-18 21:13:12 +01:00
|
|
|
self.exposed_ports = self.get_exposed_ports(self.module.params.get('expose'))
|
2014-01-22 13:04:19 +01:00
|
|
|
|
|
|
|
self.port_bindings = None
|
2014-02-26 00:24:46 +01:00
|
|
|
if self.module.params.get('ports'):
|
2014-03-18 21:13:12 +01:00
|
|
|
self.port_bindings = self.get_port_bindings(self.module.params.get('ports'))
|
2014-01-22 13:04:19 +01:00
|
|
|
|
|
|
|
self.links = None
|
|
|
|
if self.module.params.get('links'):
|
2014-06-10 14:30:27 +02:00
|
|
|
self.links = self.get_links(self.module.params.get('links'))
|
2013-10-24 07:56:02 +02:00
|
|
|
|
2014-08-15 18:03:29 +02:00
|
|
|
self.env = self.module.params.get('env', None)
|
2013-11-03 21:48:03 +01:00
|
|
|
|
2015-02-18 16:29:53 +01:00
|
|
|
# Connect to the docker server using any configured host and TLS settings.
|
|
|
|
|
|
|
|
env_host = os.getenv('DOCKER_HOST')
|
2015-03-16 19:43:52 +01:00
|
|
|
env_docker_verify = os.getenv('DOCKER_TLS_VERIFY')
|
2015-02-18 16:29:53 +01:00
|
|
|
env_cert_path = os.getenv('DOCKER_CERT_PATH')
|
2015-03-12 19:07:22 +01:00
|
|
|
env_docker_hostname = os.getenv('DOCKER_TLS_HOSTNAME')
|
2015-02-18 16:29:53 +01:00
|
|
|
|
|
|
|
docker_url = module.params.get('docker_url')
|
|
|
|
if not docker_url:
|
|
|
|
if env_host:
|
|
|
|
docker_url = env_host
|
|
|
|
else:
|
|
|
|
docker_url = 'unix://var/run/docker.sock'
|
|
|
|
|
2015-05-01 04:09:22 +02:00
|
|
|
docker_api_version = module.params.get('docker_api_version')
|
2016-01-09 19:01:02 +01:00
|
|
|
timeout = module.params.get('timeout')
|
2015-02-18 16:29:53 +01:00
|
|
|
|
2015-03-12 04:27:29 +01:00
|
|
|
tls_client_cert = module.params.get('tls_client_cert', None)
|
|
|
|
if not tls_client_cert and env_cert_path:
|
|
|
|
tls_client_cert = os.path.join(env_cert_path, 'cert.pem')
|
|
|
|
|
|
|
|
tls_client_key = module.params.get('tls_client_key', None)
|
|
|
|
if not tls_client_key and env_cert_path:
|
|
|
|
tls_client_key = os.path.join(env_cert_path, 'key.pem')
|
|
|
|
|
|
|
|
tls_ca_cert = module.params.get('tls_ca_cert')
|
|
|
|
if not tls_ca_cert and env_cert_path:
|
|
|
|
tls_ca_cert = os.path.join(env_cert_path, 'ca.pem')
|
|
|
|
|
2015-03-12 20:53:48 +01:00
|
|
|
tls_hostname = module.params.get('tls_hostname')
|
|
|
|
if tls_hostname is None:
|
|
|
|
if env_docker_hostname:
|
|
|
|
tls_hostname = env_docker_hostname
|
|
|
|
else:
|
|
|
|
parsed_url = urlparse(docker_url)
|
|
|
|
if ':' in parsed_url.netloc:
|
|
|
|
tls_hostname = parsed_url.netloc[:parsed_url.netloc.rindex(':')]
|
2015-03-12 04:27:29 +01:00
|
|
|
else:
|
2015-03-12 20:53:48 +01:00
|
|
|
tls_hostname = parsed_url
|
|
|
|
if not tls_hostname:
|
|
|
|
tls_hostname = True
|
2015-03-12 04:27:29 +01:00
|
|
|
|
|
|
|
# use_tls can be one of four values:
|
|
|
|
# no: Do not use tls
|
|
|
|
# encrypt: Use tls. We may do client auth. We will not verify the server
|
|
|
|
# verify: Use tls. We may do client auth. We will verify the server
|
2015-03-12 19:07:22 +01:00
|
|
|
# None: Only use tls if the parameters for client auth were specified
|
|
|
|
# or tls_ca_cert (which requests verifying the server with
|
|
|
|
# a specific ca certificate)
|
2015-03-12 04:27:29 +01:00
|
|
|
use_tls = module.params.get('use_tls')
|
2015-03-16 19:43:52 +01:00
|
|
|
if use_tls is None and env_docker_verify is not None:
|
|
|
|
use_tls = 'verify'
|
|
|
|
|
2015-03-15 06:59:17 +01:00
|
|
|
tls_config = None
|
|
|
|
if use_tls != 'no':
|
2015-03-12 04:27:29 +01:00
|
|
|
params = {}
|
|
|
|
|
|
|
|
# Setup client auth
|
|
|
|
if tls_client_cert and tls_client_key:
|
|
|
|
params['client_cert'] = (tls_client_cert, tls_client_key)
|
|
|
|
|
|
|
|
# We're allowed to verify the connection to the server
|
2015-03-12 19:07:22 +01:00
|
|
|
if use_tls == 'verify' or (use_tls is None and tls_ca_cert):
|
2015-03-12 04:27:29 +01:00
|
|
|
if tls_ca_cert:
|
|
|
|
params['ca_cert'] = tls_ca_cert
|
|
|
|
params['verify'] = True
|
|
|
|
params['assert_hostname'] = tls_hostname
|
|
|
|
else:
|
|
|
|
params['verify'] = True
|
|
|
|
params['assert_hostname'] = tls_hostname
|
2015-03-19 19:30:36 +01:00
|
|
|
elif use_tls == 'encrypt':
|
2015-03-12 20:53:48 +01:00
|
|
|
params['verify'] = False
|
2015-02-18 16:29:53 +01:00
|
|
|
|
2015-03-12 20:53:48 +01:00
|
|
|
if params:
|
2015-03-12 04:27:29 +01:00
|
|
|
# See https://github.com/docker/docker-py/blob/d39da11/docker/utils/utils.py#L279-L296
|
|
|
|
docker_url = docker_url.replace('tcp://', 'https://')
|
|
|
|
tls_config = docker.tls.TLSConfig(**params)
|
2015-02-18 16:29:53 +01:00
|
|
|
|
|
|
|
self.client = docker.Client(base_url=docker_url,
|
|
|
|
version=docker_api_version,
|
2016-01-09 19:01:02 +01:00
|
|
|
tls=tls_config,
|
|
|
|
timeout=timeout)
|
2014-02-26 00:24:46 +01:00
|
|
|
|
2014-12-18 20:23:44 +01:00
|
|
|
self.docker_py_versioninfo = get_docker_py_versioninfo()
|
|
|
|
|
2015-05-04 13:54:03 +02:00
|
|
|
def _check_capabilities(self):
|
2014-12-18 20:23:44 +01:00
|
|
|
"""
|
|
|
|
Create a list of available capabilities
|
|
|
|
"""
|
|
|
|
api_version = self.client.version()['ApiVersion']
|
|
|
|
for cap, req_vers in self._cap_ver_req.items():
|
|
|
|
if (self.docker_py_versioninfo >= req_vers[0] and
|
|
|
|
docker.utils.compare_version(req_vers[1], api_version) >= 0):
|
|
|
|
self._capabilities.add(cap)
|
|
|
|
|
2014-12-18 21:45:13 +01:00
|
|
|
def ensure_capability(self, capability, fail=True):
|
2014-12-18 20:23:44 +01:00
|
|
|
"""
|
|
|
|
Some of the functionality this ansible module implements are only
|
|
|
|
available in newer versions of docker. Ensure that the capability
|
|
|
|
is available here.
|
2014-12-18 21:45:13 +01:00
|
|
|
|
|
|
|
If fail is set to False then return True or False depending on whether
|
|
|
|
we have the capability. Otherwise, simply fail and exit the module if
|
|
|
|
we lack the capability.
|
2014-12-18 20:23:44 +01:00
|
|
|
"""
|
|
|
|
if not self._capabilities:
|
2015-05-04 13:54:03 +02:00
|
|
|
self._check_capabilities()
|
2014-12-18 20:23:44 +01:00
|
|
|
|
|
|
|
if capability in self._capabilities:
|
|
|
|
return True
|
|
|
|
|
2014-12-18 21:45:13 +01:00
|
|
|
if not fail:
|
|
|
|
return False
|
|
|
|
|
2014-12-18 20:23:44 +01:00
|
|
|
api_version = self.client.version()['ApiVersion']
|
|
|
|
self.module.fail_json(msg='Specifying the `%s` parameter requires'
|
|
|
|
' docker-py: %s, docker server apiversion %s; found'
|
|
|
|
' docker-py: %s, server: %s' % (
|
|
|
|
capability,
|
2015-03-18 14:28:32 +01:00
|
|
|
'.'.join(map(str, self._cap_ver_req[capability][0])),
|
2014-12-18 20:23:44 +01:00
|
|
|
self._cap_ver_req[capability][1],
|
2015-03-18 14:28:32 +01:00
|
|
|
'.'.join(map(str, self.docker_py_versioninfo)),
|
2014-12-18 20:23:44 +01:00
|
|
|
api_version))
|
2014-02-26 00:24:46 +01:00
|
|
|
|
2014-06-10 14:30:27 +02:00
|
|
|
def get_links(self, links):
|
|
|
|
"""
|
|
|
|
Parse the links passed, if a link is specified without an alias then just create the alias of the same name as the link
|
|
|
|
"""
|
|
|
|
processed_links = {}
|
|
|
|
|
|
|
|
for link in links:
|
|
|
|
parsed_link = link.split(':', 1)
|
|
|
|
if(len(parsed_link) == 2):
|
|
|
|
processed_links[parsed_link[0]] = parsed_link[1]
|
|
|
|
else:
|
|
|
|
processed_links[parsed_link[0]] = parsed_link[0]
|
|
|
|
|
|
|
|
return processed_links
|
|
|
|
|
2014-02-26 00:24:46 +01:00
|
|
|
def get_exposed_ports(self, expose_list):
|
|
|
|
"""
|
|
|
|
Parse the ports and protocols (TCP/UDP) to expose in the docker-py `create_container` call from the docker CLI-style syntax.
|
|
|
|
"""
|
|
|
|
if expose_list:
|
|
|
|
exposed = []
|
|
|
|
for port in expose_list:
|
2014-09-17 04:38:49 +02:00
|
|
|
port = str(port).strip()
|
2014-02-26 00:24:46 +01:00
|
|
|
if port.endswith('/tcp') or port.endswith('/udp'):
|
|
|
|
port_with_proto = tuple(port.split('/'))
|
|
|
|
else:
|
|
|
|
# assume tcp protocol if not specified
|
|
|
|
port_with_proto = (port, 'tcp')
|
|
|
|
exposed.append(port_with_proto)
|
|
|
|
return exposed
|
|
|
|
else:
|
|
|
|
return None
|
|
|
|
|
2015-04-27 10:58:20 +02:00
|
|
|
def get_start_params(self):
|
|
|
|
"""
|
|
|
|
Create start params
|
|
|
|
"""
|
|
|
|
params = {
|
|
|
|
'lxc_conf': self.lxc_conf,
|
|
|
|
'binds': self.binds,
|
|
|
|
'port_bindings': self.port_bindings,
|
|
|
|
'publish_all_ports': self.module.params.get('publish_all_ports'),
|
|
|
|
'privileged': self.module.params.get('privileged'),
|
|
|
|
'links': self.links,
|
|
|
|
'network_mode': self.module.params.get('net'),
|
|
|
|
}
|
|
|
|
|
|
|
|
optionals = {}
|
2015-12-19 01:33:48 +01:00
|
|
|
for optional_param in ('devices', 'dns', 'volumes_from',
|
|
|
|
'restart_policy', 'restart_policy_retry', 'pid', 'extra_hosts',
|
2015-11-03 15:11:18 +01:00
|
|
|
'log_driver', 'cap_add', 'cap_drop', 'read_only', 'log_opt'):
|
2015-04-27 10:58:20 +02:00
|
|
|
optionals[optional_param] = self.module.params.get(optional_param)
|
|
|
|
|
2015-11-03 15:11:18 +01:00
|
|
|
if optionals['devices'] is not None:
|
|
|
|
self.ensure_capability('devices')
|
|
|
|
params['devices'] = optionals['devices']
|
|
|
|
|
2015-04-27 10:58:20 +02:00
|
|
|
if optionals['dns'] is not None:
|
|
|
|
self.ensure_capability('dns')
|
|
|
|
params['dns'] = optionals['dns']
|
|
|
|
|
|
|
|
if optionals['volumes_from'] is not None:
|
|
|
|
self.ensure_capability('volumes_from')
|
|
|
|
params['volumes_from'] = optionals['volumes_from']
|
|
|
|
|
|
|
|
if optionals['restart_policy'] is not None:
|
|
|
|
self.ensure_capability('restart_policy')
|
|
|
|
params['restart_policy'] = { 'Name': optionals['restart_policy'] }
|
|
|
|
if params['restart_policy']['Name'] == 'on-failure':
|
|
|
|
params['restart_policy']['MaximumRetryCount'] = optionals['restart_policy_retry']
|
|
|
|
|
2015-09-04 00:39:18 +02:00
|
|
|
# docker_py only accepts 'host' or None
|
|
|
|
if 'pid' in optionals and not optionals['pid']:
|
|
|
|
optionals['pid'] = None
|
|
|
|
|
2015-04-27 10:58:20 +02:00
|
|
|
if optionals['pid'] is not None:
|
|
|
|
self.ensure_capability('pid')
|
|
|
|
params['pid_mode'] = optionals['pid']
|
|
|
|
|
2015-09-04 00:39:18 +02:00
|
|
|
if optionals['extra_hosts'] is not None:
|
|
|
|
self.ensure_capability('extra_hosts')
|
|
|
|
params['extra_hosts'] = optionals['extra_hosts']
|
|
|
|
|
|
|
|
if optionals['log_driver'] is not None:
|
|
|
|
self.ensure_capability('log_driver')
|
|
|
|
log_config = docker.utils.LogConfig(type=docker.utils.LogConfig.types.JSON)
|
2015-09-08 17:19:26 +02:00
|
|
|
if optionals['log_opt'] is not None:
|
|
|
|
for k, v in optionals['log_opt'].iteritems():
|
|
|
|
log_config.set_config_value(k, v)
|
2015-09-04 00:39:18 +02:00
|
|
|
log_config.type = optionals['log_driver']
|
|
|
|
params['log_config'] = log_config
|
|
|
|
|
|
|
|
if optionals['cap_add'] is not None:
|
|
|
|
self.ensure_capability('cap_add')
|
|
|
|
params['cap_add'] = optionals['cap_add']
|
|
|
|
|
|
|
|
if optionals['cap_drop'] is not None:
|
|
|
|
self.ensure_capability('cap_drop')
|
|
|
|
params['cap_drop'] = optionals['cap_drop']
|
|
|
|
|
2015-09-05 00:59:19 +02:00
|
|
|
if optionals['read_only'] is not None:
|
|
|
|
self.ensure_capability('read_only')
|
|
|
|
params['read_only'] = optionals['read_only']
|
|
|
|
|
2015-04-27 10:58:20 +02:00
|
|
|
return params
|
|
|
|
|
2015-09-04 00:39:18 +02:00
|
|
|
def create_host_config(self):
|
2015-04-27 10:58:20 +02:00
|
|
|
"""
|
|
|
|
Create HostConfig object
|
|
|
|
"""
|
|
|
|
params = self.get_start_params()
|
|
|
|
return docker.utils.create_host_config(**params)
|
|
|
|
|
2014-02-26 00:24:46 +01:00
|
|
|
def get_port_bindings(self, ports):
|
|
|
|
"""
|
|
|
|
Parse the `ports` string into a port bindings dict for the `start_container` call.
|
|
|
|
"""
|
|
|
|
binds = {}
|
|
|
|
for port in ports:
|
2014-03-18 21:13:12 +01:00
|
|
|
# ports could potentially be an array like [80, 443], so we make sure they're strings
|
|
|
|
# before splitting
|
|
|
|
parts = str(port).split(':')
|
2014-02-26 00:24:46 +01:00
|
|
|
container_port = parts[-1]
|
|
|
|
if '/' not in container_port:
|
|
|
|
container_port = int(parts[-1])
|
|
|
|
|
|
|
|
p_len = len(parts)
|
|
|
|
if p_len == 1:
|
|
|
|
# Bind `container_port` of the container to a dynamically
|
|
|
|
# allocated TCP port on all available interfaces of the host
|
|
|
|
# machine.
|
|
|
|
bind = ('0.0.0.0',)
|
|
|
|
elif p_len == 2:
|
|
|
|
# Bind `container_port` of the container to port `parts[0]` on
|
|
|
|
# all available interfaces of the host machine.
|
|
|
|
bind = ('0.0.0.0', int(parts[0]))
|
|
|
|
elif p_len == 3:
|
|
|
|
# Bind `container_port` of the container to port `parts[1]` on
|
|
|
|
# IP `parts[0]` of the host machine. If `parts[1]` empty bind
|
2015-05-04 13:54:03 +02:00
|
|
|
# to a dynamically allocated port of IP `parts[0]`.
|
2014-02-26 00:24:46 +01:00
|
|
|
bind = (parts[0], int(parts[1])) if parts[1] else (parts[0],)
|
|
|
|
|
|
|
|
if container_port in binds:
|
|
|
|
old_bind = binds[container_port]
|
|
|
|
if isinstance(old_bind, list):
|
|
|
|
# append to list if it already exists
|
|
|
|
old_bind.append(bind)
|
|
|
|
else:
|
|
|
|
# otherwise create list that contains the old and new binds
|
|
|
|
binds[container_port] = [binds[container_port], bind]
|
|
|
|
else:
|
|
|
|
binds[container_port] = bind
|
|
|
|
|
|
|
|
return binds
|
|
|
|
|
2015-02-17 22:27:00 +01:00
|
|
|
def get_summary_message(self):
|
|
|
|
'''
|
|
|
|
Generate a message that briefly describes the actions taken by this
|
|
|
|
task, in English.
|
|
|
|
'''
|
|
|
|
|
|
|
|
parts = []
|
|
|
|
for k, v in self.counters.iteritems():
|
|
|
|
if v == 0:
|
|
|
|
continue
|
|
|
|
|
|
|
|
if v == 1:
|
|
|
|
plural = ""
|
|
|
|
else:
|
|
|
|
plural = "s"
|
|
|
|
parts.append("%s %d container%s" % (k, v, plural))
|
|
|
|
|
|
|
|
if parts:
|
|
|
|
return ", ".join(parts) + "."
|
|
|
|
else:
|
|
|
|
return "No action taken."
|
|
|
|
|
|
|
|
def get_reload_reason_message(self):
|
|
|
|
'''
|
|
|
|
Generate a message describing why any reloaded containers were reloaded.
|
|
|
|
'''
|
|
|
|
|
|
|
|
if self.reload_reasons:
|
|
|
|
return ", ".join(self.reload_reasons)
|
|
|
|
else:
|
|
|
|
return None
|
2014-02-26 00:24:46 +01:00
|
|
|
|
2013-10-14 00:07:27 +02:00
|
|
|
def get_summary_counters_msg(self):
|
|
|
|
msg = ""
|
|
|
|
for k, v in self.counters.iteritems():
|
|
|
|
msg = msg + "%s %d " % (k, v)
|
|
|
|
|
|
|
|
return msg
|
2014-02-26 00:24:46 +01:00
|
|
|
|
2013-10-14 00:07:27 +02:00
|
|
|
def increment_counter(self, name):
|
|
|
|
self.counters[name] = self.counters[name] + 1
|
|
|
|
|
|
|
|
def has_changed(self):
|
|
|
|
for k, v in self.counters.iteritems():
|
|
|
|
if v > 0:
|
|
|
|
return True
|
|
|
|
|
|
|
|
return False
|
2014-02-26 00:24:46 +01:00
|
|
|
|
2014-12-12 17:14:24 +01:00
|
|
|
def get_inspect_image(self):
|
2015-03-09 15:05:56 +01:00
|
|
|
try:
|
|
|
|
return self.client.inspect_image(self.module.params.get('image'))
|
|
|
|
except DockerAPIError as e:
|
|
|
|
if e.response.status_code == 404:
|
|
|
|
return None
|
|
|
|
else:
|
|
|
|
raise e
|
|
|
|
|
|
|
|
def get_image_repo_tags(self):
|
2014-12-12 17:14:24 +01:00
|
|
|
image, tag = get_split_image_tag(self.module.params.get('image'))
|
|
|
|
if tag is None:
|
|
|
|
tag = 'latest'
|
|
|
|
resource = '%s:%s' % (image, tag)
|
|
|
|
|
|
|
|
for image in self.client.images(name=image):
|
|
|
|
if resource in image.get('RepoTags', []):
|
2015-03-09 15:05:56 +01:00
|
|
|
return image['RepoTags']
|
2015-05-01 02:44:05 +02:00
|
|
|
return []
|
2014-12-12 17:14:24 +01:00
|
|
|
|
2013-10-24 07:56:02 +02:00
|
|
|
def get_inspect_containers(self, containers):
|
|
|
|
inspect = []
|
|
|
|
for i in containers:
|
|
|
|
details = self.client.inspect_container(i['Id'])
|
|
|
|
details = _docker_id_quirk(details)
|
|
|
|
inspect.append(details)
|
|
|
|
|
|
|
|
return inspect
|
2013-10-14 00:07:27 +02:00
|
|
|
|
2015-02-17 22:27:00 +01:00
|
|
|
def get_differing_containers(self):
|
|
|
|
"""
|
|
|
|
Inspect all matching, running containers, and return those that were
|
|
|
|
started with parameters that differ from the ones that are provided
|
|
|
|
during this module run. A list containing the differing
|
|
|
|
containers will be returned, and a short string describing the specific
|
|
|
|
difference encountered in each container will be appended to
|
|
|
|
reload_reasons.
|
|
|
|
|
|
|
|
This generates the set of containers that need to be stopped and
|
|
|
|
started with new parameters with state=reloaded.
|
|
|
|
"""
|
|
|
|
|
|
|
|
running = self.get_running_containers()
|
|
|
|
current = self.get_inspect_containers(running)
|
|
|
|
|
2015-07-23 20:34:33 +02:00
|
|
|
#Get API version
|
|
|
|
api_version = self.client.version()['ApiVersion']
|
|
|
|
|
2015-02-17 22:27:00 +01:00
|
|
|
image = self.get_inspect_image()
|
|
|
|
if image is None:
|
|
|
|
# The image isn't present. Assume that we're about to pull a new
|
|
|
|
# tag and *everything* will be restarted.
|
|
|
|
#
|
|
|
|
# This will give false positives if you untag an image on the host
|
|
|
|
# and there's nothing more to pull.
|
|
|
|
return current
|
|
|
|
|
|
|
|
differing = []
|
|
|
|
|
|
|
|
for container in current:
|
|
|
|
|
|
|
|
# IMAGE
|
|
|
|
# Compare the image by ID rather than name, so that containers
|
|
|
|
# will be restarted when new versions of an existing image are
|
|
|
|
# pulled.
|
|
|
|
if container['Image'] != image['Id']:
|
2015-03-09 17:54:22 +01:00
|
|
|
self.reload_reasons.append('image ({0} => {1})'.format(container['Image'], image['Id']))
|
2015-02-17 22:27:00 +01:00
|
|
|
differing.append(container)
|
|
|
|
continue
|
|
|
|
|
2015-10-02 00:09:08 +02:00
|
|
|
# ENTRYPOINT
|
|
|
|
|
|
|
|
expected_entrypoint = self.module.params.get('entrypoint')
|
|
|
|
if expected_entrypoint:
|
|
|
|
expected_entrypoint = shlex.split(expected_entrypoint)
|
|
|
|
actual_entrypoint = container["Config"]["Entrypoint"]
|
|
|
|
|
|
|
|
if actual_entrypoint != expected_entrypoint:
|
|
|
|
self.reload_reasons.append(
|
|
|
|
'entrypoint ({0} => {1})'
|
|
|
|
.format(actual_entrypoint, expected_entrypoint)
|
|
|
|
)
|
|
|
|
differing.append(container)
|
|
|
|
continue
|
|
|
|
|
2015-02-17 22:27:00 +01:00
|
|
|
# COMMAND
|
|
|
|
|
|
|
|
expected_command = self.module.params.get('command')
|
|
|
|
if expected_command:
|
|
|
|
expected_command = shlex.split(expected_command)
|
|
|
|
actual_command = container["Config"]["Cmd"]
|
|
|
|
|
|
|
|
if actual_command != expected_command:
|
2015-03-09 17:54:22 +01:00
|
|
|
self.reload_reasons.append('command ({0} => {1})'.format(actual_command, expected_command))
|
2015-02-17 22:27:00 +01:00
|
|
|
differing.append(container)
|
|
|
|
continue
|
|
|
|
|
|
|
|
# EXPOSED PORTS
|
2015-10-13 12:24:36 +02:00
|
|
|
expected_exposed_ports = set((image['ContainerConfig'].get('ExposedPorts') or {}).keys())
|
2015-02-17 22:27:00 +01:00
|
|
|
for p in (self.exposed_ports or []):
|
|
|
|
expected_exposed_ports.add("/".join(p))
|
|
|
|
|
2015-10-13 12:34:08 +02:00
|
|
|
actually_exposed_ports = set((container["Config"].get("ExposedPorts") or {}).keys())
|
2015-02-17 22:27:00 +01:00
|
|
|
|
|
|
|
if actually_exposed_ports != expected_exposed_ports:
|
2015-03-09 17:54:22 +01:00
|
|
|
self.reload_reasons.append('exposed_ports ({0} => {1})'.format(actually_exposed_ports, expected_exposed_ports))
|
2015-02-17 22:27:00 +01:00
|
|
|
differing.append(container)
|
|
|
|
continue
|
|
|
|
|
|
|
|
# VOLUMES
|
|
|
|
|
2015-03-09 15:20:04 +01:00
|
|
|
expected_volume_keys = set((image['ContainerConfig']['Volumes'] or {}).keys())
|
2015-02-17 22:27:00 +01:00
|
|
|
if self.volumes:
|
2015-08-23 11:29:39 +02:00
|
|
|
expected_volume_keys.update(self.volumes)
|
2015-03-09 16:20:14 +01:00
|
|
|
|
2015-02-17 22:27:00 +01:00
|
|
|
actual_volume_keys = set((container['Config']['Volumes'] or {}).keys())
|
|
|
|
|
|
|
|
if actual_volume_keys != expected_volume_keys:
|
2015-03-09 17:54:22 +01:00
|
|
|
self.reload_reasons.append('volumes ({0} => {1})'.format(actual_volume_keys, expected_volume_keys))
|
2015-02-17 22:27:00 +01:00
|
|
|
differing.append(container)
|
|
|
|
continue
|
|
|
|
|
2015-11-26 15:49:18 +01:00
|
|
|
# CPU_SHARES
|
|
|
|
|
|
|
|
expected_cpu_shares = self.module.params.get('cpu_shares')
|
|
|
|
actual_cpu_shares = container['HostConfig']['CpuShares']
|
|
|
|
|
|
|
|
if expected_cpu_shares and actual_cpu_shares != expected_cpu_shares:
|
|
|
|
self.reload_reasons.append('cpu_shares ({0} => {1})'.format(actual_cpu_shares, expected_cpu_shares))
|
|
|
|
differing.append(container)
|
|
|
|
continue
|
|
|
|
|
2015-02-17 22:27:00 +01:00
|
|
|
# MEM_LIMIT
|
|
|
|
|
2015-05-11 21:15:53 +02:00
|
|
|
try:
|
|
|
|
expected_mem = _human_to_bytes(self.module.params.get('memory_limit'))
|
|
|
|
except ValueError as e:
|
|
|
|
self.module.fail_json(msg=str(e))
|
|
|
|
|
2015-07-23 21:17:26 +02:00
|
|
|
#For v1.19 API and above use HostConfig, otherwise use Config
|
2015-10-10 01:11:44 +02:00
|
|
|
if docker.utils.compare_version('1.19', api_version) >= 0:
|
2015-07-23 21:17:26 +02:00
|
|
|
actual_mem = container['HostConfig']['Memory']
|
|
|
|
else:
|
2015-07-23 20:34:33 +02:00
|
|
|
actual_mem = container['Config']['Memory']
|
2015-02-17 22:27:00 +01:00
|
|
|
|
|
|
|
if expected_mem and actual_mem != expected_mem:
|
2015-03-09 17:54:22 +01:00
|
|
|
self.reload_reasons.append('memory ({0} => {1})'.format(actual_mem, expected_mem))
|
2015-02-17 22:27:00 +01:00
|
|
|
differing.append(container)
|
|
|
|
continue
|
|
|
|
|
|
|
|
# ENVIRONMENT
|
|
|
|
# actual_env is likely to include environment variables injected by
|
|
|
|
# the Dockerfile.
|
|
|
|
|
2015-03-09 17:17:39 +01:00
|
|
|
expected_env = {}
|
|
|
|
|
|
|
|
for image_env in image['ContainerConfig']['Env'] or []:
|
|
|
|
name, value = image_env.split('=', 1)
|
|
|
|
expected_env[name] = value
|
|
|
|
|
2015-02-17 22:27:00 +01:00
|
|
|
if self.env:
|
|
|
|
for name, value in self.env.iteritems():
|
2015-03-09 20:45:43 +01:00
|
|
|
expected_env[name] = str(value)
|
2015-03-09 17:17:39 +01:00
|
|
|
|
|
|
|
actual_env = {}
|
|
|
|
for container_env in container['Config']['Env'] or []:
|
|
|
|
name, value = container_env.split('=', 1)
|
|
|
|
actual_env[name] = value
|
2015-02-17 22:27:00 +01:00
|
|
|
|
2015-03-09 15:20:04 +01:00
|
|
|
if actual_env != expected_env:
|
2015-02-17 22:27:00 +01:00
|
|
|
# Don't include the environment difference in the output.
|
2015-03-09 20:45:43 +01:00
|
|
|
self.reload_reasons.append('environment {0} => {1}'.format(actual_env, expected_env))
|
2015-02-17 22:27:00 +01:00
|
|
|
differing.append(container)
|
|
|
|
continue
|
|
|
|
|
2015-09-25 22:58:20 +02:00
|
|
|
# LABELS
|
|
|
|
|
|
|
|
expected_labels = {}
|
|
|
|
for name, value in self.module.params.get('labels').iteritems():
|
|
|
|
expected_labels[name] = str(value)
|
|
|
|
|
|
|
|
actual_labels = {}
|
|
|
|
for container_label in container['Config']['Labels'] or []:
|
|
|
|
name, value = container_label.split('=', 1)
|
|
|
|
actual_labels[name] = value
|
|
|
|
|
|
|
|
if actual_labels != expected_labels:
|
|
|
|
self.reload_reasons.append('labels {0} => {1}'.format(actual_labels, expected_labels))
|
|
|
|
differing.append(container)
|
|
|
|
continue
|
|
|
|
|
2015-02-17 22:27:00 +01:00
|
|
|
# HOSTNAME
|
|
|
|
|
|
|
|
expected_hostname = self.module.params.get('hostname')
|
|
|
|
actual_hostname = container['Config']['Hostname']
|
|
|
|
if expected_hostname and actual_hostname != expected_hostname:
|
2015-03-09 17:54:22 +01:00
|
|
|
self.reload_reasons.append('hostname ({0} => {1})'.format(actual_hostname, expected_hostname))
|
2015-02-17 22:27:00 +01:00
|
|
|
differing.append(container)
|
|
|
|
continue
|
|
|
|
|
|
|
|
# DOMAINNAME
|
|
|
|
|
|
|
|
expected_domainname = self.module.params.get('domainname')
|
|
|
|
actual_domainname = container['Config']['Domainname']
|
|
|
|
if expected_domainname and actual_domainname != expected_domainname:
|
2015-03-09 17:54:22 +01:00
|
|
|
self.reload_reasons.append('domainname ({0} => {1})'.format(actual_domainname, expected_domainname))
|
2015-02-17 22:27:00 +01:00
|
|
|
differing.append(container)
|
|
|
|
continue
|
|
|
|
|
|
|
|
# DETACH
|
|
|
|
|
|
|
|
# We don't have to check for undetached containers. If it wasn't
|
|
|
|
# detached, it would have stopped before the playbook continued!
|
|
|
|
|
|
|
|
# NAME
|
|
|
|
|
|
|
|
# We also don't have to check name, because this is one of the
|
|
|
|
# criteria that's used to determine which container(s) match in
|
|
|
|
# the first place.
|
|
|
|
|
|
|
|
# STDIN_OPEN
|
|
|
|
|
|
|
|
expected_stdin_open = self.module.params.get('stdin_open')
|
|
|
|
actual_stdin_open = container['Config']['AttachStdin']
|
|
|
|
if actual_stdin_open != expected_stdin_open:
|
2015-03-09 17:54:22 +01:00
|
|
|
self.reload_reasons.append('stdin_open ({0} => {1})'.format(actual_stdin_open, expected_stdin_open))
|
2015-02-17 22:27:00 +01:00
|
|
|
differing.append(container)
|
|
|
|
continue
|
|
|
|
|
|
|
|
# TTY
|
|
|
|
|
|
|
|
expected_tty = self.module.params.get('tty')
|
|
|
|
actual_tty = container['Config']['Tty']
|
|
|
|
if actual_tty != expected_tty:
|
2015-03-09 17:54:22 +01:00
|
|
|
self.reload_reasons.append('tty ({0} => {1})'.format(actual_tty, expected_tty))
|
2015-02-17 22:27:00 +01:00
|
|
|
differing.append(container)
|
|
|
|
continue
|
|
|
|
|
|
|
|
# -- "start" call differences --
|
|
|
|
|
|
|
|
# LXC_CONF
|
|
|
|
|
|
|
|
if self.lxc_conf:
|
|
|
|
expected_lxc = set(self.lxc_conf)
|
|
|
|
actual_lxc = set(container['HostConfig']['LxcConf'] or [])
|
|
|
|
if actual_lxc != expected_lxc:
|
2015-03-09 17:54:22 +01:00
|
|
|
self.reload_reasons.append('lxc_conf ({0} => {1})'.format(actual_lxc, expected_lxc))
|
2015-02-17 22:27:00 +01:00
|
|
|
differing.append(container)
|
|
|
|
continue
|
|
|
|
|
|
|
|
# BINDS
|
|
|
|
|
|
|
|
expected_binds = set()
|
|
|
|
if self.binds:
|
|
|
|
for host_path, config in self.binds.iteritems():
|
|
|
|
if isinstance(config, dict):
|
|
|
|
container_path = config['bind']
|
2015-11-11 15:44:01 +01:00
|
|
|
mode = config['mode']
|
2015-02-17 22:27:00 +01:00
|
|
|
else:
|
|
|
|
container_path = config
|
|
|
|
mode = 'rw'
|
2015-03-09 17:54:22 +01:00
|
|
|
expected_binds.add("{0}:{1}:{2}".format(host_path, container_path, mode))
|
2015-02-17 22:27:00 +01:00
|
|
|
|
|
|
|
actual_binds = set()
|
|
|
|
for bind in (container['HostConfig']['Binds'] or []):
|
|
|
|
if len(bind.split(':')) == 2:
|
|
|
|
actual_binds.add(bind + ":rw")
|
|
|
|
else:
|
|
|
|
actual_binds.add(bind)
|
|
|
|
|
|
|
|
if actual_binds != expected_binds:
|
2015-03-09 17:54:22 +01:00
|
|
|
self.reload_reasons.append('binds ({0} => {1})'.format(actual_binds, expected_binds))
|
2015-02-17 22:27:00 +01:00
|
|
|
differing.append(container)
|
|
|
|
continue
|
|
|
|
|
|
|
|
# PORT BINDINGS
|
|
|
|
|
|
|
|
expected_bound_ports = {}
|
|
|
|
if self.port_bindings:
|
|
|
|
for container_port, config in self.port_bindings.iteritems():
|
|
|
|
if isinstance(container_port, int):
|
2015-03-09 17:54:22 +01:00
|
|
|
container_port = "{0}/tcp".format(container_port)
|
2015-02-17 22:27:00 +01:00
|
|
|
if len(config) == 1:
|
2015-06-12 12:36:52 +02:00
|
|
|
expected_bound_ports[container_port] = [{'HostIp': "0.0.0.0", 'HostPort': ""}]
|
|
|
|
elif isinstance(config[0], tuple):
|
|
|
|
expected_bound_ports[container_port] = []
|
|
|
|
for hostip, hostport in config:
|
|
|
|
expected_bound_ports[container_port].append({ 'HostIp': hostip, 'HostPort': str(hostport)})
|
2015-02-17 22:27:00 +01:00
|
|
|
else:
|
2015-06-12 12:36:52 +02:00
|
|
|
expected_bound_ports[container_port] = [{'HostIp': config[0], 'HostPort': str(config[1])}]
|
2015-02-17 22:27:00 +01:00
|
|
|
|
|
|
|
actual_bound_ports = container['HostConfig']['PortBindings'] or {}
|
|
|
|
|
|
|
|
if actual_bound_ports != expected_bound_ports:
|
2015-03-09 17:54:22 +01:00
|
|
|
self.reload_reasons.append('port bindings ({0} => {1})'.format(actual_bound_ports, expected_bound_ports))
|
2015-02-17 22:27:00 +01:00
|
|
|
differing.append(container)
|
|
|
|
continue
|
|
|
|
|
|
|
|
# PUBLISHING ALL PORTS
|
|
|
|
|
|
|
|
# What we really care about is the set of ports that is actually
|
|
|
|
# published. That should be caught above.
|
|
|
|
|
|
|
|
# PRIVILEGED
|
|
|
|
|
|
|
|
expected_privileged = self.module.params.get('privileged')
|
|
|
|
actual_privileged = container['HostConfig']['Privileged']
|
|
|
|
if actual_privileged != expected_privileged:
|
2015-03-09 17:54:22 +01:00
|
|
|
self.reload_reasons.append('privileged ({0} => {1})'.format(actual_privileged, expected_privileged))
|
2015-02-17 22:27:00 +01:00
|
|
|
differing.append(container)
|
|
|
|
continue
|
|
|
|
|
|
|
|
# LINKS
|
|
|
|
|
|
|
|
expected_links = set()
|
|
|
|
for link, alias in (self.links or {}).iteritems():
|
2015-03-09 20:45:43 +01:00
|
|
|
expected_links.add("/{0}:{1}/{2}".format(link, container["Name"], alias))
|
2015-02-17 22:27:00 +01:00
|
|
|
|
|
|
|
actual_links = set(container['HostConfig']['Links'] or [])
|
|
|
|
if actual_links != expected_links:
|
2015-03-09 17:54:22 +01:00
|
|
|
self.reload_reasons.append('links ({0} => {1})'.format(actual_links, expected_links))
|
2015-02-17 22:27:00 +01:00
|
|
|
differing.append(container)
|
|
|
|
continue
|
|
|
|
|
|
|
|
# NETWORK MODE
|
|
|
|
|
2015-06-26 00:11:38 +02:00
|
|
|
expected_netmode = self.module.params.get('net') or 'bridge'
|
|
|
|
actual_netmode = container['HostConfig']['NetworkMode'] or 'bridge'
|
2015-02-17 22:27:00 +01:00
|
|
|
if actual_netmode != expected_netmode:
|
2015-03-09 17:54:22 +01:00
|
|
|
self.reload_reasons.append('net ({0} => {1})'.format(actual_netmode, expected_netmode))
|
2015-02-17 22:27:00 +01:00
|
|
|
differing.append(container)
|
|
|
|
continue
|
|
|
|
|
2015-12-19 01:33:48 +01:00
|
|
|
# DEVICES
|
2015-11-03 15:11:18 +01:00
|
|
|
|
|
|
|
expected_devices = set()
|
|
|
|
for device in (self.module.params.get('devices') or []):
|
|
|
|
if len(device.split(':')) == 2:
|
|
|
|
expected_devices.add(device + ":rwm")
|
|
|
|
else:
|
|
|
|
expected_devices.add(device)
|
|
|
|
|
|
|
|
actual_devices = set()
|
|
|
|
for device in (container['HostConfig']['Devices'] or []):
|
|
|
|
actual_devices.add("{PathOnHost}:{PathInContainer}:{CgroupPermissions}".format(**device))
|
|
|
|
|
|
|
|
if actual_devices != expected_devices:
|
|
|
|
self.reload_reasons.append('devices ({0} => {1})'.format(actual_devices, expected_devices))
|
|
|
|
differing.append(container)
|
|
|
|
continue
|
|
|
|
|
2015-02-17 22:27:00 +01:00
|
|
|
# DNS
|
|
|
|
|
|
|
|
expected_dns = set(self.module.params.get('dns') or [])
|
|
|
|
actual_dns = set(container['HostConfig']['Dns'] or [])
|
|
|
|
if actual_dns != expected_dns:
|
2015-03-09 17:54:22 +01:00
|
|
|
self.reload_reasons.append('dns ({0} => {1})'.format(actual_dns, expected_dns))
|
2015-02-17 22:27:00 +01:00
|
|
|
differing.append(container)
|
|
|
|
continue
|
|
|
|
|
|
|
|
# VOLUMES_FROM
|
|
|
|
|
|
|
|
expected_volumes_from = set(self.module.params.get('volumes_from') or [])
|
|
|
|
actual_volumes_from = set(container['HostConfig']['VolumesFrom'] or [])
|
|
|
|
if actual_volumes_from != expected_volumes_from:
|
2015-03-09 17:54:22 +01:00
|
|
|
self.reload_reasons.append('volumes_from ({0} => {1})'.format(actual_volumes_from, expected_volumes_from))
|
2015-02-17 22:27:00 +01:00
|
|
|
differing.append(container)
|
|
|
|
|
2015-05-23 00:36:38 +02:00
|
|
|
# LOG_DRIVER
|
|
|
|
|
2015-09-08 17:19:26 +02:00
|
|
|
if self.ensure_capability('log_driver', False):
|
2015-06-01 17:48:24 +02:00
|
|
|
expected_log_driver = self.module.params.get('log_driver') or 'json-file'
|
|
|
|
actual_log_driver = container['HostConfig']['LogConfig']['Type']
|
|
|
|
if actual_log_driver != expected_log_driver:
|
|
|
|
self.reload_reasons.append('log_driver ({0} => {1})'.format(actual_log_driver, expected_log_driver))
|
|
|
|
differing.append(container)
|
|
|
|
continue
|
2015-05-23 00:36:38 +02:00
|
|
|
|
2015-09-08 17:19:26 +02:00
|
|
|
if self.ensure_capability('log_opt', False):
|
|
|
|
expected_logging_opts = self.module.params.get('log_opt') or {}
|
|
|
|
actual_log_opts = container['HostConfig']['LogConfig']['Config']
|
|
|
|
if len(set(expected_logging_opts.items()) - set(actual_log_opts.items())) != 0:
|
|
|
|
log_opt_reasons = {
|
|
|
|
'added': dict(set(expected_logging_opts.items()) - set(actual_log_opts.items())),
|
|
|
|
'removed': dict(set(actual_log_opts.items()) - set(expected_logging_opts.items()))
|
|
|
|
}
|
|
|
|
self.reload_reasons.append('log_opt ({0})'.format(log_opt_reasons))
|
|
|
|
differing.append(container)
|
|
|
|
|
2015-02-17 22:27:00 +01:00
|
|
|
return differing
|
|
|
|
|
2013-10-14 00:07:27 +02:00
|
|
|
def get_deployed_containers(self):
|
2015-02-17 22:27:00 +01:00
|
|
|
"""
|
|
|
|
Return any matching containers that are already present.
|
|
|
|
"""
|
|
|
|
|
2015-10-02 00:09:08 +02:00
|
|
|
entrypoint = self.module.params.get('entrypoint')
|
|
|
|
if entrypoint is not None:
|
|
|
|
entrypoint = shlex.split(entrypoint)
|
2014-01-22 13:04:19 +01:00
|
|
|
command = self.module.params.get('command')
|
2015-10-01 23:44:52 +02:00
|
|
|
if command is not None:
|
|
|
|
command = shlex.split(command)
|
2014-01-22 13:04:19 +01:00
|
|
|
name = self.module.params.get('name')
|
|
|
|
if name and not name.startswith('/'):
|
|
|
|
name = '/' + name
|
|
|
|
deployed = []
|
2013-10-14 00:07:27 +02:00
|
|
|
|
2015-02-17 22:27:00 +01:00
|
|
|
# "images" will be a collection of equivalent "name:tag" image names
|
|
|
|
# that map to the same Docker image.
|
|
|
|
inspected = self.get_inspect_image()
|
|
|
|
if inspected:
|
2015-03-09 15:05:56 +01:00
|
|
|
repo_tags = self.get_image_repo_tags()
|
2015-02-17 22:27:00 +01:00
|
|
|
else:
|
2015-03-24 16:07:12 +01:00
|
|
|
repo_tags = [normalize_image(self.module.params.get('image'))]
|
2014-01-22 13:04:19 +01:00
|
|
|
|
2015-05-04 19:16:01 +02:00
|
|
|
for container in self.client.containers(all=True):
|
2015-03-24 16:18:15 +01:00
|
|
|
details = None
|
2015-02-17 22:27:00 +01:00
|
|
|
|
|
|
|
if name:
|
2015-05-04 19:16:01 +02:00
|
|
|
name_list = container.get('Names')
|
|
|
|
if name_list is None:
|
|
|
|
name_list = []
|
|
|
|
matches = name in name_list
|
2015-02-17 22:27:00 +01:00
|
|
|
else:
|
2015-05-06 11:53:40 +02:00
|
|
|
details = self.client.inspect_container(container['Id'])
|
2015-03-24 16:18:15 +01:00
|
|
|
details = _docker_id_quirk(details)
|
|
|
|
|
|
|
|
running_image = normalize_image(details['Config']['Image'])
|
|
|
|
|
2015-03-09 15:05:56 +01:00
|
|
|
image_matches = running_image in repo_tags
|
2013-10-24 07:56:02 +02:00
|
|
|
|
2015-10-01 23:44:52 +02:00
|
|
|
command_matches = command == details['Config']['Cmd']
|
2015-10-02 00:09:08 +02:00
|
|
|
entrypoint_matches = (
|
|
|
|
entrypoint == details['Config']['Entrypoint']
|
|
|
|
)
|
2014-04-18 01:10:53 +02:00
|
|
|
|
2015-10-02 00:09:08 +02:00
|
|
|
matches = (image_matches and command_matches and
|
|
|
|
entrypoint_matches)
|
2015-02-17 22:27:00 +01:00
|
|
|
|
|
|
|
if matches:
|
2015-03-24 16:18:15 +01:00
|
|
|
if not details:
|
2015-05-04 19:16:01 +02:00
|
|
|
details = self.client.inspect_container(container['Id'])
|
2015-03-24 16:18:15 +01:00
|
|
|
details = _docker_id_quirk(details)
|
|
|
|
|
2013-10-14 00:07:27 +02:00
|
|
|
deployed.append(details)
|
|
|
|
|
|
|
|
return deployed
|
|
|
|
|
|
|
|
def get_running_containers(self):
|
2015-02-17 22:27:00 +01:00
|
|
|
return [c for c in self.get_deployed_containers() if is_running(c)]
|
2013-10-14 00:07:27 +02:00
|
|
|
|
2014-12-12 17:14:24 +01:00
|
|
|
def pull_image(self):
|
|
|
|
extra_params = {}
|
|
|
|
if self.module.params.get('insecure_registry'):
|
|
|
|
if self.ensure_capability('insecure_registry', fail=False):
|
|
|
|
extra_params['insecure_registry'] = self.module.params.get('insecure_registry')
|
|
|
|
|
|
|
|
resource = self.module.params.get('image')
|
|
|
|
image, tag = get_split_image_tag(resource)
|
|
|
|
if self.module.params.get('username'):
|
|
|
|
try:
|
|
|
|
self.client.login(
|
|
|
|
self.module.params.get('username'),
|
|
|
|
password=self.module.params.get('password'),
|
|
|
|
email=self.module.params.get('email'),
|
|
|
|
registry=self.module.params.get('registry')
|
|
|
|
)
|
2015-03-12 09:04:50 +01:00
|
|
|
except Exception as e:
|
2015-02-17 22:27:00 +01:00
|
|
|
self.module.fail_json(msg="failed to login to the remote registry, check your username/password.", error=repr(e))
|
2014-12-12 17:14:24 +01:00
|
|
|
try:
|
2015-03-15 19:22:07 +01:00
|
|
|
changes = list(self.client.pull(image, tag=tag, stream=True, **extra_params))
|
2015-10-28 12:35:14 +01:00
|
|
|
pull_success = False
|
|
|
|
for change in changes:
|
|
|
|
status = json.loads(change).get('status', '')
|
|
|
|
if status.startswith('Status: Image is up to date for'):
|
|
|
|
# Image is already up to date. Don't increment the counter.
|
|
|
|
pull_success = True
|
|
|
|
break
|
|
|
|
elif (status.startswith('Status: Downloaded newer image for') or
|
|
|
|
status.startswith('Download complete')):
|
|
|
|
# Image was updated. Increment the pull counter.
|
|
|
|
self.increment_counter('pulled')
|
|
|
|
pull_success = True
|
|
|
|
break
|
|
|
|
if not pull_success:
|
2014-12-12 17:14:24 +01:00
|
|
|
# Unrecognized status string.
|
2015-03-15 19:22:07 +01:00
|
|
|
self.module.fail_json(msg="Unrecognized status from pull.", status=status, changes=changes)
|
2015-03-12 09:04:50 +01:00
|
|
|
except Exception as e:
|
2015-02-17 22:27:00 +01:00
|
|
|
self.module.fail_json(msg="Failed to pull the specified image: %s" % resource, error=repr(e))
|
2014-12-12 17:14:24 +01:00
|
|
|
|
2013-10-14 00:07:27 +02:00
|
|
|
def create_containers(self, count=1):
|
2015-07-21 17:52:48 +02:00
|
|
|
try:
|
|
|
|
mem_limit = _human_to_bytes(self.module.params.get('memory_limit'))
|
|
|
|
except ValueError as e:
|
|
|
|
self.module.fail_json(msg=str(e))
|
2015-08-06 15:46:01 +02:00
|
|
|
api_version = self.client.version()['ApiVersion']
|
2015-07-21 17:52:48 +02:00
|
|
|
|
2013-10-14 00:07:27 +02:00
|
|
|
params = {'image': self.module.params.get('image'),
|
2015-10-02 00:09:08 +02:00
|
|
|
'entrypoint': self.module.params.get('entrypoint'),
|
2013-10-14 00:07:27 +02:00
|
|
|
'command': self.module.params.get('command'),
|
2014-02-26 00:24:46 +01:00
|
|
|
'ports': self.exposed_ports,
|
2013-10-24 07:56:02 +02:00
|
|
|
'volumes': self.volumes,
|
2013-11-03 21:48:03 +01:00
|
|
|
'environment': self.env,
|
2015-09-25 22:58:20 +02:00
|
|
|
'labels': self.module.params.get('labels'),
|
2013-10-14 00:07:27 +02:00
|
|
|
'hostname': self.module.params.get('hostname'),
|
2015-02-11 08:25:24 +01:00
|
|
|
'domainname': self.module.params.get('domainname'),
|
2013-10-14 00:07:27 +02:00
|
|
|
'detach': self.module.params.get('detach'),
|
2014-02-26 00:24:46 +01:00
|
|
|
'name': self.module.params.get('name'),
|
2014-03-18 12:57:01 +01:00
|
|
|
'stdin_open': self.module.params.get('stdin_open'),
|
|
|
|
'tty': self.module.params.get('tty'),
|
2015-06-29 22:15:25 +02:00
|
|
|
'cpuset': self.module.params.get('cpu_set'),
|
2015-11-26 15:49:18 +01:00
|
|
|
'cpu_shares': self.module.params.get('cpu_shares'),
|
2014-11-20 00:21:01 +01:00
|
|
|
'user': self.module.params.get('docker_user'),
|
2013-10-14 00:07:27 +02:00
|
|
|
}
|
2015-04-27 10:58:20 +02:00
|
|
|
if self.ensure_capability('host_config', fail=False):
|
2015-09-04 00:39:18 +02:00
|
|
|
params['host_config'] = self.create_host_config()
|
2015-04-27 10:58:20 +02:00
|
|
|
|
2015-08-06 15:46:01 +02:00
|
|
|
#For v1.19 API and above use HostConfig, otherwise use Config
|
2015-10-10 01:11:44 +02:00
|
|
|
if docker.utils.compare_version('1.19', api_version) < 0:
|
2015-08-06 15:46:01 +02:00
|
|
|
params['mem_limit'] = mem_limit
|
|
|
|
else:
|
2015-08-16 17:34:56 +02:00
|
|
|
params['host_config']['Memory'] = mem_limit
|
2015-08-06 15:46:01 +02:00
|
|
|
|
|
|
|
|
2013-10-14 00:07:27 +02:00
|
|
|
def do_create(count, params):
|
|
|
|
results = []
|
2013-10-14 06:34:58 +02:00
|
|
|
for _ in range(count):
|
2013-10-14 00:07:27 +02:00
|
|
|
result = self.client.create_container(**params)
|
|
|
|
self.increment_counter('created')
|
|
|
|
results.append(result)
|
|
|
|
|
|
|
|
return results
|
|
|
|
|
|
|
|
try:
|
|
|
|
containers = do_create(count, params)
|
2015-07-16 21:25:39 +02:00
|
|
|
except docker.errors.APIError as e:
|
|
|
|
if e.response.status_code != 404:
|
|
|
|
raise
|
|
|
|
|
2014-12-12 17:14:24 +01:00
|
|
|
self.pull_image()
|
2013-10-14 00:07:27 +02:00
|
|
|
containers = do_create(count, params)
|
|
|
|
|
|
|
|
return containers
|
|
|
|
|
|
|
|
def start_containers(self, containers):
|
2015-04-27 10:58:20 +02:00
|
|
|
params = {}
|
|
|
|
|
|
|
|
if not self.ensure_capability('host_config', fail=False):
|
|
|
|
params = self.get_start_params()
|
|
|
|
|
2013-10-14 00:07:27 +02:00
|
|
|
for i in containers:
|
2015-05-23 00:36:38 +02:00
|
|
|
self.client.start(i)
|
2014-02-26 00:24:46 +01:00
|
|
|
self.increment_counter('started')
|
2013-10-14 00:07:27 +02:00
|
|
|
|
2015-03-30 21:52:17 +02:00
|
|
|
if not self.module.params.get('detach'):
|
|
|
|
status = self.client.wait(i['Id'])
|
|
|
|
if status != 0:
|
|
|
|
output = self.client.logs(i['Id'], stdout=True, stderr=True,
|
|
|
|
stream=False, timestamps=False)
|
|
|
|
self.module.fail_json(status=status, msg=output)
|
|
|
|
|
2013-10-14 00:07:27 +02:00
|
|
|
def stop_containers(self, containers):
|
|
|
|
for i in containers:
|
2015-09-24 07:15:59 +02:00
|
|
|
self.client.stop(i['Id'], self.module.params.get('stop_timeout'))
|
2013-10-14 00:07:27 +02:00
|
|
|
self.increment_counter('stopped')
|
|
|
|
|
|
|
|
return [self.client.wait(i['Id']) for i in containers]
|
|
|
|
|
|
|
|
def remove_containers(self, containers):
|
|
|
|
for i in containers:
|
|
|
|
self.client.remove_container(i['Id'])
|
|
|
|
self.increment_counter('removed')
|
2014-02-26 00:24:46 +01:00
|
|
|
|
2013-10-14 00:07:27 +02:00
|
|
|
def kill_containers(self, containers):
|
|
|
|
for i in containers:
|
2015-03-27 18:07:35 +01:00
|
|
|
self.client.kill(i['Id'], self.module.params.get('signal'))
|
2013-10-14 00:07:27 +02:00
|
|
|
self.increment_counter('killed')
|
|
|
|
|
|
|
|
def restart_containers(self, containers):
|
|
|
|
for i in containers:
|
|
|
|
self.client.restart(i['Id'])
|
|
|
|
self.increment_counter('restarted')
|
|
|
|
|
2014-02-26 00:24:46 +01:00
|
|
|
|
2015-02-17 22:27:00 +01:00
|
|
|
class ContainerSet:
|
|
|
|
|
|
|
|
def __init__(self, manager):
|
|
|
|
self.manager = manager
|
|
|
|
self.running = []
|
|
|
|
self.deployed = []
|
|
|
|
self.changed = []
|
|
|
|
|
|
|
|
def refresh(self):
|
|
|
|
'''
|
|
|
|
Update our view of the matching containers from the Docker daemon.
|
|
|
|
'''
|
|
|
|
|
|
|
|
|
|
|
|
self.deployed = self.manager.get_deployed_containers()
|
|
|
|
self.running = [c for c in self.deployed if is_running(c)]
|
|
|
|
|
|
|
|
def notice_changed(self, containers):
|
|
|
|
'''
|
|
|
|
Record a collection of containers as "changed".
|
|
|
|
'''
|
|
|
|
|
|
|
|
self.changed.extend(containers)
|
|
|
|
|
|
|
|
|
|
|
|
def present(manager, containers, count, name):
|
|
|
|
'''Ensure that exactly `count` matching containers exist in any state.'''
|
|
|
|
|
|
|
|
containers.refresh()
|
|
|
|
delta = count - len(containers.deployed)
|
|
|
|
|
|
|
|
if delta > 0:
|
2015-09-16 16:49:09 +02:00
|
|
|
created = manager.create_containers(delta)
|
|
|
|
containers.notice_changed(manager.get_inspect_containers(created))
|
2015-02-17 22:27:00 +01:00
|
|
|
|
|
|
|
if delta < 0:
|
|
|
|
# If both running and stopped containers exist, remove
|
|
|
|
# stopped containers first.
|
|
|
|
containers.deployed.sort(lambda cx, cy: cmp(is_running(cx), is_running(cy)))
|
|
|
|
|
|
|
|
to_stop = []
|
|
|
|
to_remove = []
|
|
|
|
for c in containers.deployed[0:-delta]:
|
|
|
|
if is_running(c):
|
|
|
|
to_stop.append(c)
|
|
|
|
to_remove.append(c)
|
|
|
|
|
|
|
|
manager.stop_containers(to_stop)
|
2015-09-16 16:49:09 +02:00
|
|
|
containers.notice_changed(manager.get_inspect_containers(to_remove))
|
2015-02-17 22:27:00 +01:00
|
|
|
manager.remove_containers(to_remove)
|
|
|
|
|
|
|
|
def started(manager, containers, count, name):
|
|
|
|
'''Ensure that exactly `count` matching containers exist and are running.'''
|
|
|
|
|
|
|
|
containers.refresh()
|
|
|
|
delta = count - len(containers.running)
|
|
|
|
|
|
|
|
if delta > 0:
|
|
|
|
if name and containers.deployed:
|
|
|
|
# A stopped container exists with the requested name.
|
|
|
|
# Clean it up before attempting to start a new one.
|
|
|
|
manager.remove_containers(containers.deployed)
|
|
|
|
|
|
|
|
created = manager.create_containers(delta)
|
|
|
|
manager.start_containers(created)
|
2015-09-16 16:49:09 +02:00
|
|
|
containers.notice_changed(manager.get_inspect_containers(created))
|
2015-02-17 22:27:00 +01:00
|
|
|
|
|
|
|
if delta < 0:
|
|
|
|
excess = containers.running[0:-delta]
|
2015-09-16 16:49:09 +02:00
|
|
|
containers.notice_changed(manager.get_inspect_containers(excess))
|
2015-02-17 22:27:00 +01:00
|
|
|
manager.stop_containers(excess)
|
|
|
|
manager.remove_containers(excess)
|
|
|
|
|
|
|
|
def reloaded(manager, containers, count, name):
|
|
|
|
'''
|
|
|
|
Ensure that exactly `count` matching containers exist and are
|
|
|
|
running. If any associated settings have been changed (volumes,
|
|
|
|
ports or so on), restart those containers.
|
|
|
|
'''
|
|
|
|
|
|
|
|
containers.refresh()
|
|
|
|
|
|
|
|
for container in manager.get_differing_containers():
|
|
|
|
manager.stop_containers([container])
|
|
|
|
manager.remove_containers([container])
|
|
|
|
|
|
|
|
started(manager, containers, count, name)
|
|
|
|
|
|
|
|
def restarted(manager, containers, count, name):
|
|
|
|
'''
|
|
|
|
Ensure that exactly `count` matching containers exist and are
|
|
|
|
running. Unconditionally restart any that were already running.
|
|
|
|
'''
|
|
|
|
|
|
|
|
containers.refresh()
|
|
|
|
|
2015-08-26 00:01:35 +02:00
|
|
|
for container in manager.get_differing_containers():
|
|
|
|
manager.stop_containers([container])
|
|
|
|
manager.remove_containers([container])
|
|
|
|
|
2015-02-17 22:27:00 +01:00
|
|
|
manager.restart_containers(containers.running)
|
|
|
|
started(manager, containers, count, name)
|
|
|
|
|
|
|
|
def stopped(manager, containers, count, name):
|
|
|
|
'''Stop any matching containers that are running.'''
|
|
|
|
|
|
|
|
containers.refresh()
|
|
|
|
|
|
|
|
manager.stop_containers(containers.running)
|
2015-09-16 16:49:09 +02:00
|
|
|
containers.notice_changed(manager.get_inspect_containers(containers.running))
|
2015-02-17 22:27:00 +01:00
|
|
|
|
|
|
|
def killed(manager, containers, count, name):
|
|
|
|
'''Kill any matching containers that are running.'''
|
|
|
|
|
|
|
|
containers.refresh()
|
|
|
|
|
|
|
|
manager.kill_containers(containers.running)
|
2015-09-16 16:49:09 +02:00
|
|
|
containers.notice_changed(manager.get_inspect_containers(containers.running))
|
2015-02-17 22:27:00 +01:00
|
|
|
|
|
|
|
def absent(manager, containers, count, name):
|
|
|
|
'''Stop and remove any matching containers.'''
|
|
|
|
|
|
|
|
containers.refresh()
|
|
|
|
|
|
|
|
manager.stop_containers(containers.running)
|
2015-09-16 16:49:09 +02:00
|
|
|
containers.notice_changed(manager.get_inspect_containers(containers.deployed))
|
2015-02-17 22:27:00 +01:00
|
|
|
manager.remove_containers(containers.deployed)
|
|
|
|
|
2013-10-14 00:07:27 +02:00
|
|
|
def main():
|
|
|
|
module = AnsibleModule(
|
|
|
|
argument_spec = dict(
|
|
|
|
count = dict(default=1),
|
|
|
|
image = dict(required=True),
|
2014-12-12 17:14:24 +01:00
|
|
|
pull = dict(required=False, default='missing', choices=['missing', 'always']),
|
2015-10-02 00:09:08 +02:00
|
|
|
entrypoint = dict(required=False, default=None, type='str'),
|
2013-10-14 00:07:27 +02:00
|
|
|
command = dict(required=False, default=None),
|
2014-03-18 21:13:12 +01:00
|
|
|
expose = dict(required=False, default=None, type='list'),
|
|
|
|
ports = dict(required=False, default=None, type='list'),
|
2014-02-26 00:24:46 +01:00
|
|
|
publish_all_ports = dict(default=False, type='bool'),
|
2014-03-18 21:13:12 +01:00
|
|
|
volumes = dict(default=None, type='list'),
|
2013-10-14 00:07:27 +02:00
|
|
|
volumes_from = dict(default=None),
|
2014-03-18 21:13:12 +01:00
|
|
|
links = dict(default=None, type='list'),
|
2015-11-03 15:11:18 +01:00
|
|
|
devices = dict(default=None, type='list'),
|
2013-10-14 00:07:27 +02:00
|
|
|
memory_limit = dict(default=0),
|
|
|
|
memory_swap = dict(default=0),
|
2015-11-26 15:49:18 +01:00
|
|
|
cpu_shares = dict(default=0),
|
2015-02-18 16:29:53 +01:00
|
|
|
docker_url = dict(),
|
2015-03-12 04:27:29 +01:00
|
|
|
use_tls = dict(default=None, choices=['no', 'encrypt', 'verify']),
|
|
|
|
tls_client_cert = dict(required=False, default=None, type='str'),
|
|
|
|
tls_client_key = dict(required=False, default=None, type='str'),
|
|
|
|
tls_ca_cert = dict(required=False, default=None, type='str'),
|
|
|
|
tls_hostname = dict(required=False, type='str', default=None),
|
2015-05-01 04:09:22 +02:00
|
|
|
docker_api_version = dict(required=False, default=DEFAULT_DOCKER_API_VERSION, type='str'),
|
2014-11-20 00:21:01 +01:00
|
|
|
docker_user = dict(default=None),
|
2014-08-18 17:37:07 +02:00
|
|
|
username = dict(default=None),
|
2013-10-14 00:07:27 +02:00
|
|
|
password = dict(),
|
|
|
|
email = dict(),
|
2014-08-18 17:37:07 +02:00
|
|
|
registry = dict(),
|
2013-10-14 00:07:27 +02:00
|
|
|
hostname = dict(default=None),
|
2015-02-11 08:25:24 +01:00
|
|
|
domainname = dict(default=None),
|
2014-08-15 18:03:29 +02:00
|
|
|
env = dict(type='dict'),
|
2013-10-14 00:07:27 +02:00
|
|
|
dns = dict(),
|
|
|
|
detach = dict(default=True, type='bool'),
|
2015-03-13 18:23:10 +01:00
|
|
|
state = dict(default='started', choices=['present', 'started', 'reloaded', 'restarted', 'stopped', 'killed', 'absent', 'running']),
|
2015-03-27 18:07:35 +01:00
|
|
|
signal = dict(default=None),
|
2015-11-18 10:02:51 +01:00
|
|
|
restart_policy = dict(default=None, choices=['always', 'on-failure', 'no', 'unless-stopped']),
|
2014-10-19 22:15:48 +02:00
|
|
|
restart_policy_retry = dict(default=0, type='int'),
|
2015-04-07 09:08:43 +02:00
|
|
|
extra_hosts = dict(type='dict'),
|
2013-10-14 00:07:27 +02:00
|
|
|
debug = dict(default=False, type='bool'),
|
|
|
|
privileged = dict(default=False, type='bool'),
|
2014-03-18 12:57:01 +01:00
|
|
|
stdin_open = dict(default=False, type='bool'),
|
|
|
|
tty = dict(default=False, type='bool'),
|
2014-03-18 21:13:12 +01:00
|
|
|
lxc_conf = dict(default=None, type='list'),
|
2014-05-15 00:29:54 +02:00
|
|
|
name = dict(default=None),
|
2014-12-14 04:56:30 +01:00
|
|
|
net = dict(default=None),
|
2015-03-04 06:32:15 +01:00
|
|
|
pid = dict(default=None),
|
2014-12-14 04:56:30 +01:00
|
|
|
insecure_registry = dict(default=False, type='bool'),
|
2015-09-23 17:54:51 +02:00
|
|
|
log_driver = dict(default=None, choices=['json-file', 'none', 'syslog', 'journald', 'gelf', 'fluentd']),
|
2015-09-08 17:19:26 +02:00
|
|
|
log_opt = dict(default=None, type='dict'),
|
2014-11-24 23:08:12 +01:00
|
|
|
cpu_set = dict(default=None),
|
2014-10-18 15:25:07 +02:00
|
|
|
cap_add = dict(default=None, type='list'),
|
|
|
|
cap_drop = dict(default=None, type='list'),
|
2015-09-05 00:59:19 +02:00
|
|
|
read_only = dict(default=None, type='bool'),
|
2015-09-25 22:58:20 +02:00
|
|
|
labels = dict(default={}, type='dict'),
|
2015-09-24 07:15:59 +02:00
|
|
|
stop_timeout = dict(default=10, type='int'),
|
2016-01-09 19:01:02 +01:00
|
|
|
timeout = dict(required=False, default=DEFAULT_TIMEOUT_SECONDS, type='int'),
|
2015-03-12 04:27:29 +01:00
|
|
|
),
|
|
|
|
required_together = (
|
|
|
|
['tls_client_cert', 'tls_client_key'],
|
|
|
|
),
|
2013-10-14 00:07:27 +02:00
|
|
|
)
|
|
|
|
|
2014-02-26 00:24:46 +01:00
|
|
|
check_dependencies(module)
|
|
|
|
|
2013-10-14 00:07:27 +02:00
|
|
|
try:
|
2013-10-14 22:49:53 +02:00
|
|
|
manager = DockerManager(module)
|
2013-10-14 00:07:27 +02:00
|
|
|
count = int(module.params.get('count'))
|
2014-02-26 00:24:46 +01:00
|
|
|
name = module.params.get('name')
|
2014-12-12 17:14:24 +01:00
|
|
|
pull = module.params.get('pull')
|
2014-02-26 00:24:46 +01:00
|
|
|
|
2015-03-13 18:23:10 +01:00
|
|
|
state = module.params.get('state')
|
|
|
|
if state == 'running':
|
|
|
|
# Renamed running to started in 1.9
|
|
|
|
state = 'started'
|
|
|
|
|
2014-02-26 00:24:46 +01:00
|
|
|
if count < 0:
|
|
|
|
module.fail_json(msg="Count must be greater than zero")
|
2015-02-17 22:27:00 +01:00
|
|
|
|
2014-02-26 00:24:46 +01:00
|
|
|
if count > 1 and name:
|
|
|
|
module.fail_json(msg="Count and name must not be used together")
|
2013-10-14 00:07:27 +02:00
|
|
|
|
2015-03-22 12:16:02 +01:00
|
|
|
# Explicitly pull new container images, if requested. Do this before
|
|
|
|
# noticing running and deployed containers so that the image names
|
|
|
|
# will differ if a newer image has been pulled.
|
|
|
|
# Missing images should be pulled first to avoid downtime when old
|
|
|
|
# container is stopped, but image for new one is now downloaded yet.
|
|
|
|
# It also prevents removal of running container before realizing
|
|
|
|
# that requested image cannot be retrieved.
|
|
|
|
if pull == "always" or (state == 'reloaded' and manager.get_inspect_image() is None):
|
2014-12-12 17:14:24 +01:00
|
|
|
manager.pull_image()
|
|
|
|
|
2015-02-17 22:27:00 +01:00
|
|
|
containers = ContainerSet(manager)
|
2014-02-26 00:24:46 +01:00
|
|
|
|
2015-02-17 22:27:00 +01:00
|
|
|
if state == 'present':
|
|
|
|
present(manager, containers, count, name)
|
|
|
|
elif state == 'started':
|
|
|
|
started(manager, containers, count, name)
|
|
|
|
elif state == 'reloaded':
|
|
|
|
reloaded(manager, containers, count, name)
|
|
|
|
elif state == 'restarted':
|
|
|
|
restarted(manager, containers, count, name)
|
|
|
|
elif state == 'stopped':
|
|
|
|
stopped(manager, containers, count, name)
|
|
|
|
elif state == 'killed':
|
|
|
|
killed(manager, containers, count, name)
|
|
|
|
elif state == 'absent':
|
|
|
|
absent(manager, containers, count, name)
|
|
|
|
else:
|
|
|
|
module.fail_json(msg='Unrecognized state %s. Must be one of: '
|
|
|
|
'present; started; reloaded; restarted; '
|
|
|
|
'stopped; killed; absent.' % state)
|
2014-02-26 00:24:46 +01:00
|
|
|
|
2015-02-17 22:27:00 +01:00
|
|
|
module.exit_json(changed=manager.has_changed(),
|
|
|
|
msg=manager.get_summary_message(),
|
|
|
|
summary=manager.counters,
|
2015-03-31 22:14:16 +02:00
|
|
|
reload_reasons=manager.get_reload_reason_message(),
|
2015-09-16 16:49:09 +02:00
|
|
|
ansible_facts=_ansible_facts(containers.changed))
|
2013-10-14 00:07:27 +02:00
|
|
|
|
2015-02-17 22:27:00 +01:00
|
|
|
except DockerAPIError as e:
|
|
|
|
module.fail_json(changed=manager.has_changed(), msg="Docker API Error: %s" % e.explanation)
|
2013-10-14 00:07:27 +02:00
|
|
|
|
2015-02-17 22:27:00 +01:00
|
|
|
except RequestException as e:
|
|
|
|
module.fail_json(changed=manager.has_changed(), msg=repr(e))
|
2014-02-26 00:24:46 +01:00
|
|
|
|
2013-12-02 21:13:49 +01:00
|
|
|
# import module snippets
|
2013-12-02 21:11:23 +01:00
|
|
|
from ansible.module_utils.basic import *
|
2013-10-14 00:07:27 +02:00
|
|
|
|
2014-11-14 17:46:32 +01:00
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|