def main(): module = AnsibleModule(argument_spec={ 'key': { 'required': True }, 'bool': { 'type': 'bool' }, 'int': { 'type': 'int' }, 'string': { 'type': 'str' }, 'float': { 'type': 'float' }, }, mutually_exclusive=[ ['bool', 'string', 'int', 'float'], ], required_one_of=[['bool', 'string', 'int', 'float']], supports_check_mode=True) key = module.params['key'] boolean_value = module.params['bool'] string_value = module.params['string'] integer_value = module.params['int'] float_value = module.params['float'] old_value = _get_value(module, key) if boolean_value is not None: value = str(mk_boolean(boolean_value)).lower() old_value = str(mk_boolean(old_value)).lower() elif integer_value is not None: value = int(integer_value) elif string_value is not None: value = string_value elif float_value is not None: value = float_value changed = old_value != str(value) if changed and not module.check_mode: _set_value(module, key, value) module.exit_json(changed=changed, key=key, value=value, old_value=old_value)
def do_diff(self, arg): """Toggle whether plays run with diff""" if arg: self.options.diff = C.mk_boolean(arg) display.v("diff mode changed to %s" % self.options.diff) else: display.display("Please specify a diff value , e.g. `diff yes`")
def do_check(self, arg): """Toggle whether plays run with check mode""" if arg: self.options.check = C.mk_boolean(arg) display.v("check mode changed to %s" % self.options.check) else: display.display("Please specify check mode value, e.g. `check yes`")
def do_become(self, arg): """Toggle whether plays run with become""" if arg: self.options.become = C.mk_boolean(arg) display.v("become changed to %s" % self.options.become) self.set_prompt() else: display.display("Please specify become value, e.g. `become yes`")
def test_strings(self): assert constants.mk_boolean("true") is True assert constants.mk_boolean("TRUE") is True assert constants.mk_boolean("t") is True assert constants.mk_boolean("yes") is True assert constants.mk_boolean("y") is True assert constants.mk_boolean("on") is True
def __init__(self, display=None): self.disabled = False if cli: self._options = cli.options else: self._options = None super(CallbackModule, self).__init__(display=display) if not HAS_PRETTYTABLE: self.disabled = True self._display.warning('The `prettytable` python module is not ' 'installed. Disabling the Slack callback ' 'plugin.') self.webhook_url = os.getenv('SLACK_WEBHOOK_URL') self.channel = os.getenv('SLACK_CHANNEL', '#ansible') self.username = os.getenv('SLACK_USERNAME', 'ansible') self.show_invocation = mk_boolean( os.getenv('SLACK_INVOCATION', self._display.verbosity > 1) ) if self.webhook_url is None: self.disabled = True self._display.warning('Slack Webhook URL was not provided. The ' 'Slack Webhook URL can be provided using ' 'the `SLACK_WEBHOOK_URL` environment ' 'variable.') self.playbook_name = None # This is a 6 character identifier provided with each message # This makes it easier to correlate messages when there are more # than 1 simultaneous playbooks running self.guid = uuid.uuid4().hex[:6]
def test_numbers(self): assert constants.mk_boolean(1) is True assert constants.mk_boolean(0) is False assert constants.mk_boolean(0.0) is False
def test_none(self): assert constants.mk_boolean(None) is False
def main(): # module specification module = AnsibleModule( argument_spec={ 'key': {'required': True}, 'bool': {'type': 'bool'}, 'int': {'type': 'int'}, 'string': {'type': 'str'}, 'float': {'type': 'float'}, 'list': {'type': 'list'}, 'pair': {'type': 'list'}, 'pair-cdr-type': {'choices': ['int', 'bool', 'float', 'string']}, 'pair-car-type': {'choices': ['int', 'bool', 'float', 'string']}, 'list-type': {'choices': ['int', 'bool', 'float', 'string']} }, mutually_exclusive=[ ['bool', 'string', 'int', 'float', 'list', 'pair'], ['bool', 'string', 'int', 'float', 'list-type', 'pair'], ['bool', 'string', 'int', 'float', 'list', 'pair-car-type'], ['bool', 'string', 'int', 'float', 'list', 'pair-cdr-type'], ], required_one_of=[['bool', 'string', 'int', 'float', 'list', 'pair']], required_together=[ ['pair', 'pair-car-type', 'pair-cdr-type'], ['list', 'list-type'] ], supports_check_mode=True ) key = module.params['key'] boolean_value = module.params['bool'] string_value = module.params['string'] integer_value = module.params['int'] float_value = module.params['float'] list_value = module.params['list'] pair_value = module.params['pair'] additional_args = '' instance_type_mapping = {'int': int, 'string': str, 'float': float, 'bool': mk_boolean} if boolean_value is not None: argument_type = 'bool' value = str(mk_boolean(boolean_value)).lower() old_value = str(mk_boolean(old_value)).lower() #... elif float_value is not None: argument_type = 'float' value = float_value # ... elif pair_value is not None: if len(pair_value) != 2: module.fail_json(msg='A pair must be a list of length 2, {} items found.'.format(len)) argument_type = 'pair' try: car_value = pair_value[0] car_type = module.params['pair-car-type'] if car_type == 'bool': module.boolean(car_value) car_value = mk_boolean(car_value) elif not str(instance_type_mapping) old_value = _get_value(module, key) # argument parsing changed = old_value != str(value) if changed and not module.check_mode: _set_value(module, key, value, argument_type, additional_args) module.exit_json( changed=changed, key=key, type=argument_type, value=value, old_value=old_value )
def __init__(self): self.playbook = None self.enabled = mk_boolean(os.getenv(VAR_IDEMPOTENCE, 'no')) super(CallbackModule, self).__init__()
def _list(regions): groups = collections.defaultdict(list) hostvars = collections.defaultdict(dict) images = {} cbs_attachments = collections.defaultdict(dict) prefix = get_config(p, 'rax', 'meta_prefix', 'RAX_META_PREFIX', 'meta') networks = get_config(p, 'rax', 'access_network', 'RAX_ACCESS_NETWORK', 'public', islist=True) try: ip_versions = map( int, get_config(p, 'rax', 'access_ip_version', 'RAX_ACCESS_IP_VERSION', 4, islist=True)) except: ip_versions = [4] else: ip_versions = [v for v in ip_versions if v in [4, 6]] if not ip_versions: ip_versions = [4] # Go through all the regions looking for servers for region in regions: # Connect to the region cs = pyrax.connect_to_cloudservers(region=region) if cs is None: warnings.warn( 'Connecting to Rackspace region "%s" has caused Pyrax to ' 'return a NoneType. Is this a valid region?' % region, RuntimeWarning) continue for server in cs.servers.list(): # Create a group on region groups[region].append(server.name) # Check if group metadata key in servers' metadata group = server.metadata.get('group') if group: groups[group].append(server.name) for extra_group in server.metadata.get('groups', '').split(','): if extra_group: groups[extra_group].append(server.name) # Add host metadata for key, value in to_dict(server).items(): hostvars[server.name][key] = value hostvars[server.name]['rax_region'] = region for key, value in server.metadata.iteritems(): groups['%s_%s_%s' % (prefix, key, value)].append(server.name) groups['instance-%s' % server.id].append(server.name) groups['flavor-%s' % server.flavor['id']].append(server.name) # Handle boot from volume if not server.image: if not cbs_attachments[region]: cbs = pyrax.connect_to_cloud_blockstorage(region) for vol in cbs.list(): if mk_boolean(vol.bootable): for attachment in vol.attachments: metadata = vol.volume_image_metadata server_id = attachment['server_id'] cbs_attachments[region][server_id] = { 'id': metadata['image_id'], 'name': slugify(metadata['image_name']) } image = cbs_attachments[region].get(server.id) if image: server.image = {'id': image['id']} hostvars[server.name]['rax_image'] = server.image hostvars[server.name]['rax_boot_source'] = 'volume' images[image['id']] = image['name'] else: hostvars[server.name]['rax_boot_source'] = 'local' try: imagegroup = 'image-%s' % images[server.image['id']] groups[imagegroup].append(server.name) groups['image-%s' % server.image['id']].append(server.name) except KeyError: try: image = cs.images.get(server.image['id']) except cs.exceptions.NotFound: groups['image-%s' % server.image['id']].append(server.name) else: images[image.id] = image.human_id groups['image-%s' % image.human_id].append(server.name) groups['image-%s' % server.image['id']].append(server.name) # And finally, add an IP address ansible_ssh_host = None # use accessIPv[46] instead of looping address for 'public' for network_name in networks: if ansible_ssh_host: break if network_name == 'public': for version_name in ip_versions: if ansible_ssh_host: break if version_name == 6 and server.accessIPv6: ansible_ssh_host = server.accessIPv6 elif server.accessIPv4: ansible_ssh_host = server.accessIPv4 if not ansible_ssh_host: addresses = server.addresses.get(network_name, []) for address in addresses: for version_name in ip_versions: if ansible_ssh_host: break if address.get('version') == version_name: ansible_ssh_host = address.get('addr') break if ansible_ssh_host: hostvars[server.name]['ansible_ssh_host'] = ansible_ssh_host if hostvars: groups['_meta'] = {'hostvars': hostvars} print(json.dumps(groups, sort_keys=True, indent=4))
def _list(regions): groups = collections.defaultdict(list) hostvars = collections.defaultdict(dict) images = {} cbs_attachments = collections.defaultdict(dict) prefix = get_config(p, 'rax', 'meta_prefix', 'RAX_META_PREFIX', 'meta') networks = get_config(p, 'rax', 'access_network', 'RAX_ACCESS_NETWORK', 'public', islist=True) try: ip_versions = map(int, get_config(p, 'rax', 'access_ip_version', 'RAX_ACCESS_IP_VERSION', 4, islist=True)) except: ip_versions = [4] else: ip_versions = [v for v in ip_versions if v in [4, 6]] if not ip_versions: ip_versions = [4] # Go through all the regions looking for servers for region in regions: # Connect to the region cs = pyrax.connect_to_cloudservers(region=region) if cs is None: warnings.warn( 'Connecting to Rackspace region "%s" has caused Pyrax to ' 'return a NoneType. Is this a valid region?' % region, RuntimeWarning) continue for server in cs.servers.list(): # Create a group on region groups[region].append(server.name) # Check if group metadata key in servers' metadata group = server.metadata.get('group') if group: groups[group].append(server.name) for extra_group in server.metadata.get('groups', '').split(','): if extra_group: groups[extra_group].append(server.name) # Add host metadata for key, value in to_dict(server).items(): hostvars[server.name][key] = value hostvars[server.name]['rax_region'] = region for key, value in server.metadata.iteritems(): groups['%s_%s_%s' % (prefix, key, value)].append(server.name) groups['instance-%s' % server.id].append(server.name) groups['flavor-%s' % server.flavor['id']].append(server.name) # Handle boot from volume if not server.image: if not cbs_attachments[region]: cbs = pyrax.connect_to_cloud_blockstorage(region) for vol in cbs.list(): if mk_boolean(vol.bootable): for attachment in vol.attachments: metadata = vol.volume_image_metadata server_id = attachment['server_id'] cbs_attachments[region][server_id] = { 'id': metadata['image_id'], 'name': slugify(metadata['image_name']) } image = cbs_attachments[region].get(server.id) if image: server.image = {'id': image['id']} hostvars[server.name]['rax_image'] = server.image hostvars[server.name]['rax_boot_source'] = 'volume' images[image['id']] = image['name'] else: hostvars[server.name]['rax_boot_source'] = 'local' try: imagegroup = 'image-%s' % images[server.image['id']] groups[imagegroup].append(server.name) groups['image-%s' % server.image['id']].append(server.name) except KeyError: try: image = cs.images.get(server.image['id']) except cs.exceptions.NotFound: groups['image-%s' % server.image['id']].append(server.name) else: images[image.id] = image.human_id groups['image-%s' % image.human_id].append(server.name) groups['image-%s' % server.image['id']].append(server.name) # And finally, add an IP address ansible_ssh_host = None # use accessIPv[46] instead of looping address for 'public' for network_name in networks: if ansible_ssh_host: break if network_name == 'public': for version_name in ip_versions: if ansible_ssh_host: break if version_name == 6 and server.accessIPv6: ansible_ssh_host = server.accessIPv6 elif server.accessIPv4: ansible_ssh_host = server.accessIPv4 if not ansible_ssh_host: addresses = server.addresses.get(network_name, []) for address in addresses: for version_name in ip_versions: if ansible_ssh_host: break if address.get('version') == version_name: ansible_ssh_host = address.get('addr') break if ansible_ssh_host: hostvars[server.name]['ansible_ssh_host'] = ansible_ssh_host if hostvars: groups['_meta'] = {'hostvars': hostvars} print(json.dumps(groups, sort_keys=True, indent=4))
def test_bools(self): assert constants.mk_boolean(True) is True assert constants.mk_boolean(False) is False
def main(): module = AnsibleModule( argument_spec={ 'key': { 'required': True }, 'bool': { 'type': 'bool' }, 'int': { 'type': 'int' }, 'string': { 'type': 'str' }, 'float': { 'type': 'float' }, 'list': { 'type': 'list' }, 'pair': { 'type': 'list' }, 'pair-cdr-type': { 'choices': ['int', 'bool', 'float', 'string'] }, 'pair-car-type': { 'choices': ['int', 'bool', 'float', 'string'] }, 'list-type': { 'choices': ['int', 'bool', 'float', 'string'] } }, mutually_exclusive=[ ['bool', 'string', 'int', 'float', 'list', 'pair'], ['bool', 'string', 'int', 'float', 'list-type', 'pair'], ['bool', 'string', 'int', 'float', 'list', 'pair-car-type'], ['bool', 'string', 'int', 'float', 'list', 'pair-cdr-type'] ], required_one_of=[['bool', 'string', 'int', 'float', 'list', 'pair']], required_together=[['pair', 'pair-car-type', 'pair-cdr-type'], ['list', 'list-type']], supports_check_mode=True) key = module.params['key'] boolean_value = module.params['bool'] string_value = module.params['string'] integer_value = module.params['int'] float_value = module.params['float'] list_value = module.params['list'] pair_value = module.params['pair'] old_value = _get_value(module, key) additional_args = '' instance_type_mapping = { 'int': int, 'string': str, 'float': float, 'bool': mk_boolean } if boolean_value is not None: argument_type = 'bool' value = str(mk_boolean(boolean_value)).lower() old_value = str(mk_boolean(old_value)).lower() elif integer_value is not None: argument_type = 'integer' value = int(integer_value) elif string_value is not None: argument_type = 'string' value = string_value elif float_value is not None: argument_type = 'float' value = float_value elif list_value is not None: argument_type = 'list' try: for item in list_value: if module.params['list-type'] == 'bool': module.boolean(item) elif not str( instance_type_mapping.get( module.params['list-type'])(item)) == item: raise ValueError except ValueError: module.fail_json( msg='list type `{}` does not match the type of the contents.'. format(module.params['list-type'])) additional_args = '--list-type={}'.format(module.params['list-type']) if module.params['list-type'] == 'bool': list_value = [str(mk_boolean(item)).lower() for item in list_value] value = '[{}]'.format(','.join(list_value)) elif pair_value is not None: if len(pair_value) != 2: module.fail_json( msg='A pair must be a list of length 2, {} items found.'. format(len(pair_value))) argument_type = 'pair' try: car_value = pair_value[0] car_type = module.params['pair-car-type'] if car_type == 'bool': module.boolean(car_value) car_value = mk_boolean(car_value) elif not str(instance_type_mapping.get(car_type) (car_value)) == car_value: raise ValueError cdr_value = pair_value[1] cdr_type = module.params['pair-cdr-type'] if cdr_type == 'bool': module.boolean(cdr_value) cdr_value = mk_boolean(cdr_value) elif not str(instance_type_mapping.get(cdr_type) (cdr_value)) == cdr_value: raise ValueError except ValueError: module.fail_json( msg= 'pair type `{}` or `{}` does not match the type of the contents.' .format(module.params['pair-car-type'], module.params['pair-cdr-type'])) additional_args = '--car-type={} --cdr-type={}'.format( car_type, cdr_type) value = '({},{})'.format(car_value, cdr_value) changed = old_value != str(value) if changed and not module.check_mode: _set_value(module, key, value, argument_type, additional_args) module.exit_json(changed=changed, key=key, type=argument_type, value=value, old_value=old_value)