Fix undefined variables, basestring usage, and some associated python3 issues

This commit is contained in:
Toshio Kuratomi 2017-07-22 18:15:46 -07:00
commit 225fa5d092
84 changed files with 652 additions and 963 deletions

View file

@ -184,6 +184,7 @@ import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import get_aws_connection_info, boto3_conn, ec2_argument_spec, HAS_BOTO3
from ansible.module_utils.ec2 import camel_dict_to_snake_dict
from ansible.module_utils.six import string_types
try:
import botocore
@ -309,7 +310,7 @@ def setup_removal(client, module):
params = dict()
changed = False
params['DryRun'] = module.check_mode
if isinstance(module.params.get('vpc_endpoint_id'), basestring):
if isinstance(module.params.get('vpc_endpoint_id'), string_types):
params['VpcEndpointIds'] = [module.params.get('vpc_endpoint_id')]
else:
params['VpcEndpointIds'] = module.params.get('vpc_endpoint_id')

View file

@ -138,7 +138,7 @@ def ensure_tags(vpc_conn, resource_id, tags, add_only, check_mode):
latest_tags = get_resource_tags(vpc_conn, resource_id)
return {'changed': True, 'tags': latest_tags}
except EC2ResponseError as e:
raise AnsibleTagCreationException(
raise AnsibleIGWException(
'Unable to update tags for {0}, error: {1}'.format(resource_id, e))

View file

@ -56,6 +56,7 @@ EXAMPLES = '''
"tag:Name": Example
'''
import traceback
try:
import boto.vpc
@ -66,6 +67,7 @@ except ImportError:
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import connect_to_aws, ec2_argument_spec, get_aws_connection_info
from ansible.module_utils._text import to_native
def get_vpc_info(vpc):
@ -121,8 +123,8 @@ def main():
if region:
try:
connection = connect_to_aws(boto.vpc, region, **aws_connect_params)
except (boto.exception.NoAuthHandlerFound, StandardError) as e:
module.fail_json(msg=str(e))
except (boto.exception.NoAuthHandlerFound, Exception) as e:
module.fail_json(msg=to_native(e), exception=traceback.format_exc())
else:
module.fail_json(msg="region must be specified")

View file

@ -119,6 +119,7 @@ tasks:
'''
import json
import urllib
try:
import boto
import boto.iam
@ -127,6 +128,11 @@ try:
except ImportError:
HAS_BOTO = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import connect_to_aws, ec2_argument_spec, get_aws_connection_info
from ansible.module_utils.six import string_types
def boto_exception(err):
'''generic error message handler'''
if hasattr(err, 'error_message'):
@ -317,7 +323,7 @@ def main():
elif module.params.get('policy_json') is not None:
pdoc = module.params.get('policy_json')
# if its a string, assume it is already JSON
if not isinstance(pdoc, basestring):
if not isinstance(pdoc, string_types):
try:
pdoc = json.dumps(pdoc)
except Exception as e:
@ -353,8 +359,6 @@ def main():
state)
module.exit_json(changed=changed, group_name=name, policies=current_policies, msg=msg)
from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import *
if __name__ == '__main__':
main()

View file

@ -116,6 +116,20 @@ EXAMPLES = '''
name: norwegian_blue
'''
try:
import boto.rds
from boto.exception import BotoServerError
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import connect_to_aws, ec2_argument_spec, get_aws_connection_info
from ansible.module_utils.parsing.convert_bool import BOOLEANS_TRUE
from ansible.module_utils.six import string_types
from ansible.module_utils._text import to_native
VALID_ENGINES = [
'aurora5.6',
'mariadb10.0',
@ -147,12 +161,12 @@ VALID_ENGINES = [
'sqlserver-web-12.0',
]
try:
import boto.rds
from boto.exception import BotoServerError
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
INT_MODIFIERS = {
'K': 1024,
'M': pow(1024, 2),
'G': pow(1024, 3),
'T': pow(1024, 4),
}
# returns a tuple: (whether or not a parameter was changed, the remaining parameters that weren't found in this parameter group)
@ -168,14 +182,6 @@ class NotModifiableError(Exception):
def __str__(self):
return 'NotModifiableError: %s' % self.error_message
INT_MODIFIERS = {
'K': 1024,
'M': pow(1024, 2),
'G': pow(1024, 3),
'T': pow(1024, 4),
}
TRUE_VALUES = ('on', 'true', 'yes', '1',)
def set_parameter(param, value, immediate):
"""
@ -187,7 +193,7 @@ def set_parameter(param, value, immediate):
converted_value = str(value)
elif param.type == 'integer':
if isinstance(value, basestring):
if isinstance(value, string_types):
try:
for modifier in INT_MODIFIERS.keys():
if value.endswith(modifier):
@ -203,8 +209,8 @@ def set_parameter(param, value, immediate):
converted_value = int(value)
elif param.type == 'boolean':
if isinstance(value, basestring):
converted_value = value in TRUE_VALUES
if isinstance(value, string_types):
converted_value = to_native(value) in BOOLEANS_TRUE
else:
converted_value = bool(value)
@ -337,9 +343,6 @@ def main():
module.exit_json(changed=changed)
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import *
if __name__ == '__main__':
main()

View file

@ -184,22 +184,19 @@ uploaded:
'''
import datetime
import fnmatch
import hashlib
import mimetypes
import os
import stat as osstat # os.stat constants
import mimetypes
import datetime
from dateutil import tz
import hashlib
import fnmatch
import traceback
from dateutil import tz
# import module snippets
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import ec2_argument_spec
# import a class, otherwise we'll use a fully qualified path
# from ansible.module_utils.ec2 import AWSRetry
import ansible.module_utils.ec2
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import camel_dict_to_snake_dict, ec2_argument_spec
try:

View file

@ -336,8 +336,8 @@ state:
}
''' # NOQA
from ansible.module_utils.basic import *
from ansible.module_utils.azure_rm_common import *
from ansible.module_utils.azure_rm_common import AzureRMModuleBase
from ansible.module_utils.six import integer_types
try:
from msrestazure.azure_exceptions import CloudError
@ -366,7 +366,7 @@ def validate_rule(rule, rule_type=None):
priority = rule.get('priority', None)
if not priority:
raise Exception("Rule priority is required.")
if not isinstance(priority, (int, long)):
if not isinstance(priority, integer_types):
raise Exception("Rule priority attribute must be an integer.")
if rule_type != 'default' and (priority < 100 or priority > 4096):
raise Exception("Rule priority must be between 100 and 4096")
@ -716,5 +716,6 @@ class AzureRMSecurityGroup(AzureRMModuleBase):
def main():
AzureRMSecurityGroup()
if __name__ == '__main__':
main()

View file

@ -681,16 +681,20 @@ docker_container:
}'
'''
import os
import re
import shlex
from ansible.module_utils.docker_common import *
from ansible.module_utils.basic import human_to_bytes
from ansible.module_utils.docker_common import HAS_DOCKER_PY_2, AnsibleDockerClient, DockerBaseClass
from ansible.module_utils.six import string_types
try:
from docker import utils
if HAS_DOCKER_PY_2:
from docker.types import Ulimit
from docker.types import Ulimit, LogConfig
else:
from docker.utils.types import Ulimit
from docker.utils.types import Ulimit, LogConfig
except:
# missing docker-py handled in ansible.module_utils.docker
pass
@ -705,6 +709,7 @@ REQUIRES_CONVERSION_TO_BYTES = [
VOLUME_PERMISSIONS = ('rw', 'ro', 'z', 'Z')
class TaskParameters(DockerBaseClass):
'''
Access and parse module parameters
@ -1087,14 +1092,14 @@ class TaskParameters(DockerBaseClass):
# Any published port should also be exposed
for publish_port in published_ports:
match = False
if isinstance(publish_port, basestring) and '/' in publish_port:
if isinstance(publish_port, string_types) and '/' in publish_port:
port, protocol = publish_port.split('/')
port = int(port)
else:
protocol = 'tcp'
port = int(publish_port)
for exposed_port in exposed:
if isinstance(exposed_port[0], basestring) and '-' in exposed_port[0]:
if isinstance(exposed_port[0], string_types) and '-' in exposed_port[0]:
start_port, end_port = exposed_port[0].split('-')
if int(start_port) <= port <= int(end_port):
match = True
@ -2125,8 +2130,6 @@ def main():
cm = ContainerManager(client)
client.module.exit_json(**cm.results)
# import module snippets
from ansible.module_utils.basic import *
if __name__ == '__main__':
main()

View file

@ -250,8 +250,12 @@ image:
type: dict
sample: {}
'''
import re
import os
from ansible.module_utils.docker_common import *
from ansible.module_utils.docker_common import (HAS_DOCKER_PY_2, AnsibleDockerClient,
DockerBaseClass)
from ansible.module_utils._text import to_native
try:
if HAS_DOCKER_PY_2:
@ -519,8 +523,7 @@ class ImageManager(DockerBaseClass):
params['container_limits'] = self.container_limits
if self.buildargs:
for key, value in self.buildargs.items():
if not isinstance(value, basestring):
self.buildargs[key] = str(value)
self.buildargs[key] = to_native(value)
params['buildargs'] = self.buildargs
for line in self.client.build(**params):
@ -604,8 +607,5 @@ def main():
client.module.exit_json(**results)
# import module snippets
from ansible.module_utils.basic import *
if __name__ == '__main__':
main()

View file

@ -147,15 +147,12 @@ url_map:
'''
try:
from ast import literal_eval
HAS_PYTHON26 = True
except ImportError:
HAS_PYTHON26 = False
from ast import literal_eval
# import module snippets
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.gcp import check_params, get_google_api_client, GCPUtils
from ansible.module_utils.six import string_types
USER_AGENT_PRODUCT = 'ansible-url_map'
USER_AGENT_VERSION = '0.0.1'
@ -258,7 +255,7 @@ def _validate_host_rules_params(host_rules):
try:
check_params(hr, fields)
for host in hr['hosts']:
if not isinstance(host, basestring):
if not isinstance(host, string_types):
raise ValueError("host in hostrules must be a string")
elif '*' in host:
if host.index('*') != 0:
@ -459,10 +456,6 @@ def main():
project_id=dict(), ), required_together=[
['path_matchers', 'host_rules'], ])
if not HAS_PYTHON26:
module.fail_json(
msg="GCE module requires python's 'ast' module, python v2.6+")
client, conn_params = get_google_api_client(module, 'compute', user_agent_product=USER_AGENT_PRODUCT,
user_agent_version=USER_AGENT_VERSION)
@ -515,5 +508,6 @@ def main():
json_output.update(params)
module.exit_json(**json_output)
if __name__ == '__main__':
main()

View file

@ -139,6 +139,7 @@ except ImportError as e:
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.gcp import check_min_pkg_version, get_google_cloud_credentials
from ansible.module_utils.six import string_types
CLOUD_CLIENT = 'google-cloud-spanner'
CLOUD_CLIENT_MINIMUM_VERSION = '0.23.0'
@ -169,7 +170,7 @@ def instance_update(instance):
errmsg = 'node_count must be an integer %s (%s)' % (
instance.node_count, type(instance.node_count))
if instance.display_name and not isinstance(instance.display_name,
basestring):
string_types):
errmsg = 'instance_display_name must be an string %s (%s)' % (
instance.display_name, type(instance.display_name))
if errmsg:

View file

@ -449,6 +449,7 @@ else:
# import module bits
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.parsing.convert_bool import BOOLEANS_FALSE, BOOLEANS_TRUE
from ansible.module_utils.six.moves import xrange
# LXC_COMPRESSION_MAP is a map of available compression types when creating

View file

@ -933,13 +933,13 @@ class RHEVConn(object):
VM = self.get_VM(vmname)
try:
if str(VM.status.state) == 'down':
cdrom = params.CdRom(file=cd_iso)
cdrom = params.CdRom(file=cd_drive)
VM.cdroms.add(cdrom)
setMsg("Attached the image.")
setChanged()
else:
cdrom = VM.cdroms.get(id="00000000-0000-0000-0000-000000000000")
cdrom.set_file(cd_iso)
cdrom.set_file(cd_drive)
cdrom.update(current=True)
setMsg("Attached the image.")
setChanged()
@ -971,7 +971,7 @@ class RHEVConn(object):
HOST = self.get_Host_byid(VM.host.id)
if str(HOST.name) != vmhost:
try:
vm.migrate(
VM.migrate(
action=params.Action(
host=params.Host(
name=vmhost,

View file

@ -161,6 +161,7 @@ else:
HAS_XML = True
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
ALL_COMMANDS = []
@ -278,7 +279,7 @@ class LibvirtConnection(object):
if res == 0:
return True
# command, section, parentIndex, xml, flags=0
self.module.fail_json(msg='updating this is not supported yet '+unicode(xml))
self.module.fail_json(msg='updating this is not supported yet %s' % to_native(xml))
def destroy(self, entryid):
if not self.module.check_mode:

View file

@ -103,6 +103,9 @@ try:
except ImportError:
HAS_SHADE = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.openstack import openstack_full_argument_spec, openstack_module_kwargs
def main():
@ -129,7 +132,7 @@ def main():
if name:
# Let's suppose user is passing domain ID
try:
domains = cloud.get_domain(name)
domains = opcloud.get_domain(name)
except:
domains = opcloud.search_domains(filters={'name': name})
@ -142,8 +145,6 @@ def main():
except shade.OpenStackCloudException as e:
module.fail_json(msg=str(e))
from ansible.module_utils.basic import *
from ansible.module_utils.openstack import *
if __name__ == '__main__':
main()

View file

@ -89,6 +89,9 @@ try:
except ImportError:
HAS_SHADE = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.openstack import openstack_full_argument_spec, openstack_module_kwargs
_action_map = {'stop': 'SHUTOFF',
'start': 'ACTIVE',
@ -102,7 +105,7 @@ _action_map = {'stop': 'SHUTOFF',
_admin_actions = ['pause', 'unpause', 'suspend', 'resume', 'lock', 'unlock']
def _wait(timeout, cloud, server, action):
def _wait(timeout, cloud, server, action, module):
"""Wait for the server to reach the desired state for the given action."""
for count in shade._utils._iterate_timeout(
@ -166,7 +169,7 @@ def main():
cloud.nova_client.servers.stop(server=server.id)
if wait:
_wait(timeout, cloud, server, action)
_wait(timeout, cloud, server, action, module)
module.exit_json(changed=True)
if action == 'start':
@ -175,7 +178,7 @@ def main():
cloud.nova_client.servers.start(server=server.id)
if wait:
_wait(timeout, cloud, server, action)
_wait(timeout, cloud, server, action, module)
module.exit_json(changed=True)
if action == 'pause':
@ -184,7 +187,7 @@ def main():
cloud.nova_client.servers.pause(server=server.id)
if wait:
_wait(timeout, cloud, server, action)
_wait(timeout, cloud, server, action, module)
module.exit_json(changed=True)
elif action == 'unpause':
@ -193,7 +196,7 @@ def main():
cloud.nova_client.servers.unpause(server=server.id)
if wait:
_wait(timeout, cloud, server, action)
_wait(timeout, cloud, server, action, module)
module.exit_json(changed=True)
elif action == 'lock':
@ -212,7 +215,7 @@ def main():
cloud.nova_client.servers.suspend(server=server.id)
if wait:
_wait(timeout, cloud, server, action)
_wait(timeout, cloud, server, action, module)
module.exit_json(changed=True)
elif action == 'resume':
@ -221,7 +224,7 @@ def main():
cloud.nova_client.servers.resume(server=server.id)
if wait:
_wait(timeout, cloud, server, action)
_wait(timeout, cloud, server, action, module)
module.exit_json(changed=True)
elif action == 'rebuild':
@ -233,14 +236,12 @@ def main():
# rebuild doesn't set a state, just do it
cloud.nova_client.servers.rebuild(server=server.id, image=image.id)
if wait:
_wait(timeout, cloud, server, action)
_wait(timeout, cloud, server, action, module)
module.exit_json(changed=True)
except shade.OpenStackCloudException as e:
module.fail_json(msg=str(e), extra_data=e.extra_data)
# this is magic, see lib/ansible/module_common.py
from ansible.module_utils.basic import *
from ansible.module_utils.openstack import *
if __name__ == '__main__':
main()

View file

@ -170,7 +170,7 @@ def main():
name = module.params.get('name')
state = module.params.get('state')
backend = module.params.get('backend')
weight = long(module.params.get('weight'))
weight = module.params.get('weight')
probe = module.params.get('probe')
timeout = module.params.get('timeout')

View file

@ -204,6 +204,7 @@ EXAMPLES = '''
import re
import uuid
import time
import traceback
HAS_PB_SDK = True
@ -213,7 +214,8 @@ except ImportError:
HAS_PB_SDK = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
from ansible.module_utils.six.moves import xrange
from ansible.module_utils._text import to_native
LOCATIONS = ['us/las',
@ -401,12 +403,11 @@ def create_virtual_machine(module, profitbricks):
try:
name % 0
except TypeError:
e = get_exception()
except TypeError as e:
if e.message.startswith('not all'):
name = '%s%%d' % name
else:
module.fail_json(msg=e.message)
module.fail_json(msg=e.message, exception=traceback.format_exc())
number_range = xrange(count_offset, count_offset + count + len(numbers))
available_numbers = list(set(number_range).difference(numbers))
@ -487,9 +488,8 @@ def remove_virtual_machine(module, profitbricks):
# Remove the server
try:
server_response = profitbricks.delete_server(datacenter_id, server_id)
except Exception:
e = get_exception()
module.fail_json(msg="failed to terminate the virtual server: %s" % str(e))
except Exception as e:
module.fail_json(msg="failed to terminate the virtual server: %s" % to_native(e), exception=traceback.format_exc())
else:
changed = True
@ -504,9 +504,8 @@ def _remove_boot_volume(module, profitbricks, datacenter_id, server_id):
server = profitbricks.get_server(datacenter_id, server_id)
volume_id = server['properties']['bootVolume']['id']
volume_response = profitbricks.delete_volume(datacenter_id, volume_id)
except Exception:
e = get_exception()
module.fail_json(msg="failed to remove the server's boot volume: %s" % str(e))
except Exception as e:
module.fail_json(msg="failed to remove the server's boot volume: %s" % to_native(e), exception=traceback.format_exc())
def startstop_machine(module, profitbricks, state):
@ -638,9 +637,8 @@ def main():
try:
(changed) = remove_virtual_machine(module, profitbricks)
module.exit_json(changed=changed)
except Exception:
e = get_exception()
module.fail_json(msg='failed to set instance state: %s' % str(e))
except Exception as e:
module.fail_json(msg='failed to set instance state: %s' % to_native(e), exception=traceback.format_exc())
elif state in ('running', 'stopped'):
if not module.params.get('datacenter'):
@ -649,9 +647,8 @@ def main():
try:
(changed) = startstop_machine(module, profitbricks, state)
module.exit_json(changed=changed)
except Exception:
e = get_exception()
module.fail_json(msg='failed to set instance state: %s' % str(e))
except Exception as e:
module.fail_json(msg='failed to set instance state: %s' % to_native(e), exception=traceback.format_exc())
elif state == 'present':
if not module.params.get('name'):
@ -668,9 +665,8 @@ def main():
try:
(machine_dict_array) = create_virtual_machine(module, profitbricks)
module.exit_json(**machine_dict_array)
except Exception:
e = get_exception()
module.fail_json(msg='failed to set instance state: %s' % str(e))
except Exception as e:
module.fail_json(msg='failed to set instance state: %s' % to_native(e), exception=traceback.format_exc())
if __name__ == '__main__':

View file

@ -141,6 +141,7 @@ EXAMPLES = '''
import re
import time
import traceback
HAS_PB_SDK = True
@ -150,7 +151,8 @@ except ImportError:
HAS_PB_SDK = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
from ansible.module_utils.six.moves import xrange
from ansible.module_utils._text import to_native
uuid_match = re.compile(
@ -262,12 +264,11 @@ def create_volume(module, profitbricks):
try:
name % 0
except TypeError:
e = get_exception()
except TypeError as e:
if e.message.startswith('not all'):
name = '%s%%d' % name
else:
module.fail_json(msg=e.message)
module.fail_json(msg=e.message, exception=traceback.format_exc())
number_range = xrange(count_offset, count_offset + count + len(numbers))
available_numbers = list(set(number_range).difference(numbers))
@ -326,7 +327,7 @@ def delete_volume(module, profitbricks):
for n in instance_ids:
if(uuid_match.match(n)):
_delete_volume(module, profitbricks, datacenter, volume)
_delete_volume(module, profitbricks, datacenter, n)
changed = True
else:
volumes = profitbricks.list_volumes(datacenter)
@ -364,9 +365,8 @@ def _attach_volume(module, profitbricks, datacenter, volume):
try:
return profitbricks.attach_volume(datacenter, server, volume)
except Exception:
e = get_exception()
module.fail_json(msg='failed to attach volume: %s' % str(e))
except Exception as e:
module.fail_json(msg='failed to attach volume: %s' % to_native(e), exception=traceback.format_exc())
def main():
@ -414,9 +414,8 @@ def main():
try:
(changed) = delete_volume(module, profitbricks)
module.exit_json(changed=changed)
except Exception:
e = get_exception()
module.fail_json(msg='failed to set volume state: %s' % str(e))
except Exception as e:
module.fail_json(msg='failed to set volume state: %s' % to_native(e), exception=traceback.format_exc())
elif state == 'present':
if not module.params.get('datacenter'):
@ -427,9 +426,8 @@ def main():
try:
(volume_dict_array) = create_volume(module, profitbricks)
module.exit_json(**volume_dict_array)
except Exception:
e = get_exception()
module.fail_json(msg='failed to set volume state: %s' % str(e))
except Exception as e:
module.fail_json(msg='failed to set volume state: %s' % to_native(e), exception=traceback.format_exc())
if __name__ == '__main__':

View file

@ -240,12 +240,24 @@ EXAMPLES = '''
register: rax
'''
import os
import json
import re
import time
try:
import pyrax
HAS_PYRAX = True
except ImportError:
HAS_PYRAX = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.rax import (FINAL_STATUSES, rax_argument_spec, rax_find_bootable_volume,
rax_find_image, rax_find_network, rax_find_volume,
rax_required_together, rax_to_dict, setup_rax_module)
from ansible.module_utils.six.moves import xrange
from ansible.module_utils.six import string_types
def rax_find_server_image(module, server, image, boot_volume):
if not image and boot_volume:
@ -515,7 +527,7 @@ def cloudservers(module, state=None, name=None, flavor=None, image=None,
meta[k] = ','.join(['%s' % i for i in v])
elif isinstance(v, dict):
meta[k] = json.dumps(v)
elif not isinstance(v, basestring):
elif not isinstance(v, string_types):
meta[k] = '%s' % v
# When using state=absent with group, the absent block won't match the
@ -890,11 +902,5 @@ def main():
boot_volume_terminate=boot_volume_terminate)
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.rax import *
# invoke the module
if __name__ == '__main__':
main()

View file

@ -131,7 +131,9 @@ except ImportError:
def _activate_virtualenv(path):
path = os.path.expanduser(path)
activate_this = os.path.join(path, 'bin', 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
with open(activate_this) as f:
code = compile(f.read(), activate_this, 'exec')
exec(code)
def _get_node(lb, node_id=None, address=None, port=None):

View file

@ -74,12 +74,18 @@ EXAMPLES = '''
region: DFW
'''
import json
try:
import pyrax
HAS_PYRAX = True
except ImportError:
HAS_PYRAX = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.rax import rax_argument_spec, rax_required_together, setup_rax_module
from ansible.module_utils.six import string_types
def rax_meta(module, address, name, server_id, meta):
changed = False
@ -128,7 +134,7 @@ def rax_meta(module, address, name, server_id, meta):
meta[k] = ','.join(['%s' % i for i in v])
elif isinstance(v, dict):
meta[k] = json.dumps(v)
elif not isinstance(v, basestring):
elif not isinstance(v, string_types):
meta[k] = '%s' % v
server = servers[0]
@ -175,11 +181,5 @@ def main():
rax_meta(module, address, name, server_id, meta)
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.rax import *
### invoke the module
if __name__ == '__main__':
main()

View file

@ -149,6 +149,9 @@ EXAMPLES = '''
'''
import base64
import json
import os
import time
try:
import pyrax
@ -156,6 +159,11 @@ try:
except ImportError:
HAS_PYRAX = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.rax import (rax_argument_spec, rax_find_image, rax_find_network,
rax_required_together, rax_to_dict, setup_rax_module)
from ansible.module_utils.six import string_types
def rax_asg(module, cooldown=300, disk_config=None, files={}, flavor=None,
image=None, key_name=None, loadbalancers=[], meta={},
@ -189,7 +197,7 @@ def rax_asg(module, cooldown=300, disk_config=None, files={}, flavor=None,
meta[k] = ','.join(['%s' % i for i in v])
elif isinstance(v, dict):
meta[k] = json.dumps(v)
elif not isinstance(v, basestring):
elif not isinstance(v, string_types):
meta[k] = '%s' % v
if image:
@ -426,11 +434,5 @@ def main():
state=state, config_drive=config_drive, user_data=user_data)
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.rax import *
# invoke the module
if __name__ == '__main__':
main()

View file

@ -346,18 +346,19 @@ state:
sample: 'running'
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
from ansible.module_utils._text import to_native
import os
import re
import tempfile
import traceback
try:
import json
except ImportError:
import simplejson as json
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
# While vmadm(1M) supports a -E option to return any errors in JSON, the
# generated JSON does not play well with the JSON parsers of Python.
# The returned message contains '\n' as part of the stacktrace,
@ -377,11 +378,10 @@ def get_vm_prop(module, uuid, prop):
try:
stdout_json = json.loads(stdout)
except:
e = get_exception()
except Exception as e:
module.fail_json(
msg='Invalid JSON returned by vmadm for uuid lookup of {0}'.format(alias),
details=to_native(e))
msg='Invalid JSON returned by vmadm for uuid lookup of {0}'.format(uuid),
details=to_native(e), exception=traceback.format_exc())
if len(stdout_json) > 0 and prop in stdout_json[0]:
return stdout_json[0][prop]
@ -408,11 +408,10 @@ def get_vm_uuid(module, alias):
else:
try:
stdout_json = json.loads(stdout)
except:
e = get_exception()
except Exception as e:
module.fail_json(
msg='Invalid JSON returned by vmadm for uuid lookup of {0}'.format(alias),
details=to_native(e))
details=to_native(e), exception=traceback.format_exc())
if len(stdout_json) > 0 and 'uuid' in stdout_json[0]:
return stdout_json[0]['uuid']
@ -430,9 +429,9 @@ def get_all_vm_uuids(module):
try:
stdout_json = json.loads(stdout)
return [v['uuid'] for v in stdout_json]
except:
e = get_exception()
module.fail_json(msg='Could not retrieve VM UUIDs', details=to_native(e))
except Exception as e:
module.fail_json(msg='Could not retrieve VM UUIDs', details=to_native(e),
exception=traceback.format_exc())
def new_vm(module, uuid, vm_state):

View file

@ -236,8 +236,22 @@ EXAMPLES = '''
# TODO: Disabled RETURN as it is breaking the build for docs. Needs to be fixed.
RETURN = '''# '''
import json
import time
try:
import SoftLayer
from SoftLayer import VSManager
HAS_SL = True
vsManager = VSManager(SoftLayer.create_client_from_env())
except ImportError:
HAS_SL = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six import string_types
#TODO: get this info from API
STATES = ['present', 'absent']
DATACENTERS = ['ams01', 'ams03', 'che01', 'dal01', 'dal05', 'dal06', 'dal09', 'dal10', 'fra02', 'hkg02', 'hou02', 'lon02', 'mel01', 'mex01', 'mil01', 'mon01',
@ -249,15 +263,6 @@ LOCALDISK_SIZES = [25, 100, 150, 200, 300]
SANDISK_SIZES = [10, 20, 25, 30, 40, 50, 75, 100, 125, 150, 175, 200, 250, 300, 350, 400, 500, 750, 1000, 1500, 2000]
NIC_SPEEDS = [10, 100, 1000]
try:
import SoftLayer
from SoftLayer import VSManager
HAS_SL = True
vsManager = VSManager(SoftLayer.create_client_from_env())
except ImportError:
HAS_SL = False
def create_virtual_instance(module):
@ -329,7 +334,7 @@ def cancel_instance(module):
canceled = True
if module.params.get('instance_id') is None and (module.params.get('tags') or module.params.get('hostname') or module.params.get('domain')):
tags = module.params.get('tags')
if isinstance(tags, basestring):
if isinstance(tags, string_types):
tags = [module.params.get('tags')]
instances = vsManager.list_instances(tags = tags, hostname = module.params.get('hostname'), domain = module.params.get('domain'))
for instance in instances:
@ -390,7 +395,6 @@ def main():
module.exit_json(changed=changed, instance=json.loads(json.dumps(instance, default=lambda o: o.__dict__)))
from ansible.module_utils.basic import *
if __name__ == '__main__':
main()

View file

@ -207,9 +207,9 @@ def main():
except IndexError:
additions.append(rule)
eol = len(current_rules) > len(desired_rules)
eol = len(current_rules) - len(desired_rules)
if eol > 0:
for rule in current_rules[eos:]:
for rule in current_rules[eol:]:
deletions.append(rule)
for rule in additions:

View file

@ -1,5 +1,4 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# This file is part of Ansible
#
@ -308,10 +307,11 @@ EXAMPLES = '''
force: yes
'''
try:
import json
except ImportError:
import simplejson as json
import json
import os
import re
import ssl
import traceback
HAS_PYSPHERE = False
try:
@ -323,7 +323,9 @@ try:
except ImportError:
pass
import ssl
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six import string_types
from ansible.module_utils._text import to_native
def add_scsi_controller(module, s, config, devices, type="paravirtual", bus_num=0, disk_ctrl_key=1):
@ -1041,11 +1043,10 @@ def reconfigure_vm(vsphere_client, vm, module, esxi, resource_pool, cluster_name
vm.power_off(sync_run=True)
vm.get_status()
except Exception:
e = get_exception()
module.fail_json(
msg='Failed to shutdown vm %s: %s' % (guest, e)
)
except Exception as e:
module.fail_json(msg='Failed to shutdown vm %s: %s'
% (guest, to_native(e)),
exception=traceback.format_exc())
if len(devices):
spec.set_element_deviceChange(devices)
@ -1065,10 +1066,10 @@ def reconfigure_vm(vsphere_client, vm, module, esxi, resource_pool, cluster_name
if vm.is_powered_off() and poweron:
try:
vm.power_on(sync_run=True)
except Exception:
e = get_exception()
except Exception as e:
module.fail_json(
msg='Failed to power on vm %s : %s' % (guest, e)
msg='Failed to power on vm %s : %s' % (guest, to_native(e)),
exception=traceback.format_exc()
)
vsphere_client.disconnect()
@ -1503,10 +1504,10 @@ def delete_vm(vsphere_client, module, guest, vm, force):
vm.power_off(sync_run=True)
vm.get_status()
except Exception:
e = get_exception()
except Exception as e:
module.fail_json(
msg='Failed to shutdown vm %s: %s' % (guest, e))
msg='Failed to shutdown vm %s: %s' % (guest, to_native(e)),
exception=traceback.format_exc())
else:
module.fail_json(
msg='You must use either shut the vm down first or '
@ -1528,10 +1529,10 @@ def delete_vm(vsphere_client, module, guest, vm, force):
module.fail_json(msg="Error removing vm: %s %s" %
task.get_error_message())
module.exit_json(changed=True, changes="VM %s deleted" % guest)
except Exception:
e = get_exception()
except Exception as e:
module.fail_json(
msg='Failed to delete vm %s : %s' % (guest, e))
msg='Failed to delete vm %s : %s' % (guest, to_native(e)),
exception=traceback.format_exc())
def power_state(vm, state, force):
@ -1571,8 +1572,8 @@ def power_state(vm, state, force):
% power_status
return True
except Exception:
return get_exception()
except Exception as e:
return e
return False
@ -1650,8 +1651,9 @@ class DefaultVMConfig(object):
try:
if v == int:
self.check_dict[key][k] = int(self.check_dict[key][k])
elif v == basestring:
self.check_dict[key][k] = str(self.check_dict[key][k])
elif v == string_types:
self.check_dict[key][k] = to_native(self.check_dict[key][k],
errors='surrogate_or_strict')
else:
raise ValueError
except ValueError:
@ -1689,29 +1691,29 @@ def main():
proto_vm_hardware = {
'memory_mb': int,
'num_cpus': int,
'scsi': basestring,
'osid': basestring
'scsi': string_types,
'osid': string_types
}
proto_vm_disk = {
'disk1': {
'datastore': basestring,
'datastore': string_types,
'size_gb': int,
'type': basestring
'type': string_types
}
}
proto_vm_nic = {
'nic1': {
'type': basestring,
'network': basestring,
'network_type': basestring
'type': string_types,
'network': string_types,
'network_type': string_types
}
}
proto_esxi = {
'datacenter': basestring,
'hostname': basestring
'datacenter': string_types,
'hostname': string_types
}
module = AnsibleModule(
@ -1816,10 +1818,10 @@ def main():
module.fail_json(msg='Unable to validate the certificate of the vcenter host %s' % vcenter_hostname)
else:
raise
except VIApiException:
err = get_exception()
except VIApiException as err:
module.fail_json(msg="Cannot connect to %s: %s" %
(vcenter_hostname, err))
(vcenter_hostname, to_native(err)),
exception=traceback.format_exc())
# Check if the VM exists before continuing
try:
@ -1832,16 +1834,15 @@ def main():
if vmware_guest_facts:
try:
module.exit_json(ansible_facts=gather_facts(vm))
except Exception:
e = get_exception()
module.fail_json(
msg="Fact gather failed with exception %s" % e)
except Exception as e:
module.fail_json(msg="Fact gather failed with exception %s"
% to_native(e), exception=traceback.format_exc())
# Power Changes
elif state in ['powered_on', 'powered_off', 'restarted']:
state_result = power_state(vm, state, force)
# Failure
if isinstance(state_result, basestring):
if isinstance(state_result, string_types):
module.fail_json(msg=state_result)
else:
module.exit_json(changed=state_result)
@ -1941,7 +1942,5 @@ def main():
vcenter=vcenter_hostname)
# this is magic, see lib/ansible/module_common.py
from ansible.module_utils.basic import *
if __name__ == '__main__':
main()