Several cleanups to many modules:

* Fix docs to specify when python2.6+ is required (due to a library
  dep).  This helps us know when it is okay to use python2.6+ syntax in
  the file.
* remove BabyJson returns.  See #1211  This commit fixes all but the
  openstack modules.
* Use if __name__ == '__main__' to only run the main part of the module
  if the module is run as a program.  This allows for the potential to
  unittest the code later.
This commit is contained in:
Toshio Kuratomi 2015-05-11 12:15:53 -07:00 committed by Matt Clay
parent 0567404c03
commit 5336217649
17 changed files with 186 additions and 114 deletions

View file

@ -130,6 +130,7 @@ options:
default: 'success'
required: false
requirements:
- "python >= 2.6"
- boto
'''

View file

@ -241,7 +241,9 @@ options:
default: null
aliases: []
version_added: 1.9
requirements: [ "boto" ]
requirements:
- "python >= 2.6"
- "boto"
author: Bruce Pennypacker, Will Thames
'''

View file

@ -19,7 +19,7 @@ DOCUMENTATION = '''
module: azure
short_description: create or terminate a virtual machine in azure
description:
- Creates or terminates azure instances. When created optionally waits for it to be 'running'. This module has a dependency on python-azure >= 0.7.1
- Creates or terminates azure instances. When created optionally waits for it to be 'running'.
version_added: "1.7"
options:
name:
@ -111,7 +111,9 @@ options:
default: 'present'
aliases: []
requirements: [ "azure" ]
requirements:
- "python >= 2.6"
- "azure >= 0.7.1"
author: John Whitbeck
'''
@ -141,7 +143,6 @@ EXAMPLES = '''
import base64
import datetime
import os
import sys
import time
from urlparse import urlparse
from ansible.module_utils.facts import * # TimeoutError
@ -196,9 +197,9 @@ try:
from azure.servicemanagement import (ServiceManagementService, OSVirtualHardDisk, SSH, PublicKeys,
PublicKey, LinuxConfigurationSet, ConfigurationSetInputEndpoints,
ConfigurationSetInputEndpoint)
HAS_AZURE = True
except ImportError:
print "failed=True msg='azure required for this module'"
sys.exit(1)
HAS_AZURE = False
from distutils.version import LooseVersion
from types import MethodType
@ -463,6 +464,8 @@ def main():
wait_timeout_redirects=dict(default=300)
)
)
if not HAS_AZURE:
module.fail_json(msg='azure python module required for this module')
# create azure ServiceManagementService object
subscription_id, management_cert_path = get_azure_creds(module)
@ -529,5 +532,5 @@ class Wrapper(object):
# import module snippets
from ansible.module_utils.basic import *
main()
if __name__ == '__main__':
main()

View file

@ -99,7 +99,10 @@ options:
notes:
- Two environment variables can be used, DO_API_KEY and DO_API_TOKEN. They both refer to the v2 token.
requirements: [ dopy ]
- Version 2 of DigitalOcean API is used.
requirements:
- "python >= 2.6"
- dopy
'''
@ -161,20 +164,18 @@ EXAMPLES = '''
image_id=fedora-19-x64
'''
import sys
import os
import time
from distutils.version import LooseVersion
HAS_DOPY = True
try:
import dopy
from dopy.manager import DoError, DoManager
except ImportError, e:
print "failed=True msg='dopy >= 0.3.2 required for this module'"
sys.exit(1)
if dopy.__version__ < '0.3.2':
print "failed=True msg='dopy >= 0.3.2 required for this module'"
sys.exit(1)
if LooseVersion(dopy.__version__) < LooseVersion('0.3.2'):
HAS_DOPY = False
except ImportError:
HAS_DOPY = False
class TimeoutError(DoError):
def __init__(self, msg, id):
@ -420,6 +421,8 @@ def main():
['id', 'name'],
),
)
if not HAS_DOPY:
module.fail_json(msg='dopy >= 0.3.2 required for this module')
try:
core(module)
@ -431,4 +434,5 @@ def main():
# import module snippets
from ansible.module_utils.basic import *
main()
if __name__ == '__main__':
main()

View file

@ -47,6 +47,10 @@ options:
notes:
- Two environment variables can be used, DO_CLIENT_ID and DO_API_KEY.
- Version 1 of DigitalOcean API is used.
requirements:
- "python >= 2.6"
- dopy
'''
@ -74,15 +78,14 @@ EXAMPLES = '''
ip={{ test_droplet.droplet.ip_address }}
'''
import sys
import os
import time
try:
from dopy.manager import DoError, DoManager
HAS_DOPY = True
except ImportError as e:
print "failed=True msg='dopy required for this module'"
sys.exit(1)
HAS_DOPY = False
class TimeoutError(DoError):
def __init__(self, msg, id):
@ -229,6 +232,8 @@ def main():
['id', 'name'],
),
)
if not HAS_DOPY:
module.fail_json(msg='dopy required for this module')
try:
core(module)
@ -239,5 +244,5 @@ def main():
# import module snippets
from ansible.module_utils.basic import *
main()
if __name__ == '__main__':
main()

View file

@ -47,6 +47,9 @@ options:
notes:
- Two environment variables can be used, DO_CLIENT_ID and DO_API_KEY.
- Version 1 of DigitalOcean API is used.
requirements:
- "python >= 2.6"
- dopy
'''
@ -64,15 +67,14 @@ EXAMPLES = '''
'''
import sys
import os
import time
try:
from dopy.manager import DoError, DoManager
except ImportError as e:
print "failed=True msg='dopy required for this module'"
sys.exit(1)
HAS_DOPY = True
except ImportError:
HAS_DOPY = False
class TimeoutError(DoError):
def __init__(self, msg, id):
@ -165,6 +167,8 @@ def main():
['id', 'name'],
),
)
if not HAS_DOPY:
module.fail_json(msg='dopy required for this module')
try:
core(module)
@ -175,5 +179,5 @@ def main():
# import module snippets
from ansible.module_utils.basic import *
main()
if __name__ == '__main__':
main()

View file

@ -261,7 +261,10 @@ options:
version_added: "1.9"
author: Cove Schneider, Joshua Conner, Pavel Antonov, Ash Wilson
requirements: [ "docker-py >= 0.3.0", "docker >= 0.10.0" ]
requirements:
- "python >= 2.6"
- "docker-py >= 0.3.0"
- "The docker server >= 0.10.0"
'''
EXAMPLES = '''
@ -400,8 +403,7 @@ def _human_to_bytes(number):
return int(number[:-len(each)]) * (1024 ** i)
i = i + 1
print "failed=True msg='Could not convert %s to integer'" % (number)
sys.exit(1)
raise ValueError('Could not convert %s to integer' % (number,))
def _ansible_facts(container_list):
@ -912,7 +914,11 @@ class DockerManager(object):
# MEM_LIMIT
expected_mem = _human_to_bytes(self.module.params.get('memory_limit'))
try:
expected_mem = _human_to_bytes(self.module.params.get('memory_limit'))
except ValueError as e:
self.module.fail_json(msg=str(e))
actual_mem = container['Config']['Memory']
if expected_mem and actual_mem != expected_mem:
@ -1205,11 +1211,16 @@ class DockerManager(object):
self.module.fail_json(msg="Failed to pull the specified image: %s" % resource, error=repr(e))
def create_containers(self, count=1):
try:
mem_limit = _human_to_bytes(self.module.params.get('memory_limit'))
except ValueError as e:
self.module.fail_json(msg=str(e))
params = {'image': self.module.params.get('image'),
'command': self.module.params.get('command'),
'ports': self.exposed_ports,
'volumes': self.volumes,
'mem_limit': _human_to_bytes(self.module.params.get('memory_limit')),
'mem_limit': mem_limit,
'environment': self.env,
'hostname': self.module.params.get('hostname'),
'domainname': self.module.params.get('domainname'),

View file

@ -72,7 +72,10 @@ options:
required: false
default: 600
aliases: []
requirements: [ "docker-py" ]
requirements:
- "python >= 2.6"
- "docker-py"
- "requests"
'''
EXAMPLES = '''
@ -102,21 +105,31 @@ Remove image from local docker storage:
'''
try:
import sys
import re
import json
import docker.client
from requests.exceptions import *
from urlparse import urlparse
except ImportError, e:
print "failed=True msg='failed to import python module: %s'" % e
sys.exit(1)
import re
from urlparse import urlparse
try:
from docker.errors import APIError as DockerAPIError
import json
except ImportError:
from docker.client import APIError as DockerAPIError
import simplejson as json
try:
from requests.exceptions import *
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
try:
import docker.client
HAS_DOCKER_CLIENT = True
except ImportError:
HAS_DOCKER_CLIENT = False
if HAS_DOCKER_CLIENT:
try:
from docker.errors import APIError as DockerAPIError
except ImportError:
from docker.client import APIError as DockerAPIError
class DockerImageManager:
@ -209,6 +222,10 @@ def main():
timeout = dict(default=600, type='int'),
)
)
if not HAS_DOCKER_CLIENT:
module.fail_json(msg='docker-py is needed for this module')
if not HAS_REQUESTS:
module.fail_json(msg='requests is needed for this module')
try:
manager = DockerImageManager(module)
@ -245,8 +262,8 @@ def main():
except RequestException as e:
module.exit_json(failed=True, changed=manager.has_changed(), msg=repr(e))
# import module snippets
from ansible.module_utils.basic import *
main()
if __name__ == '__main__':
main()

View file

@ -87,7 +87,9 @@ options:
required: true
default: null
requirements: [ "boto 2.9+" ]
requirements:
- "python >= 2.6"
- "boto >= 2.9"
author: benno@ansible.com Note. Most of the code has been taken from the S3 module.
@ -116,16 +118,15 @@ EXAMPLES = '''
- gc_storage: bucket=mybucket mode=delete
'''
import sys
import os
import urlparse
import hashlib
try:
import boto
HAS_BOTO = True
except ImportError:
print "failed=True msg='boto 2.9+ required for this module'"
sys.exit(1)
HAS_BOTO = False
def grant_check(module, gs, obj):
try:
@ -377,6 +378,9 @@ def main():
),
)
if not HAS_BOTO:
module.fail_json(msg='boto 2.9+ required for this module')
bucket = module.params.get('bucket')
obj = module.params.get('object')
src = module.params.get('src')
@ -445,5 +449,5 @@ def main():
# import module snippets
from ansible.module_utils.basic import *
main()
if __name__ == '__main__':
main()

View file

@ -137,7 +137,9 @@ options:
default: "true"
aliases: []
requirements: [ "libcloud" ]
requirements:
- "python >= 2.6"
- "apache-libcloud >= 0.13.3"
notes:
- Either I(name) or I(instance_names) is required.
author: Eric Johnson <erjohnso@google.com>
@ -202,25 +204,21 @@ EXAMPLES = '''
'''
import sys
try:
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
from libcloud.common.google import GoogleBaseError, QuotaExceededError, \
ResourceExistsError, ResourceInUseError, ResourceNotFoundError
_ = Provider.GCE
HAS_LIBCLOUD = True
except ImportError:
print("failed=True " + \
"msg='libcloud with GCE support (0.13.3+) required for this module'")
sys.exit(1)
HAS_LIBCLOUD = False
try:
from ast import literal_eval
HAS_PYTHON26 = True
except ImportError:
print("failed=True " + \
"msg='GCE module requires python's 'ast' module, python v2.6+'")
sys.exit(1)
HAS_PYTHON26 = False
def get_instance_info(inst):
@ -323,11 +321,9 @@ def create_instances(module, gce, instance_names):
if not isinstance(md, dict):
raise ValueError('metadata must be a dict')
except ValueError, e:
print("failed=True msg='bad metadata: %s'" % str(e))
sys.exit(1)
module.fail_json(msg='bad metadata: %s' % str(e))
except SyntaxError, e:
print("failed=True msg='bad metadata syntax'")
sys.exit(1)
module.fail_json(msg='bad metadata syntax')
items = []
for k,v in md.items():
@ -450,6 +446,11 @@ def main():
)
)
if not HAS_PYTHON26:
module.fail_json(msg="GCE module requires python's 'ast' module, python v2.6+")
if not HAS_LIBCLOUD:
module.fail_json(msg='libcloud with GCE support (0.13.3+) required for this module')
gce = gce_connect(module)
image = module.params.get('image')
@ -503,11 +504,10 @@ def main():
json_output['changed'] = changed
print json.dumps(json_output)
sys.exit(0)
module.exit_json(**json_output)
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.gce import *
main()
if __name__ == '__main__':
main()

View file

@ -131,7 +131,9 @@ options:
default: null
aliases: []
requirements: [ "libcloud" ]
requirements:
- "python >= 2.6"
- "apache-libcloud >= 0.13.3"
author: Eric Johnson <erjohnso@google.com>
'''
@ -147,9 +149,6 @@ EXAMPLES = '''
httphealthcheck_path: "/up"
'''
import sys
try:
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
@ -158,10 +157,9 @@ try:
from libcloud.common.google import GoogleBaseError, QuotaExceededError, \
ResourceExistsError, ResourceNotFoundError
_ = Provider.GCE
HAS_LIBCLOUD = True
except ImportError:
print("failed=True " + \
"msg='libcloud with GCE support required for this module.'")
sys.exit(1)
HAS_LIBCLOUD = False
def main():
@ -188,6 +186,9 @@ def main():
)
)
if not HAS_LIBCLOUD:
module.fail_json(msg='libcloud with GCE support (0.13.3+) required for this module.')
gce = gce_connect(module)
httphealthcheck_name = module.params.get('httphealthcheck_name')
@ -325,11 +326,11 @@ def main():
json_output['changed'] = changed
print json.dumps(json_output)
sys.exit(0)
module.exit_json(**json_output)
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.gce import *
main()
if __name__ == '__main__':
main()

View file

@ -102,7 +102,9 @@ options:
default: null
aliases: []
requirements: [ "libcloud" ]
requirements:
- "python >= 2.6"
- "apache-libcloud >= 0.13.3"
author: Eric Johnson <erjohnso@google.com>
'''
@ -123,18 +125,15 @@ EXAMPLES = '''
'''
import sys
try:
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
from libcloud.common.google import GoogleBaseError, QuotaExceededError, \
ResourceExistsError, ResourceNotFoundError
_ = Provider.GCE
HAS_LIBCLOUD = True
except ImportError:
print("failed=True " + \
"msg='libcloud with GCE support required for this module.'")
sys.exit(1)
HAS_LIBCLOUD = False
def format_allowed_section(allowed):
"""Format each section of the allowed list"""
@ -182,6 +181,9 @@ def main():
)
)
if not HAS_LIBCLOUD:
module.exit_json(msg='libcloud with GCE support (0.13.3+) required for this module')
gce = gce_connect(module)
allowed = module.params.get('allowed')
@ -281,11 +283,11 @@ def main():
changed = True
json_output['changed'] = changed
print json.dumps(json_output)
sys.exit(0)
module.exit_json(**json_output)
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.gce import *
main()
if __name__ == '__main__':
main()

View file

@ -117,7 +117,9 @@ options:
choices: ["pd-standard", "pd-ssd"]
aliases: []
requirements: [ "libcloud" ]
requirements:
- "python >= 2.6"
- "apache-libcloud >= 0.13.3"
author: Eric Johnson <erjohnso@google.com>
'''
@ -130,18 +132,15 @@ EXAMPLES = '''
name: pd
'''
import sys
try:
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
from libcloud.common.google import GoogleBaseError, QuotaExceededError, \
ResourceExistsError, ResourceNotFoundError, ResourceInUseError
_ = Provider.GCE
HAS_LIBCLOUD = True
except ImportError:
print("failed=True " + \
"msg='libcloud with GCE support is required for this module.'")
sys.exit(1)
HAS_LIBCLOUD = False
def main():
@ -162,6 +161,8 @@ def main():
project_id = dict(),
)
)
if not HAS_LIBCLOUD:
module.fail_json(msg='libcloud with GCE support (0.13.3+) is required for this module')
gce = gce_connect(module)
@ -285,11 +286,11 @@ def main():
changed = True
json_output['changed'] = changed
print json.dumps(json_output)
sys.exit(0)
module.exit_json(**json_output)
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.gce import *
main()
if __name__ == '__main__':
main()

View file

@ -88,7 +88,10 @@ options:
description:
- how long before wait gives up, in seconds
default: 300
requirements: [ "linode-python", "pycurl" ]
requirements:
- "python >= 2.6"
- "linode-python"
- "pycurl"
author: Vincent Viallet
notes:
- LINODE_API_KEY env variable can be used instead
@ -151,22 +154,21 @@ EXAMPLES = '''
state: restarted
'''
import sys
import time
import os
try:
import pycurl
HAS_PYCURL = True
except ImportError:
print("failed=True msg='pycurl required for this module'")
sys.exit(1)
HAS_PYCURL = False
try:
from linode import api as linode_api
HAS_LINODE = True
except ImportError:
print("failed=True msg='linode-python required for this module'")
sys.exit(1)
HAS_LINODE = False
def randompass():
@ -456,6 +458,11 @@ def main():
)
)
if not HAS_PYCURL:
module.fail_json(msg='pycurl required for this module')
if not HAS_LINODE:
module.fail_json(msg='linode-python required for this module')
state = module.params.get('state')
api_key = module.params.get('api_key')
name = module.params.get('name')
@ -490,4 +497,5 @@ def main():
# import module snippets
from ansible.module_utils.basic import *
main()
if __name__ == '__main__':
main()

View file

@ -120,7 +120,9 @@ notes:
- This module should run from a system that can access vSphere directly.
Either by using local_action, or using delegate_to.
author: Richard Hoop <wrhoop@gmail.com>
requirements: [ pysphere ]
requirements:
- "python >= 2.6"
- pysphere
'''
@ -1320,4 +1322,5 @@ def main():
# this is magic, see lib/ansible/module_common.py
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>
main()
if __name__ == '__main__':
main()

View file

@ -60,9 +60,9 @@ import sys
try:
import selinux
HAS_SELINUX = True
except ImportError:
print "failed=True msg='libselinux-python required for this module'"
sys.exit(1)
HAS_SELINUX = False
# getter subroutines
def get_config_state(configfile):
@ -130,6 +130,9 @@ def main():
supports_check_mode=True
)
if not HAS_SELINUX:
module.fail_json(msg='libselinux-python required for this module')
# global vars
changed=False
msgs = []
@ -204,5 +207,6 @@ def main():
# import module snippets
from ansible.module_utils.basic import *
main()
if __name__ == '__main__':
main()

View file

@ -63,7 +63,9 @@ options:
version_added: "1.6"
notes:
- See the advanced playbooks chapter for more about using accelerated mode.
requirements: [ "python-keyczar" ]
requirements:
- "python >= 2.6"
- "python-keyczar"
author: James Cammarata
'''