desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Add additional requirements from setup.cfg to file metadata_path'
def add_requirements(self, metadata_path):
additional = list(self.setupcfg_requirements()) if (not additional): return pkg_info = read_pkg_info(metadata_path) if (('Provides-Extra' in pkg_info) or ('Requires-Dist' in pkg_info)): warnings.warn('setup.cfg requirements overwrite values from setup.py') del pkg_...
'Convert an .egg-info directory into a .dist-info directory'
def egg2dist(self, egginfo_path, distinfo_path):
def adios(p): 'Appropriately delete directory, file or link.' if (os.path.exists(p) and (not os.path.islink(p)) and os.path.isdir(p)): shutil.rmtree(p) elif os.path.exists(p): os.unlink(p) adios(distinfo_path) if (not os.path.exists(egginfo_path...
'Main execution path'
def __init__(self):
self.inventory = dict() self.cache = dict() self.read_settings() self.parse_cli_args() if self.args.host: print _json_format_dict(self.get_host_info(), self.args.pretty) elif self.args.list: print _json_format_dict(self.get_inventory(), self.args.pretty) else: print _...
'Reads the settings from the libvirt.ini file'
def read_settings(self):
config = ConfigParser.SafeConfigParser() config.read((os.path.dirname(os.path.realpath(__file__)) + '/libvirt.ini')) self.libvirt_uri = config.get('libvirt', 'uri')
'Command line argument processing'
def parse_cli_args(self):
parser = argparse.ArgumentParser(description='Produce an Ansible Inventory file based on libvirt') parser.add_argument('--list', action='store_true', default=True, help='List instances (default: True)') parser.add_argument('--host', action='store', help='Get all the va...
'Get variables about a specific host'
def get_host_info(self):
inventory = self.get_inventory() if (self.args.host in inventory['_meta']['hostvars']): return inventory['_meta']['hostvars'][self.args.host]
'Construct the inventory'
def get_inventory(self):
inventory = dict(_meta=dict(hostvars=dict())) conn = libvirt.openReadOnly(self.libvirt_uri) if (conn is None): print ('Failed to open connection to %s' % self.libvirt_uri) sys.exit(1) domains = conn.listAllDomains() if (domains is None): print ('Failed to ...
'Determines if the cache files have expired, or if it is still valid'
def is_valid(self, max_age=None):
if (max_age is None): max_age = self.cache_max_age if os.path.isfile(self.cache_path_cache): mod_time = os.path.getmtime(self.cache_path_cache) current_time = time() if ((mod_time + max_age) > current_time): return True return False
'Reads the JSON inventory from the cache file. Returns Python dictionary.'
def get_all_data_from_cache(self, filename=''):
data = '' if (not filename): filename = self.cache_path_cache with open(filename, 'r') as cache: data = cache.read() return json.loads(data)
'Writes data to file as JSON. Returns True.'
def write_to_cache(self, data, filename=''):
if (not filename): filename = self.cache_path_cache json_data = json.dumps(data) with open(filename, 'w') as cache: cache.write(json_data) return True
'Reads the settings from the gce.ini file. Populates a SafeConfigParser object with defaults and attempts to read an .ini-style configuration from the filename specified in GCE_INI_PATH. If the environment variable is not present, the filename defaults to gce.ini in the current working directory.'
def get_config(self):
gce_ini_default_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'gce.ini') gce_ini_path = os.environ.get('GCE_INI_PATH', gce_ini_default_path) config = ConfigParser.SafeConfigParser(defaults={'gce_service_account_email_address': '', 'gce_service_account_pem_file_path': '', 'gce_project_id':...
'Determine inventory options. Environment variables always take precedence over configuration files.'
def get_inventory_options(self):
ip_type = self.config.get('inventory', 'inventory_ip_type') ip_type = os.environ.get('INVENTORY_IP_TYPE', ip_type) return ip_type
'Determine the GCE authorization settings and return a libcloud driver.'
def get_gce_driver(self):
secrets_path = self.config.get('gce', 'libcloud_secrets') secrets_found = False try: import secrets args = list(getattr(secrets, 'GCE_PARAMS', [])) kwargs = getattr(secrets, 'GCE_KEYWORD_PARAMS', {}) secrets_found = True except: pass if ((not secrets_found) an...
'returns a list of comma separated zones parsed from the GCE_ZONE environment variable. If provided, this will be used to filter the results of the grouped_instances call'
def parse_env_zones(self):
import csv reader = csv.reader([os.environ.get('GCE_ZONE', '')], skipinitialspace=True) zones = [r for r in reader] return [z for z in zones[0]]
'Command line argument processing'
def parse_cli_args(self):
parser = argparse.ArgumentParser(description='Produce an Ansible Inventory file based on GCE') parser.add_argument('--list', action='store_true', default=True, help='List instances (default: True)') parser.add_argument('--host', action='store', help='Get all information ...
'Loads inventory from JSON on disk.'
def load_inventory_from_cache(self):
try: self.inventory = self.cache.get_all_data_from_cache() hosts = self.inventory['_meta']['hostvars'] except Exception as e: print ('Invalid inventory file %s. Please rebuild with -refresh-cache option.' % self.cache.cache_path_cache) raise
'Do API calls and save data in cache.'
def do_api_calls_update_cache(self):
zones = self.parse_env_zones() data = self.group_instances(zones) self.cache.write_to_cache(data) self.inventory = data
'Group all instances'
def group_instances(self, zones=None):
groups = {} meta = {} meta['hostvars'] = {} for node in self.list_nodes(): if (self.instance_states and (not (node.extra['status'] in self.instance_states))): continue name = node.name meta['hostvars'][name] = self.node_to_dict(node) zone = node.extra['zone']....
'Converts a dict to a JSON object and dumps it as a formatted string'
def json_format_dict(self, data, pretty=False):
if pretty: return json.dumps(data, sort_keys=True, indent=2) else: return json.dumps(data)
'Main execution path'
def __init__(self):
self.inventory = self._empty_inventory() self.index = {} self.boto_profile = None self.credentials = {} self.parse_cli_args() self.read_settings() if self.boto_profile: if (not hasattr(boto.ec2.EC2Connection, 'profile_name')): self.fail_with_error('boto version must...
'Determines if the cache files have expired, or if it is still valid'
def is_cache_valid(self):
if os.path.isfile(self.cache_path_cache): mod_time = os.path.getmtime(self.cache_path_cache) current_time = time() if ((mod_time + self.cache_max_age) > current_time): if os.path.isfile(self.cache_path_index): return True return False
'Reads the settings from the ec2.ini file'
def read_settings(self):
if six.PY3: config = configparser.ConfigParser() else: config = configparser.SafeConfigParser() ec2_default_ini_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ec2.ini') ec2_ini_path = os.path.expanduser(os.path.expandvars(os.environ.get('EC2_INI_PATH', ec2_default_ini_...
'Command line argument processing'
def parse_cli_args(self):
parser = argparse.ArgumentParser(description='Produce an Ansible Inventory file based on EC2') parser.add_argument('--list', action='store_true', default=True, help='List instances (default: True)') parser.add_argument('--host', action='store', help='Get all the variab...
'Do API calls to each region, and save data in cache files'
def do_api_calls_update_cache(self):
if self.route53_enabled: self.get_route53_records() for region in self.regions: self.get_instances_by_region(region) if self.rds_enabled: self.get_rds_instances_by_region(region) if self.elasticache_enabled: self.get_elasticache_clusters_by_region(region) ...
'create connection to api server'
def connect(self, region):
if self.eucalyptus: conn = boto.connect_euca(host=self.eucalyptus_host, **self.credentials) conn.APIVersion = '2010-08-31' else: conn = self.connect_to_aws(ec2, region) return conn
'monkey patch for boto issue boto/boto#2100'
def boto_fix_security_token_in_profile(self, connect_args):
profile = ('profile ' + self.boto_profile) if boto.config.has_option(profile, 'aws_security_token'): connect_args['security_token'] = boto.config.get(profile, 'aws_security_token') return connect_args
'Makes an AWS EC2 API call to the list of instances in a particular region'
def get_instances_by_region(self, region):
try: conn = self.connect(region) reservations = [] if self.ec2_instance_filters: for (filter_key, filter_values) in self.ec2_instance_filters.items(): reservations.extend(conn.get_all_instances(filters={filter_key: filter_values})) else: reserv...
'Makes an AWS API call to the list of RDS instances in a particular region'
def get_rds_instances_by_region(self, region):
try: conn = self.connect_to_aws(rds, region) if conn: marker = None while True: instances = conn.get_all_dbinstances(marker=marker) marker = instances.marker for instance in instances: self.add_rds_instance(i...
'Makes an AWS API call to the list of ElastiCache clusters (with nodes\' info) in a particular region.'
def get_elasticache_clusters_by_region(self, region):
try: conn = self.connect_to_aws(elasticache, region) if conn: response = conn.describe_cache_clusters(None, None, None, True) except boto.exception.BotoServerError as e: error = e.reason if (e.error_code == 'AuthFailure'): error = self.get_auth_error_messa...
'Makes an AWS API call to the list of ElastiCache replication groups in a particular region.'
def get_elasticache_replication_groups_by_region(self, region):
try: conn = self.connect_to_aws(elasticache, region) if conn: response = conn.describe_replication_groups() except boto.exception.BotoServerError as e: error = e.reason if (e.error_code == 'AuthFailure'): error = self.get_auth_error_message() if (n...
'create an informative error message if there is an issue authenticating'
def get_auth_error_message(self):
errors = ['Authentication error retrieving ec2 inventory.'] if (None in [os.environ.get('AWS_ACCESS_KEY_ID'), os.environ.get('AWS_SECRET_ACCESS_KEY')]): errors.append(' - No AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY environment vars found') else: errors.a...
'log an error to std err for ansible-playbook to consume and exit'
def fail_with_error(self, err_msg, err_operation=None):
if err_operation: err_msg = 'ERROR: "{err_msg}", while: {err_operation}'.format(err_msg=err_msg, err_operation=err_operation) sys.stderr.write(err_msg) sys.exit(1)
'Adds an instance to the inventory and index, as long as it is addressable'
def add_instance(self, instance, region):
if (instance.state not in self.ec2_instance_states): return if (self.destination_format and self.destination_format_tags): dest = self.destination_format.format(*[getattr(instance, 'tags').get(tag, '') for tag in self.destination_format_tags]) elif instance.subnet_id: dest = getattr(...
'Adds an RDS instance to the inventory and index, as long as it is addressable'
def add_rds_instance(self, instance, region):
if ((not self.all_rds_instances) and (instance.status != 'available')): return dest = instance.endpoint[0] if (not dest): return hostname = None if self.hostname_variable: if self.hostname_variable.startswith('tag_'): hostname = instance.tags.get(self.hostname_var...
'Adds an ElastiCache cluster to the inventory and index, as long as it\'s nodes are addressable'
def add_elasticache_cluster(self, cluster, region):
if ((not self.all_elasticache_clusters) and (cluster['CacheClusterStatus'] != 'available')): return if (('ConfigurationEndpoint' in cluster) and cluster['ConfigurationEndpoint']): dest = cluster['ConfigurationEndpoint']['Address'] is_redis = False else: dest = cluster['CacheN...
'Adds an ElastiCache node to the inventory and index, as long as it is addressable'
def add_elasticache_node(self, node, cluster, region):
if ((not self.all_elasticache_nodes) and (node['CacheNodeStatus'] != 'available')): return dest = node['Endpoint']['Address'] if (not dest): return node_id = self.to_safe(((cluster['CacheClusterId'] + '_') + node['CacheNodeId'])) self.index[dest] = [region, node_id] if self.group...
'Adds an ElastiCache replication group to the inventory and index'
def add_elasticache_replication_group(self, replication_group, region):
if ((not self.all_elasticache_replication_groups) and (replication_group['Status'] != 'available')): return dest = replication_group['NodeGroups'][0]['PrimaryEndpoint']['Address'] if (not dest): return self.index[dest] = [region, replication_group['ReplicationGroupId']] if self.group...
'Get and store the map of resource records to domain names that point to them.'
def get_route53_records(self):
r53_conn = route53.Route53Connection() all_zones = r53_conn.get_zones() route53_zones = [zone for zone in all_zones if (zone.name[:(-1)] not in self.route53_excluded_zones)] self.route53_records = {} for zone in route53_zones: rrsets = r53_conn.get_all_rrsets(zone.id) for record_set ...
'Check if an instance is referenced in the records we have from Route53. If it is, return the list of domain names pointing to said instance. If nothing points to it, return an empty list.'
def get_instance_route53_names(self, instance):
instance_attributes = ['public_dns_name', 'private_dns_name', 'ip_address', 'private_ip_address'] name_list = set() for attrib in instance_attributes: try: value = getattr(instance, attrib) except AttributeError: continue if (value in self.route53_records): ...
'Parses the dictionary returned by the API call into a flat list of parameters. This method should be used only when \'describe\' is used directly because Boto doesn\'t provide specific classes.'
def get_host_info_dict_from_describe_dict(self, describe_dict):
host_info = {} for key in describe_dict: value = describe_dict[key] key = self.to_safe(('ec2_' + self.uncammelize(key))) if ((key == 'ec2_configuration_endpoint') and value): host_info['ec2_configuration_endpoint_address'] = value['Address'] host_info['ec2_configu...
'Get variables about a specific host'
def get_host_info(self):
if (len(self.index) == 0): self.load_index_from_cache() if (not (self.args.host in self.index)): self.do_api_calls_update_cache() if (not (self.args.host in self.index)): return self.json_format_dict({}, True) (region, instance_id) = self.index[self.args.host] instanc...
'Push an element onto an array that may not have been defined in the dict'
def push(self, my_dict, key, element):
group_info = my_dict.setdefault(key, []) if isinstance(group_info, dict): host_list = group_info.setdefault('hosts', []) host_list.append(element) else: group_info.append(element)
'Push a group as a child of another group.'
def push_group(self, my_dict, key, element):
parent_group = my_dict.setdefault(key, {}) if (not isinstance(parent_group, dict)): parent_group = my_dict[key] = {'hosts': parent_group} child_groups = parent_group.setdefault('children', []) if (element not in child_groups): child_groups.append(element)
'Reads the inventory from the cache file and returns it as a JSON object'
def get_inventory_from_cache(self):
cache = open(self.cache_path_cache, 'r') json_inventory = cache.read() return json_inventory
'Reads the index from the cache file sets self.index'
def load_index_from_cache(self):
cache = open(self.cache_path_index, 'r') json_index = cache.read() self.index = json.loads(json_index)
'Writes data in JSON format to a file'
def write_to_cache(self, data, filename):
json_data = self.json_format_dict(data, True) cache = open(filename, 'w') cache.write(json_data) cache.close()
'Converts \'bad\' characters in a string to underscores so they can be used as Ansible groups'
def to_safe(self, word):
regex = '[^A-Za-z0-9\\_' if (not self.replace_dash_in_groups): regex += '\\-' return re.sub((regex + ']'), '_', word)
'Converts a dict to a JSON object and dumps it as a formatted string'
def json_format_dict(self, data, pretty=False):
if pretty: return json.dumps(data, sort_keys=True, indent=2) else: return json.dumps(data)
'This filter matches a device string /dev/sdX to /dev/xvdX It will then return the AWS volume ID'
@staticmethod def translate_volume_name(volumes, target_volume):
for vol in volumes: translated_name = vol['attachment_set']['device'].replace('/dev/sd', '/dev/xvd') if target_volume.startswith(translated_name): return vol['id'] return None
'returns a mapping of filters to methods'
def filters(self):
return {'translate_volume_name': self.translate_volume_name}
'Constructor'
def __init__(self, basedir=None, **kwargs):
self.basedir = basedir
'Main execution path'
def run(self, terms, variables, **kwargs):
ret = [] for term in terms: option_name = term.split()[0] cli_key = ('cli_' + option_name) if (('vars' in variables) and (cli_key in variables['vars'])): ret.append(variables['vars'][cli_key]) elif (option_name in os.environ): ret.append(os.environ[option_...
'initialize_options'
def initialize_options(self):
self.excludes = None self.config_file = None self.format = None
'finalize_options'
def finalize_options(self):
if isinstance(self.excludes, string_types): self.excludes = self.excludes.split(',') if (self.format is None): self.format = 'standard' assert (self.format in ['standard', 'parsable']), 'unknown format {0}.'.format(self.format) if (self.config_file is None): self.config_fil...
'run command'
def run(self):
if (self.excludes is not None): print('Excludes:\n{0}'.format(yaml.dump(self.excludes, default_flow_style=False))) config = YamlLintConfig(file=self.config_file) has_errors = False has_warnings = False if (self.format == 'parsable'): format_method = Format.parsable else: ...
'find all python files to test'
def find_all_modules(self):
exclude_dirs = ['.tox', 'utils', 'test', 'tests', 'git'] modules = [] for match in find_files(os.getcwd(), exclude_dirs, None, '\\.py$'): package = os.path.basename(match).replace('.py', '') modules.append(('openshift_ansible', package, match)) return modules
'override get_finalized_command to ensure we use our find_all_modules method'
def get_finalized_command(self, cmd):
if (cmd == 'build_py'): return self
'override behavior, since we don\'t need to build'
def with_project_on_sys_path(self, func, func_args, func_kwargs):
return func(*func_args, **func_kwargs)
'initialize_options'
def initialize_options(self):
pass
'finalize_options'
def finalize_options(self):
pass
'run command'
def run(self):
generate_files = find_files('roles', ['inventory', 'test', 'playbooks', 'utils'], None, 'generate.py$') if (len(generate_files) < 1): print('Did not find any code generation. Please verify module code generation.') raise SystemExit(1) errors = False for ...
'initialize_options'
def initialize_options(self):
pass
'finalize_options'
def finalize_options(self):
pass
'run command'
def run(self):
has_errors = False for yaml_file in find_files(os.path.join(os.getcwd(), 'playbooks', 'byo'), None, None, '\\.ya?ml$'): with open(yaml_file, 'r') as contents: for line in contents: if re.search('initialize_groups\\.yml', line): print(('-' * 60)) ...
'initialize_options'
def initialize_options(self):
pass
'initialize_options'
def finalize_options(self):
pass
'run command'
def run(self):
print('Unsupported command for openshift-ansible')
'Logs the start of each task'
def playbook_on_task_start(self, name, is_conditional):
if (self.current is not None): self.stats[self.current] = (time.time() - self.stats[self.current]) self.current = name self.stats[self.current] = time.time()
'Prints the timings'
def playbook_on_stats(self, stats):
if (self.current is not None): self.stats[self.current] = (time.time() - self.stats[self.current]) results = sorted(self.stats.items(), key=(lambda value: value[1]), reverse=True) results = results[:10] for (name, elapsed) in results: print '{0:-<70}{1:->9}'.format('{0} '.format(name)...
'Constructor, ensure standard self.*s are set'
def __init__(self):
self._play = None self._last_task_banner = None super(CallbackModule, self).__init__()
'Prints a header-looking line with stars taking up to 80 columns of width (3 columns, minimum) Overrides the upstream banner method so that display is called with log_only=True'
def banner(self, msg, color=None):
msg = msg.strip() star_len = (79 - len(msg)) if (star_len < 0): star_len = 3 stars = ('*' * star_len) self._display.display(('\n%s %s' % (msg, stars)), color=color, log_only=True)
'Imported from the upstream \'default\' callback'
def _print_task_banner(self, task):
args = '' if ((not task.no_log) and C.DISPLAY_ARGS_TO_STDOUT): args = ', '.join((('%s=%s' % a) for a in task.args.items())) args = (' %s' % args) self.banner((u'TASK [%s%s]' % (task.get_name().strip(), args))) if (self._display.verbosity >= 2): path = task.get_path() ...
'This is basically the start of it all'
def v2_playbook_on_start(self, playbook):
self.plays_count = len(playbook.get_plays()) self.plays_total_ran = 0 if (self._display.verbosity > 1): from os.path import basename self.banner(('PLAYBOOK: %s' % basename(playbook._file_name)))
'Each play calls this once before running any tasks We could print the number of tasks here as well by using `play.get_tasks()` but that is not accurate when a play includes a role. Only the tasks directly assigned to a play are exposed in the `play` object.'
def v2_playbook_on_play_start(self, play):
self.plays_total_ran += 1 print('') print(('Play %s/%s (%s)' % (self.plays_total_ran, self.plays_count, play.get_name()))) name = play.get_name().strip() if (not name): msg = 'PLAY' else: msg = ('PLAY [%s]' % name) self._play = play self.banner(msg)
'This prints out the task header. For example: TASK [openshift_facts : Ensure PyYaml is installed] ***... Rather than print out all that for every task, we print a dot character to indicate a task has been started.'
def v2_playbook_on_task_start(self, task, is_conditional):
sys.stdout.write('.') args = '' if ((not task.no_log) and C.DISPLAY_ARGS_TO_STDOUT): args = ', '.join((('%s=%s' % a) for a in task.args.items())) args = (' %s' % args) self.banner(('TASK [%s%s]' % (task.get_name().strip(), args))) if (self._display.verbosity >= 2): p...
'Print out task header for handlers Rather than print out a header for every handler, we print a dot character to indicate a handler task has been started.'
def v2_playbook_on_handler_task_start(self, task):
sys.stdout.write('.') self.banner(('RUNNING HANDLER [%s]' % task.get_name().strip()))
'Print out a task header for cleanup tasks Rather than print out a header for every handler, we print a dot character to indicate a handler task has been started.'
def v2_playbook_on_cleanup_task_start(self, task):
sys.stdout.write('.') self.banner(('CLEANUP TASK [%s]' % task.get_name().strip()))
'Print out paths to statically included files'
def v2_playbook_on_include(self, included_file):
msg = ('included: %s for %s' % (included_file._filename, ', '.join([h.name for h in included_file._hosts]))) self._display.display(msg, color=C.COLOR_SKIP, log_only=True)
'This prints out task results in a fancy format The only thing we change here is adding `log_only=True` to the .display() call'
def v2_runner_on_ok(self, result):
delegated_vars = result._result.get('_ansible_delegated_vars', None) self._clean_results(result._result, result._task.action) if (result._task.action in ('include', 'include_role')): return elif result._result.get('changed', False): if delegated_vars: msg = ('changed: [%s ...
'Print out task results for items you\'re iterating over'
def v2_runner_item_on_ok(self, result):
delegated_vars = result._result.get('_ansible_delegated_vars', None) if (result._task.action in ('include', 'include_role')): return elif result._result.get('changed', False): msg = 'changed' color = C.COLOR_CHANGED else: msg = 'ok' color = C.COLOR_OK if deleg...
'Print out task results when an item is skipped'
def v2_runner_item_on_skipped(self, result):
if C.DISPLAY_SKIPPED_HOSTS: msg = ('skipping: [%s] => (item=%s) ' % (result._host.get_name(), self._get_item(result._result))) if (((self._display.verbosity > 0) or ('_ansible_verbose_always' in result._result)) and ('_ansible_verbose_override' not in result._result)): msg +=...
'Print out task results when a task (or something else?) is skipped'
def v2_runner_on_skipped(self, result):
if C.DISPLAY_SKIPPED_HOSTS: if (result._task.loop and ('results' in result._result)): self._process_items(result) else: msg = ('skipping: [%s]' % result._host.get_name()) if (((self._display.verbosity > 0) or ('_ansible_verbose_always' in result._result)) and (...
'What happens when a task result is \'changed\' and the task has a \'notify\' list attached.'
def v2_playbook_on_notify(self, res, handler):
self._display.display('skipping: no hosts matched', color=C.COLOR_SKIP, log_only=True)
'I guess this is when an entire task has failed?'
def v2_runner_on_failed(self, result, ignore_errors=False):
if ((self._play.strategy == 'free') and (self._last_task_banner != result._task._uuid)): self._print_task_banner(result._task) delegated_vars = result._result.get('_ansible_delegated_vars', None) if ('exception' in result._result): if (self._display.verbosity < 3): error = result...
'When an item in a task fails.'
def v2_runner_item_on_failed(self, result):
delegated_vars = result._result.get('_ansible_delegated_vars', None) if ('exception' in result._result): if (self._display.verbosity < 3): error = result._result['exception'].strip().split('\n')[(-1)] msg = ('An exception occurred during task execution. To se...
'Print the final playbook run stats'
def v2_playbook_on_stats(self, stats):
self._display.display('', screen_only=True) self.banner('PLAY RECAP') hosts = sorted(stats.processed.keys()) for h in hosts: t = stats.summarize(h) self._display.display((u'%s : %s %s %s %s' % (hostcolor(h, t), colorize(u'ok', t['ok'], C.COLOR_OK), colorize(u'changed', ...
'Return the text to output for a result.'
def _dump_results(self, result):
result['_ansible_verbose_always'] = True save = {} for key in ['stdout', 'stdout_lines', 'stderr', 'stderr_lines', 'msg']: if (key in result): save[key] = result.pop(key) output = BASECLASS._dump_results(self, result) for key in ['stdout', 'stderr', 'msg']: if ((key in sa...
'Version verification is performed in __init__ to catch the requirement early in the execution of Ansible and fail gracefully'
def __init__(self):
super(CallbackModule, self).__init__() if (not version_requirement(__version__)): display(('FATAL: Current Ansible version (%s) is not supported. %s' % (__version__, DESCRIPTION)), color='red') sys.exit(1)
'Generate facts Args: local_facts (dict): local_facts for overriding generated defaults additive_facts_to_overwrite (list): additive facts to overwrite in jinja \'.\' notation ex: [\'master.named_certificates\'] openshift_env (dict): openshift_env facts for overriding generated defaults protected_facts_to_overwrite (li...
def generate_facts(self, local_facts, additive_facts_to_overwrite, openshift_env, openshift_env_structures, protected_facts_to_overwrite):
local_facts = self.init_local_facts(local_facts, additive_facts_to_overwrite, openshift_env, openshift_env_structures, protected_facts_to_overwrite) roles = local_facts.keys() if (('common' in local_facts) and ('deployment_type' in local_facts['common'])): deployment_type = local_facts['common']['de...
'Get default fact values Args: roles (list): list of roles for this host Returns: dict: The generated default facts'
def get_defaults(self, roles, deployment_type, deployment_subtype):
defaults = {} ip_addr = self.system_facts['ansible_default_ipv4']['address'] (exit_code, output, _) = module.run_command(['hostname', '-f']) hostname_f = (output.strip() if (exit_code == 0) else '') hostname_values = [hostname_f, self.system_facts['ansible_nodename'], self.system_facts['ansible_fqdn...
'Guess the host provider Returns: dict: The generated default facts for the detected provider'
def guess_host_provider(self):
product_name = self.system_facts['ansible_product_name'] product_version = self.system_facts['ansible_product_version'] virt_type = self.system_facts['ansible_virtualization_type'] virt_role = self.system_facts['ansible_virtualization_role'] bios_vendor = self.system_facts['ansible_system_vendor'] ...
'Initialize the provider facts Returns: dict: The normalized provider facts'
def init_provider_facts(self):
provider_info = self.guess_host_provider() provider_facts = normalize_provider_facts(provider_info.get('name'), provider_info.get('metadata')) return provider_facts
'Split openshift_env facts based on openshift_env structures. Args: openshift_env_fact (string): the openshift_env fact to split ex: \'openshift_cloudprovider_openstack_auth_url\' openshift_env_structures (list): a list of structures to determine fact keys ex: [\'openshift.cloudprovider.openstack.*\'] Returns: list: a ...
@staticmethod def split_openshift_env_fact_keys(openshift_env_fact, openshift_env_structures):
fact_keys = openshift_env_fact.split('_') matching_structure = None if (openshift_env_structures is not None): for structure in openshift_env_structures: if re.match(structure, openshift_env_fact): matching_structure = structure if (matching_structure is None): ...
'Initialize the local facts Args: facts (dict): local facts to set additive_facts_to_overwrite (list): additive facts to overwrite in jinja \'.\' notation ex: [\'master.named_certificates\'] openshift_env (dict): openshift env facts to set protected_facts_to_overwrite (list): protected facts to overwrite in jinja \'.\'...
def init_local_facts(self, facts=None, additive_facts_to_overwrite=None, openshift_env=None, openshift_env_structures=None, protected_facts_to_overwrite=None):
changed = False facts_to_set = dict() if (facts is not None): facts_to_set[self.role] = facts if ((openshift_env != {}) and (openshift_env is not None)): for (fact, value) in iteritems(openshift_env): oo_env_facts = dict() current_level = oo_env_facts ...
'Remove empty facts Args: facts (dict): facts to clean'
def remove_empty_facts(self, facts=None):
facts_to_remove = [] for (fact, value) in iteritems(facts): if isinstance(facts[fact], dict): facts[fact] = self.remove_empty_facts(facts[fact]) elif ((value == '') or (value == ['']) or (value is None)): facts_to_remove.append(fact) for fact in facts_to_remove: ...
'Validate local facts Args: facts (dict): local facts to validate'
def validate_local_facts(self, facts=None):
invalid_facts = dict() invalid_facts = self.validate_master_facts(facts, invalid_facts) if invalid_facts: msg = 'Invalid facts detected:\n' for key in invalid_facts.keys(): msg += '{0}: {1}\n'.format(key, invalid_facts[key]) module.fail_json(msg=msg, changed=self...
'Validate master facts Args: facts (dict): local facts to validate invalid_facts (dict): collected invalid_facts Returns: dict: Invalid facts'
@staticmethod def validate_master_facts(facts, invalid_facts):
if ('master' in facts): if ('session_auth_secrets' in facts['master']): session_auth_secrets = facts['master']['session_auth_secrets'] if (not issubclass(type(session_auth_secrets), list)): invalid_facts['session_auth_secrets'] = 'Expects session_auth_secrets is...
'validates a list of idps'
@staticmethod def validate_idp_list(idp_list, openshift_version, deployment_type):
login_providers = [x.name for x in idp_list if x.login] multiple_logins_unsupported = False if (len(login_providers) > 1): if (deployment_type in ['enterprise', 'online', 'atomic-enterprise', 'openshift-enterprise']): if (LooseVersion(openshift_version) < LooseVersion('3.2')): ...
'validate an instance of this idp class'
def validate(self):
pass
'get a default value for a given key'
@staticmethod def get_default(key):
if (key == 'mappingMethod'): return 'claim' else: return None