openshift_facts.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. # vim: expandtab:tabstop=4:shiftwidth=4
  4. # disable pylint checks
  5. # temporarily disabled until items can be addressed:
  6. # fixme - until all TODO comments have been addressed
  7. # pylint:disable=fixme
  8. """Ansible module for retrieving and setting openshift related facts"""
  9. DOCUMENTATION = '''
  10. ---
  11. module: openshift_facts
  12. short_description: OpenShift Facts
  13. author: Jason DeTiberus
  14. requirements: [ ]
  15. '''
  16. EXAMPLES = '''
  17. '''
  18. import ConfigParser
  19. import copy
  20. def hostname_valid(hostname):
  21. """ Test if specified hostname should be considered valid
  22. Args:
  23. hostname (str): hostname to test
  24. Returns:
  25. bool: True if valid, otherwise False
  26. """
  27. if (not hostname or
  28. hostname.startswith('localhost') or
  29. hostname.endswith('localdomain') or
  30. len(hostname.split('.')) < 2):
  31. return False
  32. return True
  33. def choose_hostname(hostnames=None, fallback=''):
  34. """ Choose a hostname from the provided hostnames
  35. Given a list of hostnames and a fallback value, choose a hostname to
  36. use. This function will prefer fqdns if they exist (excluding any that
  37. begin with localhost or end with localdomain) over ip addresses.
  38. Args:
  39. hostnames (list): list of hostnames
  40. fallback (str): default value to set if hostnames does not contain
  41. a valid hostname
  42. Returns:
  43. str: chosen hostname
  44. """
  45. hostname = fallback
  46. if hostnames is None:
  47. return hostname
  48. ip_regex = r'\A\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\Z'
  49. ips = [i for i in hostnames
  50. if (i is not None and isinstance(i, basestring)
  51. and re.match(ip_regex, i))]
  52. hosts = [i for i in hostnames
  53. if i is not None and i != '' and i not in ips]
  54. for host_list in (hosts, ips):
  55. for host in host_list:
  56. if hostname_valid(host):
  57. return host
  58. return hostname
  59. def query_metadata(metadata_url, headers=None, expect_json=False):
  60. """ Return metadata from the provided metadata_url
  61. Args:
  62. metadata_url (str): metadata url
  63. headers (dict): headers to set for metadata request
  64. expect_json (bool): does the metadata_url return json
  65. Returns:
  66. dict or list: metadata request result
  67. """
  68. result, info = fetch_url(module, metadata_url, headers=headers)
  69. if info['status'] != 200:
  70. raise OpenShiftFactsMetadataUnavailableError("Metadata unavailable")
  71. if expect_json:
  72. return module.from_json(result.read())
  73. else:
  74. return [line.strip() for line in result.readlines()]
  75. def walk_metadata(metadata_url, headers=None, expect_json=False):
  76. """ Walk the metadata tree and return a dictionary of the entire tree
  77. Args:
  78. metadata_url (str): metadata url
  79. headers (dict): headers to set for metadata request
  80. expect_json (bool): does the metadata_url return json
  81. Returns:
  82. dict: the result of walking the metadata tree
  83. """
  84. metadata = dict()
  85. for line in query_metadata(metadata_url, headers, expect_json):
  86. if line.endswith('/') and not line == 'public-keys/':
  87. key = line[:-1]
  88. metadata[key] = walk_metadata(metadata_url + line,
  89. headers, expect_json)
  90. else:
  91. results = query_metadata(metadata_url + line, headers,
  92. expect_json)
  93. if len(results) == 1:
  94. # disable pylint maybe-no-member because overloaded use of
  95. # the module name causes pylint to not detect that results
  96. # is an array or hash
  97. # pylint: disable=maybe-no-member
  98. metadata[line] = results.pop()
  99. else:
  100. metadata[line] = results
  101. return metadata
  102. def get_provider_metadata(metadata_url, supports_recursive=False,
  103. headers=None, expect_json=False):
  104. """ Retrieve the provider metadata
  105. Args:
  106. metadata_url (str): metadata url
  107. supports_recursive (bool): does the provider metadata api support
  108. recursion
  109. headers (dict): headers to set for metadata request
  110. expect_json (bool): does the metadata_url return json
  111. Returns:
  112. dict: the provider metadata
  113. """
  114. try:
  115. if supports_recursive:
  116. metadata = query_metadata(metadata_url, headers,
  117. expect_json)
  118. else:
  119. metadata = walk_metadata(metadata_url, headers,
  120. expect_json)
  121. except OpenShiftFactsMetadataUnavailableError:
  122. metadata = None
  123. return metadata
  124. def normalize_gce_facts(metadata, facts):
  125. """ Normalize gce facts
  126. Args:
  127. metadata (dict): provider metadata
  128. facts (dict): facts to update
  129. Returns:
  130. dict: the result of adding the normalized metadata to the provided
  131. facts dict
  132. """
  133. for interface in metadata['instance']['networkInterfaces']:
  134. int_info = dict(ips=[interface['ip']], network_type='gce')
  135. int_info['public_ips'] = [ac['externalIp'] for ac
  136. in interface['accessConfigs']]
  137. int_info['public_ips'].extend(interface['forwardedIps'])
  138. _, _, network_id = interface['network'].rpartition('/')
  139. int_info['network_id'] = network_id
  140. facts['network']['interfaces'].append(int_info)
  141. _, _, zone = metadata['instance']['zone'].rpartition('/')
  142. facts['zone'] = zone
  143. facts['external_id'] = metadata['instance']['id']
  144. # Default to no sdn for GCE deployments
  145. facts['use_openshift_sdn'] = False
  146. # GCE currently only supports a single interface
  147. facts['network']['ip'] = facts['network']['interfaces'][0]['ips'][0]
  148. pub_ip = facts['network']['interfaces'][0]['public_ips'][0]
  149. facts['network']['public_ip'] = pub_ip
  150. facts['network']['hostname'] = metadata['instance']['hostname']
  151. # TODO: attempt to resolve public_hostname
  152. facts['network']['public_hostname'] = facts['network']['public_ip']
  153. return facts
  154. def normalize_aws_facts(metadata, facts):
  155. """ Normalize aws facts
  156. Args:
  157. metadata (dict): provider metadata
  158. facts (dict): facts to update
  159. Returns:
  160. dict: the result of adding the normalized metadata to the provided
  161. facts dict
  162. """
  163. for interface in sorted(
  164. metadata['network']['interfaces']['macs'].values(),
  165. key=lambda x: x['device-number']
  166. ):
  167. int_info = dict()
  168. var_map = {'ips': 'local-ipv4s', 'public_ips': 'public-ipv4s'}
  169. for ips_var, int_var in var_map.iteritems():
  170. ips = interface.get(int_var)
  171. if isinstance(ips, basestring):
  172. int_info[ips_var] = [ips]
  173. else:
  174. int_info[ips_var] = ips
  175. if 'vpc-id' in interface:
  176. int_info['network_type'] = 'vpc'
  177. else:
  178. int_info['network_type'] = 'classic'
  179. if int_info['network_type'] == 'vpc':
  180. int_info['network_id'] = interface['subnet-id']
  181. else:
  182. int_info['network_id'] = None
  183. facts['network']['interfaces'].append(int_info)
  184. facts['zone'] = metadata['placement']['availability-zone']
  185. facts['external_id'] = metadata['instance-id']
  186. # TODO: actually attempt to determine default local and public ips
  187. # by using the ansible default ip fact and the ipv4-associations
  188. # from the ec2 metadata
  189. facts['network']['ip'] = metadata.get('local-ipv4')
  190. facts['network']['public_ip'] = metadata.get('public-ipv4')
  191. # TODO: verify that local hostname makes sense and is resolvable
  192. facts['network']['hostname'] = metadata.get('local-hostname')
  193. # TODO: verify that public hostname makes sense and is resolvable
  194. facts['network']['public_hostname'] = metadata.get('public-hostname')
  195. return facts
  196. def normalize_openstack_facts(metadata, facts):
  197. """ Normalize openstack facts
  198. Args:
  199. metadata (dict): provider metadata
  200. facts (dict): facts to update
  201. Returns:
  202. dict: the result of adding the normalized metadata to the provided
  203. facts dict
  204. """
  205. # openstack ec2 compat api does not support network interfaces and
  206. # the version tested on did not include the info in the openstack
  207. # metadata api, should be updated if neutron exposes this.
  208. facts['zone'] = metadata['availability_zone']
  209. facts['external_id'] = metadata['uuid']
  210. facts['network']['ip'] = metadata['ec2_compat']['local-ipv4']
  211. facts['network']['public_ip'] = metadata['ec2_compat']['public-ipv4']
  212. # TODO: verify local hostname makes sense and is resolvable
  213. facts['network']['hostname'] = metadata['hostname']
  214. # TODO: verify that public hostname makes sense and is resolvable
  215. pub_h = metadata['ec2_compat']['public-hostname']
  216. facts['network']['public_hostname'] = pub_h
  217. return facts
  218. def normalize_provider_facts(provider, metadata):
  219. """ Normalize provider facts
  220. Args:
  221. provider (str): host provider
  222. metadata (dict): provider metadata
  223. Returns:
  224. dict: the normalized provider facts
  225. """
  226. if provider is None or metadata is None:
  227. return {}
  228. # TODO: test for ipv6_enabled where possible (gce, aws do not support)
  229. # and configure ipv6 facts if available
  230. # TODO: add support for setting user_data if available
  231. facts = dict(name=provider, metadata=metadata,
  232. network=dict(interfaces=[], ipv6_enabled=False))
  233. if provider == 'gce':
  234. facts = normalize_gce_facts(metadata, facts)
  235. elif provider == 'ec2':
  236. facts = normalize_aws_facts(metadata, facts)
  237. elif provider == 'openstack':
  238. facts = normalize_openstack_facts(metadata, facts)
  239. return facts
  240. def set_url_facts_if_unset(facts):
  241. """ Set url facts if not already present in facts dict
  242. Args:
  243. facts (dict): existing facts
  244. Returns:
  245. dict: the facts dict updated with the generated url facts if they
  246. were not already present
  247. """
  248. if 'master' in facts:
  249. for (url_var, use_ssl, port, default) in [
  250. ('api_url',
  251. facts['master']['api_use_ssl'],
  252. facts['master']['api_port'],
  253. facts['common']['hostname']),
  254. ('public_api_url',
  255. facts['master']['api_use_ssl'],
  256. facts['master']['api_port'],
  257. facts['common']['public_hostname']),
  258. ('console_url',
  259. facts['master']['console_use_ssl'],
  260. facts['master']['console_port'],
  261. facts['common']['hostname']),
  262. ('public_console_url' 'console_use_ssl',
  263. facts['master']['console_use_ssl'],
  264. facts['master']['console_port'],
  265. facts['common']['public_hostname'])]:
  266. if url_var not in facts['master']:
  267. scheme = 'https' if use_ssl else 'http'
  268. netloc = default
  269. if ((scheme == 'https' and port != '443')
  270. or (scheme == 'http' and port != '80')):
  271. netloc = "%s:%s" % (netloc, port)
  272. facts['master'][url_var] = urlparse.urlunparse(
  273. (scheme, netloc, '', '', '', '')
  274. )
  275. return facts
  276. def get_current_config(facts):
  277. """ Get current openshift config
  278. Args:
  279. facts (dict): existing facts
  280. Returns:
  281. dict: the facts dict updated with the current openshift config
  282. """
  283. current_config = dict()
  284. roles = [role for role in facts if role not in ['common', 'provider']]
  285. for role in roles:
  286. if 'roles' in current_config:
  287. current_config['roles'].append(role)
  288. else:
  289. current_config['roles'] = [role]
  290. # TODO: parse the /etc/sysconfig/openshift-{master,node} config to
  291. # determine the location of files.
  292. # Query kubeconfig settings
  293. kubeconfig_dir = '/var/lib/openshift/openshift.local.certificates'
  294. if role == 'node':
  295. kubeconfig_dir = os.path.join(
  296. kubeconfig_dir, "node-%s" % facts['common']['hostname']
  297. )
  298. kubeconfig_path = os.path.join(kubeconfig_dir, '.kubeconfig')
  299. if (os.path.isfile('/usr/bin/openshift')
  300. and os.path.isfile(kubeconfig_path)):
  301. try:
  302. _, output, _ = module.run_command(
  303. ["/usr/bin/openshift", "ex", "config", "view", "-o",
  304. "json", "--kubeconfig=%s" % kubeconfig_path],
  305. check_rc=False
  306. )
  307. config = json.loads(output)
  308. cad = 'certificate-authority-data'
  309. try:
  310. for cluster in config['clusters']:
  311. config['clusters'][cluster][cad] = 'masked'
  312. except KeyError:
  313. pass
  314. try:
  315. for user in config['users']:
  316. config['users'][user][cad] = 'masked'
  317. config['users'][user]['client-key-data'] = 'masked'
  318. except KeyError:
  319. pass
  320. current_config['kubeconfig'] = config
  321. # override pylint broad-except warning, since we do not want
  322. # to bubble up any exceptions if openshift ex config view
  323. # fails
  324. # pylint: disable=broad-except
  325. except Exception:
  326. pass
  327. return current_config
  328. def apply_provider_facts(facts, provider_facts, roles):
  329. """ Apply provider facts to supplied facts dict
  330. Args:
  331. facts (dict): facts dict to update
  332. provider_facts (dict): provider facts to apply
  333. roles: host roles
  334. Returns:
  335. dict: the merged facts
  336. """
  337. if not provider_facts:
  338. return facts
  339. use_openshift_sdn = provider_facts.get('use_openshift_sdn')
  340. if isinstance(use_openshift_sdn, bool):
  341. facts['common']['use_openshift_sdn'] = use_openshift_sdn
  342. common_vars = [('hostname', 'ip'), ('public_hostname', 'public_ip')]
  343. for h_var, ip_var in common_vars:
  344. ip_value = provider_facts['network'].get(ip_var)
  345. if ip_value:
  346. facts['common'][ip_var] = ip_value
  347. facts['common'][h_var] = choose_hostname(
  348. [provider_facts['network'].get(h_var)],
  349. facts['common'][ip_var]
  350. )
  351. if 'node' in roles:
  352. ext_id = provider_facts.get('external_id')
  353. if ext_id:
  354. facts['node']['external_id'] = ext_id
  355. facts['provider'] = provider_facts
  356. return facts
  357. def merge_facts(orig, new):
  358. """ Recursively merge facts dicts
  359. Args:
  360. orig (dict): existing facts
  361. new (dict): facts to update
  362. Returns:
  363. dict: the merged facts
  364. """
  365. facts = dict()
  366. for key, value in orig.iteritems():
  367. if key in new:
  368. if isinstance(value, dict):
  369. facts[key] = merge_facts(value, new[key])
  370. else:
  371. facts[key] = copy.copy(new[key])
  372. else:
  373. facts[key] = copy.deepcopy(value)
  374. new_keys = set(new.keys()) - set(orig.keys())
  375. for key in new_keys:
  376. facts[key] = copy.deepcopy(new[key])
  377. return facts
  378. def save_local_facts(filename, facts):
  379. """ Save local facts
  380. Args:
  381. filename (str): local facts file
  382. facts (dict): facts to set
  383. """
  384. try:
  385. fact_dir = os.path.dirname(filename)
  386. if not os.path.exists(fact_dir):
  387. os.makedirs(fact_dir)
  388. with open(filename, 'w') as fact_file:
  389. fact_file.write(module.jsonify(facts))
  390. except (IOError, OSError) as ex:
  391. raise OpenShiftFactsFileWriteError(
  392. "Could not create fact file: %s, error: %s" % (filename, ex)
  393. )
  394. def get_local_facts_from_file(filename):
  395. """ Retrieve local facts from fact file
  396. Args:
  397. filename (str): local facts file
  398. Returns:
  399. dict: the retrieved facts
  400. """
  401. local_facts = dict()
  402. try:
  403. # Handle conversion of INI style facts file to json style
  404. ini_facts = ConfigParser.SafeConfigParser()
  405. ini_facts.read(filename)
  406. for section in ini_facts.sections():
  407. local_facts[section] = dict()
  408. for key, value in ini_facts.items(section):
  409. local_facts[section][key] = value
  410. except (ConfigParser.MissingSectionHeaderError,
  411. ConfigParser.ParsingError):
  412. try:
  413. with open(filename, 'r') as facts_file:
  414. local_facts = json.load(facts_file)
  415. except (ValueError, IOError):
  416. pass
  417. return local_facts
  418. class OpenShiftFactsUnsupportedRoleError(Exception):
  419. """OpenShift Facts Unsupported Role Error"""
  420. pass
  421. class OpenShiftFactsFileWriteError(Exception):
  422. """OpenShift Facts File Write Error"""
  423. pass
  424. class OpenShiftFactsMetadataUnavailableError(Exception):
  425. """OpenShift Facts Metadata Unavailable Error"""
  426. pass
  427. class OpenShiftFacts(object):
  428. """ OpenShift Facts
  429. Attributes:
  430. facts (dict): OpenShift facts for the host
  431. Args:
  432. role (str): role for setting local facts
  433. filename (str): local facts file to use
  434. local_facts (dict): local facts to set
  435. Raises:
  436. OpenShiftFactsUnsupportedRoleError:
  437. """
  438. known_roles = ['common', 'master', 'node', 'master_sdn', 'node_sdn', 'dns']
  439. def __init__(self, role, filename, local_facts):
  440. self.changed = False
  441. self.filename = filename
  442. if role not in self.known_roles:
  443. raise OpenShiftFactsUnsupportedRoleError(
  444. "Role %s is not supported by this module" % role
  445. )
  446. self.role = role
  447. self.system_facts = ansible_facts(module)
  448. self.facts = self.generate_facts(local_facts)
  449. def generate_facts(self, local_facts):
  450. """ Generate facts
  451. Args:
  452. local_facts (dict): local_facts for overriding generated
  453. defaults
  454. Returns:
  455. dict: The generated facts
  456. """
  457. local_facts = self.init_local_facts(local_facts)
  458. roles = local_facts.keys()
  459. defaults = self.get_defaults(roles)
  460. provider_facts = self.init_provider_facts()
  461. facts = apply_provider_facts(defaults, provider_facts, roles)
  462. facts = merge_facts(facts, local_facts)
  463. facts['current_config'] = get_current_config(facts)
  464. facts = set_url_facts_if_unset(facts)
  465. return dict(openshift=facts)
  466. def get_defaults(self, roles):
  467. """ Get default fact values
  468. Args:
  469. roles (list): list of roles for this host
  470. Returns:
  471. dict: The generated default facts
  472. """
  473. defaults = dict()
  474. common = dict(use_openshift_sdn=True)
  475. ip_addr = self.system_facts['default_ipv4']['address']
  476. common['ip'] = ip_addr
  477. common['public_ip'] = ip_addr
  478. exit_code, output, _ = module.run_command(['hostname', '-f'])
  479. hostname_f = output.strip() if exit_code == 0 else ''
  480. hostname_values = [hostname_f, self.system_facts['nodename'],
  481. self.system_facts['fqdn']]
  482. hostname = choose_hostname(hostname_values)
  483. common['hostname'] = hostname
  484. common['public_hostname'] = hostname
  485. defaults['common'] = common
  486. if 'master' in roles:
  487. master = dict(api_use_ssl=True, api_port='8443',
  488. console_use_ssl=True, console_path='/console',
  489. console_port='8443', etcd_use_ssl=False,
  490. etcd_port='4001', portal_net='172.30.17.0/24')
  491. defaults['master'] = master
  492. if 'node' in roles:
  493. node = dict(external_id=common['hostname'], pod_cidr='',
  494. labels={}, annotations={})
  495. node['resources_cpu'] = self.system_facts['processor_cores']
  496. node['resources_memory'] = int(
  497. int(self.system_facts['memtotal_mb']) * 1024 * 1024 * 0.75
  498. )
  499. defaults['node'] = node
  500. return defaults
  501. def guess_host_provider(self):
  502. """ Guess the host provider
  503. Returns:
  504. dict: The generated default facts for the detected provider
  505. """
  506. # TODO: cloud provider facts should probably be submitted upstream
  507. product_name = self.system_facts['product_name']
  508. product_version = self.system_facts['product_version']
  509. virt_type = self.system_facts['virtualization_type']
  510. virt_role = self.system_facts['virtualization_role']
  511. provider = None
  512. metadata = None
  513. # TODO: this is not exposed through module_utils/facts.py in ansible,
  514. # need to create PR for ansible to expose it
  515. bios_vendor = get_file_content(
  516. '/sys/devices/virtual/dmi/id/bios_vendor'
  517. )
  518. if bios_vendor == 'Google':
  519. provider = 'gce'
  520. metadata_url = ('http://metadata.google.internal/'
  521. 'computeMetadata/v1/?recursive=true')
  522. headers = {'Metadata-Flavor': 'Google'}
  523. metadata = get_provider_metadata(metadata_url, True, headers,
  524. True)
  525. # Filter sshKeys and serviceAccounts from gce metadata
  526. if metadata:
  527. metadata['project']['attributes'].pop('sshKeys', None)
  528. metadata['instance'].pop('serviceAccounts', None)
  529. elif (virt_type == 'xen' and virt_role == 'guest'
  530. and re.match(r'.*\.amazon$', product_version)):
  531. provider = 'ec2'
  532. metadata_url = 'http://169.254.169.254/latest/meta-data/'
  533. metadata = get_provider_metadata(metadata_url)
  534. elif re.search(r'OpenStack', product_name):
  535. provider = 'openstack'
  536. metadata_url = ('http://169.254.169.254/openstack/latest/'
  537. 'meta_data.json')
  538. metadata = get_provider_metadata(metadata_url, True, None,
  539. True)
  540. if metadata:
  541. ec2_compat_url = 'http://169.254.169.254/latest/meta-data/'
  542. metadata['ec2_compat'] = get_provider_metadata(
  543. ec2_compat_url
  544. )
  545. # disable pylint maybe-no-member because overloaded use of
  546. # the module name causes pylint to not detect that results
  547. # is an array or hash
  548. # pylint: disable=maybe-no-member
  549. # Filter public_keys and random_seed from openstack metadata
  550. metadata.pop('public_keys', None)
  551. metadata.pop('random_seed', None)
  552. if not metadata['ec2_compat']:
  553. metadata = None
  554. return dict(name=provider, metadata=metadata)
  555. def init_provider_facts(self):
  556. """ Initialize the provider facts
  557. Returns:
  558. dict: The normalized provider facts
  559. """
  560. provider_info = self.guess_host_provider()
  561. provider_facts = normalize_provider_facts(
  562. provider_info.get('name'),
  563. provider_info.get('metadata')
  564. )
  565. return provider_facts
  566. def init_local_facts(self, facts=None):
  567. """ Initialize the provider facts
  568. Args:
  569. facts (dict): local facts to set
  570. Returns:
  571. dict: The result of merging the provided facts with existing
  572. local facts
  573. """
  574. changed = False
  575. facts_to_set = {self.role: dict()}
  576. if facts is not None:
  577. facts_to_set[self.role] = facts
  578. local_facts = get_local_facts_from_file(self.filename)
  579. for arg in ['labels', 'annotations']:
  580. if arg in facts_to_set and isinstance(facts_to_set[arg],
  581. basestring):
  582. facts_to_set[arg] = module.from_json(facts_to_set[arg])
  583. new_local_facts = merge_facts(local_facts, facts_to_set)
  584. for facts in new_local_facts.values():
  585. keys_to_delete = []
  586. for fact, value in facts.iteritems():
  587. if value == "" or value is None:
  588. keys_to_delete.append(fact)
  589. for key in keys_to_delete:
  590. del facts[key]
  591. if new_local_facts != local_facts:
  592. changed = True
  593. if not module.check_mode:
  594. save_local_facts(self.filename, new_local_facts)
  595. self.changed = changed
  596. return new_local_facts
  597. def main():
  598. """ main """
  599. # disabling pylint errors for global-variable-undefined and invalid-name
  600. # for 'global module' usage, since it is required to use ansible_facts
  601. # pylint: disable=global-variable-undefined, invalid-name
  602. global module
  603. module = AnsibleModule(
  604. argument_spec=dict(
  605. role=dict(default='common', required=False,
  606. choices=OpenShiftFacts.known_roles),
  607. local_facts=dict(default=None, type='dict', required=False),
  608. ),
  609. supports_check_mode=True,
  610. add_file_common_args=True,
  611. )
  612. role = module.params['role']
  613. local_facts = module.params['local_facts']
  614. fact_file = '/etc/ansible/facts.d/openshift.fact'
  615. openshift_facts = OpenShiftFacts(role, fact_file, local_facts)
  616. file_params = module.params.copy()
  617. file_params['path'] = fact_file
  618. file_args = module.load_file_common_arguments(file_params)
  619. changed = module.set_fs_attributes_if_different(file_args,
  620. openshift_facts.changed)
  621. return module.exit_json(changed=changed,
  622. ansible_facts=openshift_facts.facts)
  623. # ignore pylint errors related to the module_utils import
  624. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import
  625. # import module snippets
  626. from ansible.module_utils.basic import *
  627. from ansible.module_utils.facts import *
  628. from ansible.module_utils.urls import *
  629. if __name__ == '__main__':
  630. main()