openshift_facts.py 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301
  1. #!/usr/bin/python
  2. # pylint: disable=too-many-lines
  3. # -*- coding: utf-8 -*-
  4. # Reason: Disable pylint too-many-lines because we don't want to split up this file.
  5. # Status: Permanently disabled to keep this module as self-contained as possible.
  6. """Ansible module for retrieving and setting openshift related facts"""
  7. # pylint: disable=no-name-in-module, import-error, wrong-import-order
  8. import copy
  9. import errno
  10. import json
  11. import re
  12. import os
  13. import yaml
  14. import struct
  15. import socket
  16. import ipaddress
  17. from distutils.util import strtobool
  18. from ansible.module_utils.six import text_type
  19. from ansible.module_utils.six import string_types
  20. # ignore pylint errors related to the module_utils import
  21. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import
  22. # import module snippets
  23. from ansible.module_utils.basic import * # noqa: F403
  24. from ansible.module_utils.facts import * # noqa: F403
  25. from ansible.module_utils.urls import * # noqa: F403
  26. from ansible.module_utils.six import iteritems, itervalues
  27. from ansible.module_utils.six.moves.urllib.parse import urlparse, urlunparse
  28. from ansible.module_utils._text import to_native
  29. DOCUMENTATION = '''
  30. ---
  31. module: openshift_facts
  32. short_description: Cluster Facts
  33. author: Jason DeTiberus
  34. requirements: [ ]
  35. '''
  36. EXAMPLES = '''
  37. '''
  38. def migrate_admission_plugin_facts(facts):
  39. """ Apply migrations for admission plugin facts """
  40. if 'master' in facts:
  41. if 'kube_admission_plugin_config' in facts['master']:
  42. if 'admission_plugin_config' not in facts['master']:
  43. facts['master']['admission_plugin_config'] = dict()
  44. # Merge existing kube_admission_plugin_config with admission_plugin_config.
  45. facts['master']['admission_plugin_config'] = merge_facts(facts['master']['admission_plugin_config'],
  46. facts['master']['kube_admission_plugin_config'],
  47. additive_facts_to_overwrite=[])
  48. # Remove kube_admission_plugin_config fact
  49. facts['master'].pop('kube_admission_plugin_config', None)
  50. return facts
  51. def migrate_local_facts(facts):
  52. """ Apply migrations of local facts """
  53. migrated_facts = copy.deepcopy(facts)
  54. migrated_facts = migrate_admission_plugin_facts(migrated_facts)
  55. return migrated_facts
  56. def first_ip(network):
  57. """ Return the first IPv4 address in network
  58. Args:
  59. network (str): network in CIDR format
  60. Returns:
  61. str: first IPv4 address
  62. """
  63. atoi = lambda addr: struct.unpack("!I", socket.inet_aton(addr))[0] # noqa: E731
  64. itoa = lambda addr: socket.inet_ntoa(struct.pack("!I", addr)) # noqa: E731
  65. (address, netmask) = network.split('/')
  66. netmask_i = (0xffffffff << (32 - atoi(netmask))) & 0xffffffff
  67. return itoa((atoi(address) & netmask_i) + 1)
  68. def hostname_valid(hostname):
  69. """ Test if specified hostname should be considered valid
  70. Args:
  71. hostname (str): hostname to test
  72. Returns:
  73. bool: True if valid, otherwise False
  74. """
  75. if (not hostname or
  76. hostname.startswith('localhost') or
  77. hostname.endswith('localdomain') or
  78. # OpenShift will not allow a node with more than 63 chars in name.
  79. len(hostname) > 63):
  80. return False
  81. return True
  82. def choose_hostname(hostnames=None, fallback=''):
  83. """ Choose a hostname from the provided hostnames
  84. Given a list of hostnames and a fallback value, choose a hostname to
  85. use. This function will prefer fqdns if they exist (excluding any that
  86. begin with localhost or end with localdomain) over ip addresses.
  87. Args:
  88. hostnames (list): list of hostnames
  89. fallback (str): default value to set if hostnames does not contain
  90. a valid hostname
  91. Returns:
  92. str: chosen hostname
  93. """
  94. hostname = fallback
  95. if hostnames is None:
  96. return hostname
  97. ip_regex = r'\A\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\Z'
  98. ips = [i for i in hostnames if i is not None and isinstance(i, string_types) and re.match(ip_regex, i)]
  99. hosts = [i for i in hostnames if i is not None and i != '' and i not in ips]
  100. for host_list in (hosts, ips):
  101. for host in host_list:
  102. if hostname_valid(host):
  103. return host
  104. return hostname
  105. def query_metadata(metadata_url, headers=None, expect_json=False):
  106. """ Return metadata from the provided metadata_url
  107. Args:
  108. metadata_url (str): metadata url
  109. headers (dict): headers to set for metadata request
  110. expect_json (bool): does the metadata_url return json
  111. Returns:
  112. dict or list: metadata request result
  113. """
  114. result, info = fetch_url(module, metadata_url, headers=headers) # noqa: F405
  115. if info['status'] != 200:
  116. raise OpenShiftFactsMetadataUnavailableError("Metadata unavailable")
  117. if expect_json:
  118. return module.from_json(to_native(result.read())) # noqa: F405
  119. else:
  120. return [to_native(line.strip()) for line in result.readlines()]
  121. def walk_metadata(metadata_url, headers=None, expect_json=False):
  122. """ Walk the metadata tree and return a dictionary of the entire tree
  123. Args:
  124. metadata_url (str): metadata url
  125. headers (dict): headers to set for metadata request
  126. expect_json (bool): does the metadata_url return json
  127. Returns:
  128. dict: the result of walking the metadata tree
  129. """
  130. metadata = dict()
  131. for line in query_metadata(metadata_url, headers, expect_json):
  132. if line.endswith('/') and not line == 'public-keys/':
  133. key = line[:-1]
  134. metadata[key] = walk_metadata(metadata_url + line,
  135. headers, expect_json)
  136. else:
  137. results = query_metadata(metadata_url + line, headers,
  138. expect_json)
  139. if len(results) == 1:
  140. # disable pylint maybe-no-member because overloaded use of
  141. # the module name causes pylint to not detect that results
  142. # is an array or hash
  143. # pylint: disable=maybe-no-member
  144. metadata[line] = results.pop()
  145. else:
  146. metadata[line] = results
  147. return metadata
  148. def get_provider_metadata(metadata_url, supports_recursive=False,
  149. headers=None, expect_json=False):
  150. """ Retrieve the provider metadata
  151. Args:
  152. metadata_url (str): metadata url
  153. supports_recursive (bool): does the provider metadata api support
  154. recursion
  155. headers (dict): headers to set for metadata request
  156. expect_json (bool): does the metadata_url return json
  157. Returns:
  158. dict: the provider metadata
  159. """
  160. try:
  161. if supports_recursive:
  162. metadata = query_metadata(metadata_url, headers,
  163. expect_json)
  164. else:
  165. metadata = walk_metadata(metadata_url, headers,
  166. expect_json)
  167. except OpenShiftFactsMetadataUnavailableError:
  168. metadata = None
  169. return metadata
  170. def normalize_gce_facts(metadata, facts):
  171. """ Normalize gce facts
  172. Args:
  173. metadata (dict): provider metadata
  174. facts (dict): facts to update
  175. Returns:
  176. dict: the result of adding the normalized metadata to the provided
  177. facts dict
  178. """
  179. for interface in metadata['instance']['networkInterfaces']:
  180. int_info = dict(ips=[interface['ip']], network_type='gce')
  181. int_info['public_ips'] = [ac['externalIp'] for ac
  182. in interface['accessConfigs']]
  183. int_info['public_ips'].extend(interface['forwardedIps'])
  184. _, _, network_id = interface['network'].rpartition('/')
  185. int_info['network_id'] = network_id
  186. facts['network']['interfaces'].append(int_info)
  187. _, _, zone = metadata['instance']['zone'].rpartition('/')
  188. facts['zone'] = zone
  189. # GCE currently only supports a single interface
  190. facts['network']['ip'] = facts['network']['interfaces'][0]['ips'][0]
  191. pub_ip = facts['network']['interfaces'][0]['public_ips'][0]
  192. facts['network']['public_ip'] = pub_ip
  193. # Split instance hostname from GCE metadata to use the short instance name
  194. facts['network']['hostname'] = metadata['instance']['hostname'].split('.')[0]
  195. # TODO: attempt to resolve public_hostname
  196. facts['network']['public_hostname'] = facts['network']['public_ip']
  197. return facts
  198. def normalize_aws_facts(metadata, facts):
  199. """ Normalize aws facts
  200. Args:
  201. metadata (dict): provider metadata
  202. facts (dict): facts to update
  203. Returns:
  204. dict: the result of adding the normalized metadata to the provided
  205. facts dict
  206. """
  207. for interface in sorted(
  208. metadata['network']['interfaces']['macs'].values(),
  209. key=lambda x: x['device-number']
  210. ):
  211. int_info = dict()
  212. var_map = {'ips': 'local-ipv4s', 'public_ips': 'public-ipv4s'}
  213. for ips_var, int_var in iteritems(var_map):
  214. ips = interface.get(int_var)
  215. if isinstance(ips, string_types):
  216. int_info[ips_var] = [ips]
  217. else:
  218. int_info[ips_var] = ips
  219. if 'vpc-id' in interface:
  220. int_info['network_type'] = 'vpc'
  221. else:
  222. int_info['network_type'] = 'classic'
  223. if int_info['network_type'] == 'vpc':
  224. int_info['network_id'] = interface['subnet-id']
  225. else:
  226. int_info['network_id'] = None
  227. facts['network']['interfaces'].append(int_info)
  228. facts['zone'] = metadata['placement']['availability-zone']
  229. # TODO: actually attempt to determine default local and public ips
  230. # by using the ansible default ip fact and the ipv4-associations
  231. # from the ec2 metadata
  232. facts['network']['ip'] = metadata.get('local-ipv4')
  233. facts['network']['public_ip'] = metadata.get('public-ipv4')
  234. # TODO: verify that local hostname makes sense and is resolvable
  235. facts['network']['hostname'] = metadata.get('local-hostname')
  236. # TODO: verify that public hostname makes sense and is resolvable
  237. facts['network']['public_hostname'] = metadata.get('public-hostname')
  238. return facts
  239. def normalize_openstack_facts(metadata, facts):
  240. """ Normalize openstack facts
  241. Args:
  242. metadata (dict): provider metadata
  243. facts (dict): facts to update
  244. Returns:
  245. dict: the result of adding the normalized metadata to the provided
  246. facts dict
  247. """
  248. # openstack ec2 compat api does not support network interfaces and
  249. # the version tested on did not include the info in the openstack
  250. # metadata api, should be updated if neutron exposes this.
  251. facts['zone'] = metadata['availability_zone']
  252. local_ipv4 = metadata['ec2_compat']['local-ipv4'].split(',')[0]
  253. facts['network']['ip'] = local_ipv4
  254. facts['network']['public_ip'] = metadata['ec2_compat']['public-ipv4']
  255. for f_var, h_var, ip_var in [('hostname', 'hostname', 'local-ipv4'),
  256. ('public_hostname', 'public-hostname', 'public-ipv4')]:
  257. try:
  258. if socket.gethostbyname(metadata['ec2_compat'][h_var]) == metadata['ec2_compat'][ip_var]:
  259. facts['network'][f_var] = metadata['ec2_compat'][h_var]
  260. else:
  261. facts['network'][f_var] = metadata['ec2_compat'][ip_var]
  262. except socket.gaierror:
  263. facts['network'][f_var] = metadata['ec2_compat'][ip_var]
  264. return facts
  265. def normalize_provider_facts(provider, metadata):
  266. """ Normalize provider facts
  267. Args:
  268. provider (str): host provider
  269. metadata (dict): provider metadata
  270. Returns:
  271. dict: the normalized provider facts
  272. """
  273. if provider is None or metadata is None:
  274. return {}
  275. # TODO: test for ipv6_enabled where possible (gce, aws do not support)
  276. # and configure ipv6 facts if available
  277. # TODO: add support for setting user_data if available
  278. facts = dict(name=provider, metadata=metadata,
  279. network=dict(interfaces=[], ipv6_enabled=False))
  280. if provider == 'gce':
  281. facts = normalize_gce_facts(metadata, facts)
  282. elif provider == 'aws':
  283. facts = normalize_aws_facts(metadata, facts)
  284. elif provider == 'openstack':
  285. facts = normalize_openstack_facts(metadata, facts)
  286. return facts
  287. def set_url_facts_if_unset(facts):
  288. """ Set url facts if not already present in facts dict
  289. Args:
  290. facts (dict): existing facts
  291. Returns:
  292. dict: the facts dict updated with the generated url facts if they
  293. were not already present
  294. """
  295. if 'master' in facts:
  296. hostname = facts['common']['hostname']
  297. cluster_hostname = facts['master'].get('cluster_hostname')
  298. cluster_public_hostname = facts['master'].get('cluster_public_hostname')
  299. public_hostname = facts['common']['public_hostname']
  300. api_hostname = cluster_hostname if cluster_hostname else hostname
  301. api_public_hostname = cluster_public_hostname if cluster_public_hostname else public_hostname
  302. console_path = facts['master']['console_path']
  303. use_ssl = dict(
  304. api=facts['master']['api_use_ssl'],
  305. public_api=facts['master']['api_use_ssl'],
  306. loopback_api=facts['master']['api_use_ssl'],
  307. console=facts['master']['console_use_ssl'],
  308. public_console=facts['master']['console_use_ssl'],
  309. )
  310. ports = dict(
  311. api=facts['master']['api_port'],
  312. public_api=facts['master']['api_port'],
  313. loopback_api=facts['master']['api_port'],
  314. console=facts['master']['console_port'],
  315. public_console=facts['master']['console_port'],
  316. )
  317. prefix_hosts = [('api', api_hostname),
  318. ('public_api', api_public_hostname),
  319. ('loopback_api', hostname)]
  320. for prefix, host in prefix_hosts:
  321. facts['master'].setdefault(prefix + '_url', format_url(use_ssl[prefix],
  322. host,
  323. ports[prefix]))
  324. r_lhn = "{0}:{1}".format(hostname, ports['api']).replace('.', '-')
  325. r_lhu = "system:openshift-master/{0}:{1}".format(api_hostname, ports['api']).replace('.', '-')
  326. facts['master'].setdefault('loopback_cluster_name', r_lhn)
  327. facts['master'].setdefault('loopback_context_name', "default/{0}/system:openshift-master".format(r_lhn))
  328. facts['master'].setdefault('loopback_user', r_lhu)
  329. prefix_hosts = [('console', api_hostname), ('public_console', api_public_hostname)]
  330. for prefix, host in prefix_hosts:
  331. facts['master'].setdefault(prefix + '_url', format_url(use_ssl[prefix],
  332. host,
  333. ports[prefix],
  334. console_path))
  335. return facts
  336. def set_aggregate_facts(facts):
  337. """ Set aggregate facts
  338. Args:
  339. facts (dict): existing facts
  340. Returns:
  341. dict: the facts dict updated with aggregated facts
  342. """
  343. all_hostnames = set()
  344. internal_hostnames = set()
  345. kube_svc_ip = first_ip(facts['common']['portal_net'])
  346. if 'common' in facts:
  347. all_hostnames.add(facts['common']['hostname'])
  348. all_hostnames.add(facts['common']['public_hostname'])
  349. all_hostnames.add(facts['common']['ip'])
  350. all_hostnames.add(facts['common']['public_ip'])
  351. facts['common']['kube_svc_ip'] = kube_svc_ip
  352. internal_hostnames.add(facts['common']['hostname'])
  353. internal_hostnames.add(facts['common']['ip'])
  354. cluster_domain = facts['common']['dns_domain']
  355. if 'master' in facts:
  356. if 'cluster_hostname' in facts['master']:
  357. all_hostnames.add(facts['master']['cluster_hostname'])
  358. if 'cluster_public_hostname' in facts['master']:
  359. all_hostnames.add(facts['master']['cluster_public_hostname'])
  360. svc_names = ['openshift', 'openshift.default', 'openshift.default.svc',
  361. 'openshift.default.svc.' + cluster_domain, 'kubernetes', 'kubernetes.default',
  362. 'kubernetes.default.svc', 'kubernetes.default.svc.' + cluster_domain]
  363. all_hostnames.update(svc_names)
  364. internal_hostnames.update(svc_names)
  365. all_hostnames.add(kube_svc_ip)
  366. internal_hostnames.add(kube_svc_ip)
  367. facts['common']['all_hostnames'] = list(all_hostnames)
  368. facts['common']['internal_hostnames'] = list(internal_hostnames)
  369. return facts
  370. def set_sdn_facts_if_unset(facts, system_facts):
  371. """ Set sdn facts if not already present in facts dict
  372. Args:
  373. facts (dict): existing facts
  374. system_facts (dict): ansible_facts
  375. Returns:
  376. dict: the facts dict updated with the generated sdn facts if they
  377. were not already present
  378. """
  379. if 'node' in facts and 'sdn_mtu' not in facts['node']:
  380. node_ip = facts['common']['ip']
  381. # default MTU if interface MTU cannot be detected
  382. facts['node']['sdn_mtu'] = '1450'
  383. for val in itervalues(system_facts):
  384. if isinstance(val, dict) and 'mtu' in val:
  385. mtu = val['mtu']
  386. if 'ipv4' in val and val['ipv4'].get('address') == node_ip:
  387. facts['node']['sdn_mtu'] = str(mtu - 50)
  388. return facts
  389. def set_nodename(facts):
  390. """ set nodename """
  391. if 'node' in facts and 'common' in facts:
  392. if 'cloudprovider' in facts and facts['cloudprovider']['kind'] == 'gce':
  393. facts['node']['nodename'] = facts['provider']['metadata']['instance']['hostname'].split('.')[0]
  394. # TODO: The openstack cloudprovider nodename setting was too opinionaed.
  395. # It needs to be generalized before it can be enabled again.
  396. # elif 'cloudprovider' in facts and facts['cloudprovider']['kind'] == 'openstack':
  397. # facts['node']['nodename'] = facts['provider']['metadata']['hostname'].replace('.novalocal', '')
  398. else:
  399. facts['node']['nodename'] = facts['common']['raw_hostname'].lower()
  400. return facts
  401. def make_allowed_registries(registry_list):
  402. """ turns a list of wildcard registries to allowedRegistriesForImport json setting """
  403. return {
  404. "allowedRegistriesForImport": [
  405. {'domainName': reg} if isinstance(reg, str) else reg for reg in registry_list
  406. ]
  407. }
  408. def set_allowed_registries(facts):
  409. """ override allowedRegistriesForImport in imagePolicyConfig """
  410. if 'master' in facts:
  411. image_policy = {}
  412. overriden = False
  413. if facts['master'].get('image_policy_config', None):
  414. image_policy = facts['master']['image_policy_config']
  415. overriden = True
  416. overrides = facts['master'].get('image_policy_allowed_registries_for_import', None)
  417. if overrides:
  418. image_policy = merge_facts(image_policy, make_allowed_registries(overrides), None)
  419. overriden = True
  420. if overriden:
  421. facts['master']['image_policy_config'] = image_policy
  422. return facts
  423. def format_url(use_ssl, hostname, port, path=''):
  424. """ Format url based on ssl flag, hostname, port and path
  425. Args:
  426. use_ssl (bool): is ssl enabled
  427. hostname (str): hostname
  428. port (str): port
  429. path (str): url path
  430. Returns:
  431. str: The generated url string
  432. """
  433. scheme = 'https' if use_ssl else 'http'
  434. netloc = hostname
  435. if (use_ssl and port != '443') or (not use_ssl and port != '80'):
  436. netloc += ":%s" % port
  437. try:
  438. url = urlparse.urlunparse((scheme, netloc, path, '', '', ''))
  439. except AttributeError:
  440. # pylint: disable=undefined-variable
  441. url = urlunparse((scheme, netloc, path, '', '', ''))
  442. return url
  443. def get_current_config(facts):
  444. """ Get current openshift config
  445. Args:
  446. facts (dict): existing facts
  447. Returns:
  448. dict: the facts dict updated with the current openshift config
  449. """
  450. current_config = dict()
  451. roles = [role for role in facts if role not in ['common', 'provider']]
  452. for role in roles:
  453. if 'roles' in current_config:
  454. current_config['roles'].append(role)
  455. else:
  456. current_config['roles'] = [role]
  457. # TODO: parse the /etc/sysconfig/openshift-{master,node} config to
  458. # determine the location of files.
  459. # TODO: I suspect this isn't working right now, but it doesn't prevent
  460. # anything from working properly as far as I can tell, perhaps because
  461. # we override the kubeconfig path everywhere we use it?
  462. # Query kubeconfig settings
  463. kubeconfig_dir = '/var/lib/origin/openshift.local.certificates'
  464. if role == 'node':
  465. kubeconfig_dir = os.path.join(
  466. kubeconfig_dir, "node-%s" % facts['common']['hostname']
  467. )
  468. kubeconfig_path = os.path.join(kubeconfig_dir, '.kubeconfig')
  469. if os.path.isfile('/usr/bin/openshift') and os.path.isfile(kubeconfig_path):
  470. try:
  471. _, output, _ = module.run_command( # noqa: F405
  472. ["/usr/bin/openshift", "ex", "config", "view", "-o",
  473. "json", "--kubeconfig=%s" % kubeconfig_path],
  474. check_rc=False
  475. )
  476. config = json.loads(output)
  477. cad = 'certificate-authority-data'
  478. try:
  479. for cluster in config['clusters']:
  480. config['clusters'][cluster][cad] = 'masked'
  481. except KeyError:
  482. pass
  483. try:
  484. for user in config['users']:
  485. config['users'][user][cad] = 'masked'
  486. config['users'][user]['client-key-data'] = 'masked'
  487. except KeyError:
  488. pass
  489. current_config['kubeconfig'] = config
  490. # override pylint broad-except warning, since we do not want
  491. # to bubble up any exceptions if oc config view
  492. # fails
  493. # pylint: disable=broad-except
  494. except Exception:
  495. pass
  496. return current_config
  497. def build_controller_args(facts):
  498. """ Build master controller_args """
  499. cloud_cfg_path = os.path.join(facts['common']['config_base'],
  500. 'cloudprovider')
  501. if 'master' in facts:
  502. controller_args = {
  503. 'pv-recycler-pod-template-filepath-nfs': ['/etc/origin/master/recycler_pod.yaml'],
  504. 'pv-recycler-pod-template-filepath-hostpath': ['/etc/origin/master/recycler_pod.yaml']
  505. }
  506. if 'cloudprovider' in facts:
  507. if 'kind' in facts['cloudprovider']:
  508. if facts['cloudprovider']['kind'] == 'aws':
  509. controller_args['cloud-provider'] = ['aws']
  510. controller_args['cloud-config'] = [cloud_cfg_path + '/aws.conf']
  511. controller_args['disable-attach-detach-reconcile-sync'] = ['true']
  512. if facts['cloudprovider']['kind'] == 'azure':
  513. controller_args['cloud-provider'] = ['azure']
  514. controller_args['cloud-config'] = [cloud_cfg_path + '/azure.conf']
  515. if facts['cloudprovider']['kind'] == 'openstack':
  516. controller_args['cloud-provider'] = ['openstack']
  517. controller_args['cloud-config'] = [cloud_cfg_path + '/openstack.conf']
  518. if facts['cloudprovider']['kind'] == 'gce':
  519. controller_args['cloud-provider'] = ['gce']
  520. controller_args['cloud-config'] = [cloud_cfg_path + '/gce.conf']
  521. if controller_args != {}:
  522. facts = merge_facts({'master': {'controller_args': controller_args}}, facts, [])
  523. return facts
  524. def build_api_server_args(facts):
  525. """ Build master api_server_args """
  526. cloud_cfg_path = os.path.join(facts['common']['config_base'],
  527. 'cloudprovider')
  528. if 'master' in facts:
  529. api_server_args = {}
  530. if 'cloudprovider' in facts:
  531. if 'kind' in facts['cloudprovider']:
  532. if facts['cloudprovider']['kind'] == 'aws':
  533. api_server_args['cloud-provider'] = ['aws']
  534. api_server_args['cloud-config'] = [cloud_cfg_path + '/aws.conf']
  535. if facts['cloudprovider']['kind'] == 'azure':
  536. api_server_args['cloud-provider'] = ['azure']
  537. api_server_args['cloud-config'] = [cloud_cfg_path + '/azure.conf']
  538. if facts['cloudprovider']['kind'] == 'openstack':
  539. api_server_args['cloud-provider'] = ['openstack']
  540. api_server_args['cloud-config'] = [cloud_cfg_path + '/openstack.conf']
  541. if facts['cloudprovider']['kind'] == 'gce':
  542. api_server_args['cloud-provider'] = ['gce']
  543. api_server_args['cloud-config'] = [cloud_cfg_path + '/gce.conf']
  544. if api_server_args != {}:
  545. facts = merge_facts({'master': {'api_server_args': api_server_args}}, facts, [])
  546. return facts
  547. def apply_provider_facts(facts, provider_facts):
  548. """ Apply provider facts to supplied facts dict
  549. Args:
  550. facts (dict): facts dict to update
  551. provider_facts (dict): provider facts to apply
  552. roles: host roles
  553. Returns:
  554. dict: the merged facts
  555. """
  556. if not provider_facts:
  557. return facts
  558. common_vars = [('hostname', 'ip'), ('public_hostname', 'public_ip')]
  559. for h_var, ip_var in common_vars:
  560. ip_value = provider_facts['network'].get(ip_var)
  561. if ip_value:
  562. facts['common'][ip_var] = ip_value
  563. facts['common'][h_var] = choose_hostname(
  564. [provider_facts['network'].get(h_var)],
  565. facts['common'][h_var]
  566. )
  567. facts['provider'] = provider_facts
  568. return facts
  569. # Disabling pylint too many branches. This function needs refactored
  570. # but is a very core part of openshift_facts.
  571. # pylint: disable=too-many-branches, too-many-nested-blocks
  572. def merge_facts(orig, new, additive_facts_to_overwrite):
  573. """ Recursively merge facts dicts
  574. Args:
  575. orig (dict): existing facts
  576. new (dict): facts to update
  577. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  578. '.' notation ex: ['master.named_certificates']
  579. Returns:
  580. dict: the merged facts
  581. """
  582. additive_facts = ['named_certificates']
  583. # Facts we do not ever want to merge. These originate in inventory variables
  584. # and contain JSON dicts. We don't ever want to trigger a merge
  585. # here, just completely overwrite with the new if they are present there.
  586. inventory_json_facts = ['admission_plugin_config',
  587. 'kube_admission_plugin_config',
  588. 'image_policy_config',
  589. "builddefaults",
  590. "buildoverrides"]
  591. facts = dict()
  592. for key, value in iteritems(orig):
  593. # Key exists in both old and new facts.
  594. if key in new:
  595. if key in inventory_json_facts:
  596. # Watchout for JSON facts that sometimes load as strings.
  597. # (can happen if the JSON contains a boolean)
  598. if isinstance(new[key], string_types):
  599. facts[key] = yaml.safe_load(new[key])
  600. else:
  601. facts[key] = copy.deepcopy(new[key])
  602. # Continue to recurse if old and new fact is a dictionary.
  603. elif isinstance(value, dict) and isinstance(new[key], dict):
  604. # Collect the subset of additive facts to overwrite if
  605. # key matches. These will be passed to the subsequent
  606. # merge_facts call.
  607. relevant_additive_facts = []
  608. for item in additive_facts_to_overwrite:
  609. if '.' in item and item.startswith(key + '.'):
  610. relevant_additive_facts.append(item)
  611. facts[key] = merge_facts(value, new[key], relevant_additive_facts)
  612. # Key matches an additive fact and we are not overwriting
  613. # it so we will append the new value to the existing value.
  614. elif key in additive_facts and key not in [x.split('.')[-1] for x in additive_facts_to_overwrite]:
  615. if isinstance(value, list) and isinstance(new[key], list):
  616. new_fact = []
  617. for item in copy.deepcopy(value) + copy.deepcopy(new[key]):
  618. if item not in new_fact:
  619. new_fact.append(item)
  620. facts[key] = new_fact
  621. # No other condition has been met. Overwrite the old fact
  622. # with the new value.
  623. else:
  624. facts[key] = copy.deepcopy(new[key])
  625. # Key isn't in new so add it to facts to keep it.
  626. else:
  627. facts[key] = copy.deepcopy(value)
  628. new_keys = set(new.keys()) - set(orig.keys())
  629. for key in new_keys:
  630. # Watchout for JSON facts that sometimes load as strings.
  631. # (can happen if the JSON contains a boolean)
  632. if key in inventory_json_facts and isinstance(new[key], string_types):
  633. facts[key] = yaml.safe_load(new[key])
  634. else:
  635. facts[key] = copy.deepcopy(new[key])
  636. return facts
  637. def save_local_facts(filename, facts):
  638. """ Save local facts
  639. Args:
  640. filename (str): local facts file
  641. facts (dict): facts to set
  642. """
  643. try:
  644. fact_dir = os.path.dirname(filename)
  645. try:
  646. os.makedirs(fact_dir) # try to make the directory
  647. except OSError as exception:
  648. if exception.errno != errno.EEXIST: # but it is okay if it is already there
  649. raise # pass any other exceptions up the chain
  650. with open(filename, 'w') as fact_file:
  651. fact_file.write(module.jsonify(facts)) # noqa: F405
  652. os.chmod(filename, 0o600)
  653. except (IOError, OSError) as ex:
  654. raise OpenShiftFactsFileWriteError(
  655. "Could not create fact file: %s, error: %s" % (filename, ex)
  656. )
  657. def get_local_facts_from_file(filename):
  658. """ Retrieve local facts from fact file
  659. Args:
  660. filename (str): local facts file
  661. Returns:
  662. dict: the retrieved facts
  663. """
  664. try:
  665. with open(filename, 'r') as facts_file:
  666. local_facts = json.load(facts_file)
  667. except (ValueError, IOError):
  668. local_facts = {}
  669. return local_facts
  670. def sort_unique(alist):
  671. """ Sorts and de-dupes a list
  672. Args:
  673. list: a list
  674. Returns:
  675. list: a sorted de-duped list
  676. """
  677. return sorted(list(set(alist)))
  678. def safe_get_bool(fact):
  679. """ Get a boolean fact safely.
  680. Args:
  681. facts: fact to convert
  682. Returns:
  683. bool: given fact as a bool
  684. """
  685. return bool(strtobool(str(fact)))
  686. def set_proxy_facts(facts):
  687. """ Set global proxy facts
  688. Args:
  689. facts(dict): existing facts
  690. Returns:
  691. facts(dict): Updated facts with missing values
  692. """
  693. if 'common' in facts:
  694. common = facts['common']
  695. if 'http_proxy' in common or 'https_proxy' in common or 'no_proxy' in common:
  696. if 'no_proxy' in common and isinstance(common['no_proxy'], string_types):
  697. common['no_proxy'] = common['no_proxy'].split(",")
  698. elif 'no_proxy' not in common:
  699. common['no_proxy'] = []
  700. # See https://bugzilla.redhat.com/show_bug.cgi?id=1466783
  701. # masters behind a proxy need to connect to etcd via IP
  702. if 'no_proxy_etcd_host_ips' in common:
  703. if isinstance(common['no_proxy_etcd_host_ips'], string_types):
  704. common['no_proxy'].extend(common['no_proxy_etcd_host_ips'].split(','))
  705. # Master IPs should be added to no proxy lists to make liveness probes to pass
  706. if 'no_proxy_master_ips' in common:
  707. if isinstance(common['no_proxy_master_ips'], string_types):
  708. common['no_proxy'].extend(common['no_proxy_master_ips'].split(','))
  709. if 'generate_no_proxy_hosts' in common and safe_get_bool(common['generate_no_proxy_hosts']):
  710. if 'no_proxy_internal_hostnames' in common:
  711. common['no_proxy'].extend(common['no_proxy_internal_hostnames'].split(','))
  712. # TODO: This is Azure specific and should be scoped out to only Azure installs
  713. common['no_proxy'].append('169.254.169.254')
  714. # We always add local dns domain and ourselves no matter what
  715. kube_svc_ip = str(ipaddress.ip_network(text_type(common['portal_net']))[1])
  716. common['no_proxy'].append(kube_svc_ip)
  717. common['no_proxy'].append('.' + common['dns_domain'])
  718. common['no_proxy'].append('.svc')
  719. common['no_proxy'].append(common['hostname'])
  720. if 'master' in facts:
  721. if 'cluster_hostname' in facts['master']:
  722. common['no_proxy'].append(facts['master']['cluster_hostname'])
  723. common['no_proxy'] = ','.join(sort_unique(common['no_proxy']))
  724. facts['common'] = common
  725. return facts
  726. def set_builddefaults_facts(facts):
  727. """ Set build defaults including setting proxy values from http_proxy, https_proxy,
  728. no_proxy to the more specific builddefaults and builddefaults_git vars.
  729. 1. http_proxy, https_proxy, no_proxy
  730. 2. builddefaults_*
  731. 3. builddefaults_git_*
  732. Args:
  733. facts(dict): existing facts
  734. Returns:
  735. facts(dict): Updated facts with missing values
  736. """
  737. if 'builddefaults' in facts:
  738. builddefaults = facts['builddefaults']
  739. common = facts['common']
  740. # Copy values from common to builddefaults
  741. if 'http_proxy' not in builddefaults and 'http_proxy' in common:
  742. builddefaults['http_proxy'] = common['http_proxy']
  743. if 'https_proxy' not in builddefaults and 'https_proxy' in common:
  744. builddefaults['https_proxy'] = common['https_proxy']
  745. if 'no_proxy' not in builddefaults and 'no_proxy' in common:
  746. builddefaults['no_proxy'] = common['no_proxy']
  747. # Create git specific facts from generic values, if git specific values are
  748. # not defined.
  749. if 'git_http_proxy' not in builddefaults and 'http_proxy' in builddefaults:
  750. builddefaults['git_http_proxy'] = builddefaults['http_proxy']
  751. if 'git_https_proxy' not in builddefaults and 'https_proxy' in builddefaults:
  752. builddefaults['git_https_proxy'] = builddefaults['https_proxy']
  753. if 'git_no_proxy' not in builddefaults and 'no_proxy' in builddefaults:
  754. builddefaults['git_no_proxy'] = builddefaults['no_proxy']
  755. # If we're actually defining a builddefaults config then create admission_plugin_config
  756. # then merge builddefaults[config] structure into admission_plugin_config
  757. # 'config' is the 'openshift_builddefaults_json' inventory variable
  758. if 'config' in builddefaults:
  759. if 'admission_plugin_config' not in facts['master']:
  760. # Scaffold out the full expected datastructure
  761. facts['master']['admission_plugin_config'] = {'BuildDefaults': {'configuration': {'env': {}}}}
  762. facts['master']['admission_plugin_config'].update(builddefaults['config'])
  763. if 'env' in facts['master']['admission_plugin_config']['BuildDefaults']['configuration']:
  764. delete_empty_keys(facts['master']['admission_plugin_config']['BuildDefaults']['configuration']['env'])
  765. return facts
  766. def delete_empty_keys(keylist):
  767. """ Delete dictionary elements from keylist where "value" is empty.
  768. Args:
  769. keylist(list): A list of builddefault configuration envs.
  770. Returns:
  771. none
  772. Example:
  773. keylist = [{'name': 'HTTP_PROXY', 'value': 'http://file.rdu.redhat.com:3128'},
  774. {'name': 'HTTPS_PROXY', 'value': 'http://file.rdu.redhat.com:3128'},
  775. {'name': 'NO_PROXY', 'value': ''}]
  776. After calling delete_empty_keys the provided list is modified to become:
  777. [{'name': 'HTTP_PROXY', 'value': 'http://file.rdu.redhat.com:3128'},
  778. {'name': 'HTTPS_PROXY', 'value': 'http://file.rdu.redhat.com:3128'}]
  779. """
  780. count = 0
  781. for i in range(0, len(keylist)):
  782. if len(keylist[i - count]['value']) == 0:
  783. del keylist[i - count]
  784. count += 1
  785. def set_buildoverrides_facts(facts):
  786. """ Set build overrides
  787. Args:
  788. facts(dict): existing facts
  789. Returns:
  790. facts(dict): Updated facts with missing values
  791. """
  792. if 'buildoverrides' in facts:
  793. buildoverrides = facts['buildoverrides']
  794. # If we're actually defining a buildoverrides config then create admission_plugin_config
  795. # then merge buildoverrides[config] structure into admission_plugin_config
  796. if 'config' in buildoverrides:
  797. if 'admission_plugin_config' not in facts['master']:
  798. facts['master']['admission_plugin_config'] = dict()
  799. facts['master']['admission_plugin_config'].update(buildoverrides['config'])
  800. return facts
  801. def pop_obsolete_local_facts(local_facts):
  802. """Remove unused keys from local_facts"""
  803. keys_to_remove = {
  804. 'master': ('etcd_port', 'etcd_use_ssl', 'etcd_hosts')
  805. }
  806. for role in keys_to_remove:
  807. if role in local_facts:
  808. for key in keys_to_remove[role]:
  809. local_facts[role].pop(key, None)
  810. class OpenShiftFactsUnsupportedRoleError(Exception):
  811. """Origin Facts Unsupported Role Error"""
  812. pass
  813. class OpenShiftFactsFileWriteError(Exception):
  814. """Origin Facts File Write Error"""
  815. pass
  816. class OpenShiftFactsMetadataUnavailableError(Exception):
  817. """Origin Facts Metadata Unavailable Error"""
  818. pass
  819. class OpenShiftFacts(object):
  820. """ Origin Facts
  821. Attributes:
  822. facts (dict): facts for the host
  823. Args:
  824. module (AnsibleModule): an AnsibleModule object
  825. role (str): role for setting local facts
  826. filename (str): local facts file to use
  827. local_facts (dict): local facts to set
  828. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  829. '.' notation ex: ['master.named_certificates']
  830. Raises:
  831. OpenShiftFactsUnsupportedRoleError:
  832. """
  833. known_roles = ['builddefaults',
  834. 'buildoverrides',
  835. 'cloudprovider',
  836. 'common',
  837. 'etcd',
  838. 'master',
  839. 'node']
  840. # Disabling too-many-arguments, this should be cleaned up as a TODO item.
  841. # pylint: disable=too-many-arguments,no-value-for-parameter
  842. def __init__(self, role, filename, local_facts,
  843. additive_facts_to_overwrite=None):
  844. self.changed = False
  845. self.filename = filename
  846. if role not in self.known_roles:
  847. raise OpenShiftFactsUnsupportedRoleError(
  848. "Role %s is not supported by this module" % role
  849. )
  850. self.role = role
  851. # Collect system facts and preface each fact with 'ansible_'.
  852. try:
  853. # pylint: disable=too-many-function-args,invalid-name
  854. self.system_facts = ansible_facts(module, ['hardware', 'network', 'virtual', 'facter']) # noqa: F405
  855. additional_facts = {}
  856. for (k, v) in self.system_facts.items():
  857. additional_facts["ansible_%s" % k.replace('-', '_')] = v
  858. self.system_facts.update(additional_facts)
  859. except UnboundLocalError:
  860. # ansible-2.2,2.3
  861. self.system_facts = get_all_facts(module)['ansible_facts'] # noqa: F405
  862. self.facts = self.generate_facts(local_facts,
  863. additive_facts_to_overwrite)
  864. def generate_facts(self,
  865. local_facts,
  866. additive_facts_to_overwrite):
  867. """ Generate facts
  868. Args:
  869. local_facts (dict): local_facts for overriding generated defaults
  870. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  871. '.' notation ex: ['master.named_certificates']
  872. Returns:
  873. dict: The generated facts
  874. """
  875. local_facts = self.init_local_facts(local_facts,
  876. additive_facts_to_overwrite)
  877. roles = local_facts.keys()
  878. defaults = self.get_defaults(roles)
  879. provider_facts = self.init_provider_facts()
  880. facts = apply_provider_facts(defaults, provider_facts)
  881. facts = merge_facts(facts,
  882. local_facts,
  883. additive_facts_to_overwrite)
  884. facts['current_config'] = get_current_config(facts)
  885. facts = set_url_facts_if_unset(facts)
  886. facts = set_sdn_facts_if_unset(facts, self.system_facts)
  887. facts = build_controller_args(facts)
  888. facts = build_api_server_args(facts)
  889. facts = set_aggregate_facts(facts)
  890. facts = set_proxy_facts(facts)
  891. facts = set_builddefaults_facts(facts)
  892. facts = set_buildoverrides_facts(facts)
  893. facts = set_nodename(facts)
  894. facts = set_allowed_registries(facts)
  895. return dict(openshift=facts)
  896. def get_defaults(self, roles):
  897. """ Get default fact values
  898. Args:
  899. roles (list): list of roles for this host
  900. Returns:
  901. dict: The generated default facts
  902. """
  903. defaults = {}
  904. ip_addr = self.system_facts['ansible_default_ipv4']['address']
  905. exit_code, output, _ = module.run_command(['hostname', '-f']) # noqa: F405
  906. hostname_f = output.strip() if exit_code == 0 else ''
  907. hostname_values = [hostname_f, self.system_facts['ansible_nodename'],
  908. self.system_facts['ansible_fqdn']]
  909. hostname = choose_hostname(hostname_values, ip_addr).lower()
  910. exit_code, output, _ = module.run_command(['hostname']) # noqa: F405
  911. raw_hostname = output.strip() if exit_code == 0 else hostname
  912. defaults['common'] = dict(ip=ip_addr,
  913. public_ip=ip_addr,
  914. raw_hostname=raw_hostname,
  915. hostname=hostname,
  916. public_hostname=hostname,
  917. portal_net='172.30.0.0/16',
  918. dns_domain='cluster.local',
  919. config_base='/etc/origin')
  920. if 'master' in roles:
  921. defaults['master'] = dict(api_use_ssl=True, api_port='8443',
  922. controllers_port='8444',
  923. console_use_ssl=True,
  924. console_path='/console',
  925. console_port='8443',
  926. portal_net='172.30.0.0/16',
  927. bind_addr='0.0.0.0',
  928. session_max_seconds=3600,
  929. session_name='ssn')
  930. if 'cloudprovider' in roles:
  931. defaults['cloudprovider'] = dict(kind=None)
  932. return defaults
  933. def guess_host_provider(self):
  934. """ Guess the host provider
  935. Returns:
  936. dict: The generated default facts for the detected provider
  937. """
  938. # TODO: cloud provider facts should probably be submitted upstream
  939. product_name = self.system_facts['ansible_product_name']
  940. product_version = self.system_facts['ansible_product_version']
  941. virt_type = self.system_facts['ansible_virtualization_type']
  942. virt_role = self.system_facts['ansible_virtualization_role']
  943. bios_vendor = self.system_facts['ansible_system_vendor']
  944. provider = None
  945. metadata = None
  946. if bios_vendor == 'Google':
  947. provider = 'gce'
  948. metadata_url = ('http://metadata.google.internal/'
  949. 'computeMetadata/v1/?recursive=true')
  950. headers = {'Metadata-Flavor': 'Google'}
  951. metadata = get_provider_metadata(metadata_url, True, headers,
  952. True)
  953. # Filter sshKeys and serviceAccounts from gce metadata
  954. if metadata:
  955. metadata['project']['attributes'].pop('sshKeys', None)
  956. metadata['instance'].pop('serviceAccounts', None)
  957. elif bios_vendor == 'Amazon EC2':
  958. # Adds support for Amazon EC2 C5 instance types
  959. provider = 'aws'
  960. metadata_url = 'http://169.254.169.254/latest/meta-data/'
  961. metadata = get_provider_metadata(metadata_url)
  962. elif virt_type == 'xen' and virt_role == 'guest' and re.match(r'.*\.amazon$', product_version):
  963. provider = 'aws'
  964. metadata_url = 'http://169.254.169.254/latest/meta-data/'
  965. metadata = get_provider_metadata(metadata_url)
  966. elif re.search(r'OpenStack', product_name):
  967. provider = 'openstack'
  968. metadata_url = ('http://169.254.169.254/openstack/latest/'
  969. 'meta_data.json')
  970. metadata = get_provider_metadata(metadata_url, True, None,
  971. True)
  972. if metadata:
  973. ec2_compat_url = 'http://169.254.169.254/latest/meta-data/'
  974. metadata['ec2_compat'] = get_provider_metadata(
  975. ec2_compat_url
  976. )
  977. # disable pylint maybe-no-member because overloaded use of
  978. # the module name causes pylint to not detect that results
  979. # is an array or hash
  980. # pylint: disable=maybe-no-member
  981. # Filter public_keys and random_seed from openstack metadata
  982. metadata.pop('public_keys', None)
  983. metadata.pop('random_seed', None)
  984. if not metadata['ec2_compat']:
  985. metadata = None
  986. return dict(name=provider, metadata=metadata)
  987. def init_provider_facts(self):
  988. """ Initialize the provider facts
  989. Returns:
  990. dict: The normalized provider facts
  991. """
  992. provider_info = self.guess_host_provider()
  993. provider_facts = normalize_provider_facts(
  994. provider_info.get('name'),
  995. provider_info.get('metadata')
  996. )
  997. return provider_facts
  998. # Disabling too-many-branches and too-many-locals.
  999. # This should be cleaned up as a TODO item.
  1000. # pylint: disable=too-many-branches, too-many-locals
  1001. def init_local_facts(self, facts=None,
  1002. additive_facts_to_overwrite=None):
  1003. """ Initialize the local facts
  1004. Args:
  1005. facts (dict): local facts to set
  1006. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1007. '.' notation ex: ['master.named_certificates']
  1008. Returns:
  1009. dict: The result of merging the provided facts with existing
  1010. local facts
  1011. """
  1012. changed = False
  1013. facts_to_set = dict()
  1014. if facts is not None:
  1015. facts_to_set[self.role] = facts
  1016. local_facts = get_local_facts_from_file(self.filename)
  1017. migrated_facts = migrate_local_facts(local_facts)
  1018. new_local_facts = merge_facts(migrated_facts,
  1019. facts_to_set,
  1020. additive_facts_to_overwrite)
  1021. new_local_facts = self.remove_empty_facts(new_local_facts)
  1022. pop_obsolete_local_facts(new_local_facts)
  1023. if new_local_facts != local_facts:
  1024. changed = True
  1025. if not module.check_mode: # noqa: F405
  1026. save_local_facts(self.filename, new_local_facts)
  1027. self.changed = changed
  1028. return new_local_facts
  1029. def remove_empty_facts(self, facts=None):
  1030. """ Remove empty facts
  1031. Args:
  1032. facts (dict): facts to clean
  1033. """
  1034. facts_to_remove = []
  1035. for fact, value in iteritems(facts):
  1036. if isinstance(facts[fact], dict):
  1037. facts[fact] = self.remove_empty_facts(facts[fact])
  1038. else:
  1039. if value == "" or value == [""] or value is None:
  1040. facts_to_remove.append(fact)
  1041. for fact in facts_to_remove:
  1042. del facts[fact]
  1043. return facts
  1044. def main():
  1045. """ main """
  1046. # disabling pylint errors for global-variable-undefined and invalid-name
  1047. # for 'global module' usage, since it is required to use ansible_facts
  1048. # pylint: disable=global-variable-undefined, invalid-name
  1049. global module
  1050. module = AnsibleModule( # noqa: F405
  1051. argument_spec=dict(
  1052. role=dict(default='common', required=False,
  1053. choices=OpenShiftFacts.known_roles),
  1054. local_facts=dict(default=None, type='dict', required=False),
  1055. additive_facts_to_overwrite=dict(default=[], type='list', required=False),
  1056. ),
  1057. supports_check_mode=True,
  1058. add_file_common_args=True,
  1059. )
  1060. module.params['gather_subset'] = ['hardware', 'network', 'virtual', 'facter'] # noqa: F405
  1061. module.params['gather_timeout'] = 10 # noqa: F405
  1062. module.params['filter'] = '*' # noqa: F405
  1063. role = module.params['role'] # noqa: F405
  1064. local_facts = module.params['local_facts'] # noqa: F405
  1065. additive_facts_to_overwrite = module.params['additive_facts_to_overwrite'] # noqa: F405
  1066. fact_file = '/etc/ansible/facts.d/openshift.fact'
  1067. openshift_facts = OpenShiftFacts(role,
  1068. fact_file,
  1069. local_facts,
  1070. additive_facts_to_overwrite)
  1071. file_params = module.params.copy() # noqa: F405
  1072. file_params['path'] = fact_file
  1073. file_args = module.load_file_common_arguments(file_params) # noqa: F405
  1074. changed = module.set_fs_attributes_if_different(file_args, # noqa: F405
  1075. openshift_facts.changed)
  1076. return module.exit_json(changed=changed, # noqa: F405
  1077. ansible_facts=openshift_facts.facts)
  1078. if __name__ == '__main__':
  1079. main()