docker_service: make PyYAML requirement explicit

The "Developing Modules" documentation states:

  Include a minimum of dependencies if possible. If there are
  dependencies, document them at the top of the module file, and have
  the module raise JSON error messages when the import fails.

When docker_service runs on a remote host without PyYAML it crashes with
ImportError.

This patch raises a JSON error message when import fails, but only if
the PyYAML module is actually used.  It's only needed when the
"definition" parameter is given.

Signed-off-by: Stefan Hajnoczi <stefanha@gmail.com>
This commit is contained in:
Stefan Hajnoczi 2016-06-11 17:08:57 +01:00 committed by Matt Clay
parent 617c230b62
commit 7c4a469174

View file

@ -153,6 +153,7 @@ requirements:
- "python >= 2.6" - "python >= 2.6"
- "docker-compose >= 1.7.0" - "docker-compose >= 1.7.0"
- "Docker API >= 1.20" - "Docker API >= 1.20"
- "PyYAML >= 3.11"
''' '''
EXAMPLES = ''' EXAMPLES = '''
@ -402,13 +403,19 @@ actions:
type: string type: string
''' '''
HAS_YAML = True
HAS_YAML_EXC = None
HAS_COMPOSE = True HAS_COMPOSE = True
HAS_COMPOSE_EXC = None HAS_COMPOSE_EXC = None
MINIMUM_COMPOSE_VERSION = '1.7.0' MINIMUM_COMPOSE_VERSION = '1.7.0'
import yaml try:
from distutils.version import LooseVersion import yaml
except ImportError as exc:
HAS_YAML = False
HAS_YAML_EXC = str(exc)
from distutils.version import LooseVersion
from ansible.module_utils.basic import * from ansible.module_utils.basic import *
try: try:
@ -489,6 +496,9 @@ class ContainerManager(DockerBaseClass):
self.log(self.options, pretty_print=True) self.log(self.options, pretty_print=True)
if self.definition: if self.definition:
if not HAS_YAML:
self.client.fail("Unable to load yaml. Try `pip install PyYAML`. Error: %s" % HAS_YAML_EXC)
if not self.project_name: if not self.project_name:
self.client.fail("Parameter error - project_name required when providing definition.") self.client.fail("Parameter error - project_name required when providing definition.")