openshift_facts.py 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268
  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. if 'bootstrapped' in facts['node'] and facts['node']['bootstrapped']:
  400. facts['node']['nodename'] = facts['common']['raw_hostname'].lower()
  401. else:
  402. facts['node']['nodename'] = facts['common']['hostname'].lower()
  403. return facts
  404. def format_url(use_ssl, hostname, port, path=''):
  405. """ Format url based on ssl flag, hostname, port and path
  406. Args:
  407. use_ssl (bool): is ssl enabled
  408. hostname (str): hostname
  409. port (str): port
  410. path (str): url path
  411. Returns:
  412. str: The generated url string
  413. """
  414. scheme = 'https' if use_ssl else 'http'
  415. netloc = hostname
  416. if (use_ssl and port != '443') or (not use_ssl and port != '80'):
  417. netloc += ":%s" % port
  418. try:
  419. url = urlparse.urlunparse((scheme, netloc, path, '', '', ''))
  420. except AttributeError:
  421. # pylint: disable=undefined-variable
  422. url = urlunparse((scheme, netloc, path, '', '', ''))
  423. return url
  424. def get_current_config(facts):
  425. """ Get current openshift config
  426. Args:
  427. facts (dict): existing facts
  428. Returns:
  429. dict: the facts dict updated with the current openshift config
  430. """
  431. current_config = dict()
  432. roles = [role for role in facts if role not in ['common', 'provider']]
  433. for role in roles:
  434. if 'roles' in current_config:
  435. current_config['roles'].append(role)
  436. else:
  437. current_config['roles'] = [role]
  438. # TODO: parse the /etc/sysconfig/openshift-{master,node} config to
  439. # determine the location of files.
  440. # TODO: I suspect this isn't working right now, but it doesn't prevent
  441. # anything from working properly as far as I can tell, perhaps because
  442. # we override the kubeconfig path everywhere we use it?
  443. # Query kubeconfig settings
  444. kubeconfig_dir = '/var/lib/origin/openshift.local.certificates'
  445. if role == 'node':
  446. kubeconfig_dir = os.path.join(
  447. kubeconfig_dir, "node-%s" % facts['common']['hostname']
  448. )
  449. kubeconfig_path = os.path.join(kubeconfig_dir, '.kubeconfig')
  450. if os.path.isfile('/usr/bin/openshift') and os.path.isfile(kubeconfig_path):
  451. try:
  452. _, output, _ = module.run_command( # noqa: F405
  453. ["/usr/bin/openshift", "ex", "config", "view", "-o",
  454. "json", "--kubeconfig=%s" % kubeconfig_path],
  455. check_rc=False
  456. )
  457. config = json.loads(output)
  458. cad = 'certificate-authority-data'
  459. try:
  460. for cluster in config['clusters']:
  461. config['clusters'][cluster][cad] = 'masked'
  462. except KeyError:
  463. pass
  464. try:
  465. for user in config['users']:
  466. config['users'][user][cad] = 'masked'
  467. config['users'][user]['client-key-data'] = 'masked'
  468. except KeyError:
  469. pass
  470. current_config['kubeconfig'] = config
  471. # override pylint broad-except warning, since we do not want
  472. # to bubble up any exceptions if oc config view
  473. # fails
  474. # pylint: disable=broad-except
  475. except Exception:
  476. pass
  477. return current_config
  478. def build_controller_args(facts):
  479. """ Build master controller_args """
  480. cloud_cfg_path = os.path.join(facts['common']['config_base'],
  481. 'cloudprovider')
  482. if 'master' in facts:
  483. controller_args = {}
  484. if 'cloudprovider' in facts:
  485. if 'kind' in facts['cloudprovider']:
  486. if facts['cloudprovider']['kind'] == 'aws':
  487. controller_args['cloud-provider'] = ['aws']
  488. controller_args['cloud-config'] = [cloud_cfg_path + '/aws.conf']
  489. controller_args['disable-attach-detach-reconcile-sync'] = ['true']
  490. if facts['cloudprovider']['kind'] == 'azure':
  491. controller_args['cloud-provider'] = ['azure']
  492. controller_args['cloud-config'] = [cloud_cfg_path + '/azure.conf']
  493. if facts['cloudprovider']['kind'] == 'openstack':
  494. controller_args['cloud-provider'] = ['openstack']
  495. controller_args['cloud-config'] = [cloud_cfg_path + '/openstack.conf']
  496. if facts['cloudprovider']['kind'] == 'gce':
  497. controller_args['cloud-provider'] = ['gce']
  498. controller_args['cloud-config'] = [cloud_cfg_path + '/gce.conf']
  499. if controller_args != {}:
  500. facts = merge_facts({'master': {'controller_args': controller_args}}, facts, [])
  501. return facts
  502. def build_api_server_args(facts):
  503. """ Build master api_server_args """
  504. cloud_cfg_path = os.path.join(facts['common']['config_base'],
  505. 'cloudprovider')
  506. if 'master' in facts:
  507. api_server_args = {}
  508. if 'cloudprovider' in facts:
  509. if 'kind' in facts['cloudprovider']:
  510. if facts['cloudprovider']['kind'] == 'aws':
  511. api_server_args['cloud-provider'] = ['aws']
  512. api_server_args['cloud-config'] = [cloud_cfg_path + '/aws.conf']
  513. if facts['cloudprovider']['kind'] == 'azure':
  514. api_server_args['cloud-provider'] = ['azure']
  515. api_server_args['cloud-config'] = [cloud_cfg_path + '/azure.conf']
  516. if facts['cloudprovider']['kind'] == 'openstack':
  517. api_server_args['cloud-provider'] = ['openstack']
  518. api_server_args['cloud-config'] = [cloud_cfg_path + '/openstack.conf']
  519. if facts['cloudprovider']['kind'] == 'gce':
  520. api_server_args['cloud-provider'] = ['gce']
  521. api_server_args['cloud-config'] = [cloud_cfg_path + '/gce.conf']
  522. if api_server_args != {}:
  523. facts = merge_facts({'master': {'api_server_args': api_server_args}}, facts, [])
  524. return facts
  525. def apply_provider_facts(facts, provider_facts):
  526. """ Apply provider facts to supplied facts dict
  527. Args:
  528. facts (dict): facts dict to update
  529. provider_facts (dict): provider facts to apply
  530. roles: host roles
  531. Returns:
  532. dict: the merged facts
  533. """
  534. if not provider_facts:
  535. return facts
  536. common_vars = [('hostname', 'ip'), ('public_hostname', 'public_ip')]
  537. for h_var, ip_var in common_vars:
  538. ip_value = provider_facts['network'].get(ip_var)
  539. if ip_value:
  540. facts['common'][ip_var] = ip_value
  541. facts['common'][h_var] = choose_hostname(
  542. [provider_facts['network'].get(h_var)],
  543. facts['common'][h_var]
  544. )
  545. facts['provider'] = provider_facts
  546. return facts
  547. # Disabling pylint too many branches. This function needs refactored
  548. # but is a very core part of openshift_facts.
  549. # pylint: disable=too-many-branches, too-many-nested-blocks
  550. def merge_facts(orig, new, additive_facts_to_overwrite):
  551. """ Recursively merge facts dicts
  552. Args:
  553. orig (dict): existing facts
  554. new (dict): facts to update
  555. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  556. '.' notation ex: ['master.named_certificates']
  557. Returns:
  558. dict: the merged facts
  559. """
  560. additive_facts = ['named_certificates']
  561. # Facts we do not ever want to merge. These originate in inventory variables
  562. # and contain JSON dicts. We don't ever want to trigger a merge
  563. # here, just completely overwrite with the new if they are present there.
  564. inventory_json_facts = ['admission_plugin_config',
  565. 'kube_admission_plugin_config',
  566. 'image_policy_config',
  567. "builddefaults",
  568. "buildoverrides"]
  569. facts = dict()
  570. for key, value in iteritems(orig):
  571. # Key exists in both old and new facts.
  572. if key in new:
  573. if key in inventory_json_facts:
  574. # Watchout for JSON facts that sometimes load as strings.
  575. # (can happen if the JSON contains a boolean)
  576. if isinstance(new[key], string_types):
  577. facts[key] = yaml.safe_load(new[key])
  578. else:
  579. facts[key] = copy.deepcopy(new[key])
  580. # Continue to recurse if old and new fact is a dictionary.
  581. elif isinstance(value, dict) and isinstance(new[key], dict):
  582. # Collect the subset of additive facts to overwrite if
  583. # key matches. These will be passed to the subsequent
  584. # merge_facts call.
  585. relevant_additive_facts = []
  586. for item in additive_facts_to_overwrite:
  587. if '.' in item and item.startswith(key + '.'):
  588. relevant_additive_facts.append(item)
  589. facts[key] = merge_facts(value, new[key], relevant_additive_facts)
  590. # Key matches an additive fact and we are not overwriting
  591. # it so we will append the new value to the existing value.
  592. elif key in additive_facts and key not in [x.split('.')[-1] for x in additive_facts_to_overwrite]:
  593. if isinstance(value, list) and isinstance(new[key], list):
  594. new_fact = []
  595. for item in copy.deepcopy(value) + copy.deepcopy(new[key]):
  596. if item not in new_fact:
  597. new_fact.append(item)
  598. facts[key] = new_fact
  599. # No other condition has been met. Overwrite the old fact
  600. # with the new value.
  601. else:
  602. facts[key] = copy.deepcopy(new[key])
  603. # Key isn't in new so add it to facts to keep it.
  604. else:
  605. facts[key] = copy.deepcopy(value)
  606. new_keys = set(new.keys()) - set(orig.keys())
  607. for key in new_keys:
  608. # Watchout for JSON facts that sometimes load as strings.
  609. # (can happen if the JSON contains a boolean)
  610. if key in inventory_json_facts and isinstance(new[key], string_types):
  611. facts[key] = yaml.safe_load(new[key])
  612. else:
  613. facts[key] = copy.deepcopy(new[key])
  614. return facts
  615. def save_local_facts(filename, facts):
  616. """ Save local facts
  617. Args:
  618. filename (str): local facts file
  619. facts (dict): facts to set
  620. """
  621. try:
  622. fact_dir = os.path.dirname(filename)
  623. try:
  624. os.makedirs(fact_dir) # try to make the directory
  625. except OSError as exception:
  626. if exception.errno != errno.EEXIST: # but it is okay if it is already there
  627. raise # pass any other exceptions up the chain
  628. with open(filename, 'w') as fact_file:
  629. fact_file.write(module.jsonify(facts)) # noqa: F405
  630. os.chmod(filename, 0o600)
  631. except (IOError, OSError) as ex:
  632. raise OpenShiftFactsFileWriteError(
  633. "Could not create fact file: %s, error: %s" % (filename, ex)
  634. )
  635. def get_local_facts_from_file(filename):
  636. """ Retrieve local facts from fact file
  637. Args:
  638. filename (str): local facts file
  639. Returns:
  640. dict: the retrieved facts
  641. """
  642. try:
  643. with open(filename, 'r') as facts_file:
  644. local_facts = json.load(facts_file)
  645. except (ValueError, IOError):
  646. local_facts = {}
  647. return local_facts
  648. def sort_unique(alist):
  649. """ Sorts and de-dupes a list
  650. Args:
  651. list: a list
  652. Returns:
  653. list: a sorted de-duped list
  654. """
  655. return sorted(list(set(alist)))
  656. def safe_get_bool(fact):
  657. """ Get a boolean fact safely.
  658. Args:
  659. facts: fact to convert
  660. Returns:
  661. bool: given fact as a bool
  662. """
  663. return bool(strtobool(str(fact)))
  664. def set_proxy_facts(facts):
  665. """ Set global proxy facts
  666. Args:
  667. facts(dict): existing facts
  668. Returns:
  669. facts(dict): Updated facts with missing values
  670. """
  671. if 'common' in facts:
  672. common = facts['common']
  673. if 'http_proxy' in common or 'https_proxy' in common or 'no_proxy' in common:
  674. if 'no_proxy' in common and isinstance(common['no_proxy'], string_types):
  675. common['no_proxy'] = common['no_proxy'].split(",")
  676. elif 'no_proxy' not in common:
  677. common['no_proxy'] = []
  678. # See https://bugzilla.redhat.com/show_bug.cgi?id=1466783
  679. # masters behind a proxy need to connect to etcd via IP
  680. if 'no_proxy_etcd_host_ips' in common:
  681. if isinstance(common['no_proxy_etcd_host_ips'], string_types):
  682. common['no_proxy'].extend(common['no_proxy_etcd_host_ips'].split(','))
  683. # Master IPs should be added to no proxy lists to make liveness probes to pass
  684. if 'no_proxy_master_ips' in common:
  685. if isinstance(common['no_proxy_master_ips'], string_types):
  686. common['no_proxy'].extend(common['no_proxy_master_ips'].split(','))
  687. if 'generate_no_proxy_hosts' in common and safe_get_bool(common['generate_no_proxy_hosts']):
  688. if 'no_proxy_internal_hostnames' in common:
  689. common['no_proxy'].extend(common['no_proxy_internal_hostnames'].split(','))
  690. # TODO: This is Azure specific and should be scoped out to only Azure installs
  691. common['no_proxy'].append('169.254.169.254')
  692. # We always add local dns domain and ourselves no matter what
  693. kube_svc_ip = str(ipaddress.ip_network(text_type(common['portal_net']))[1])
  694. common['no_proxy'].append(kube_svc_ip)
  695. common['no_proxy'].append('.' + common['dns_domain'])
  696. common['no_proxy'].append('.svc')
  697. common['no_proxy'].append(common['hostname'])
  698. common['no_proxy'] = ','.join(sort_unique(common['no_proxy']))
  699. facts['common'] = common
  700. return facts
  701. def set_builddefaults_facts(facts):
  702. """ Set build defaults including setting proxy values from http_proxy, https_proxy,
  703. no_proxy to the more specific builddefaults and builddefaults_git vars.
  704. 1. http_proxy, https_proxy, no_proxy
  705. 2. builddefaults_*
  706. 3. builddefaults_git_*
  707. Args:
  708. facts(dict): existing facts
  709. Returns:
  710. facts(dict): Updated facts with missing values
  711. """
  712. if 'builddefaults' in facts:
  713. builddefaults = facts['builddefaults']
  714. common = facts['common']
  715. # Copy values from common to builddefaults
  716. if 'http_proxy' not in builddefaults and 'http_proxy' in common:
  717. builddefaults['http_proxy'] = common['http_proxy']
  718. if 'https_proxy' not in builddefaults and 'https_proxy' in common:
  719. builddefaults['https_proxy'] = common['https_proxy']
  720. if 'no_proxy' not in builddefaults and 'no_proxy' in common:
  721. builddefaults['no_proxy'] = common['no_proxy']
  722. # Create git specific facts from generic values, if git specific values are
  723. # not defined.
  724. if 'git_http_proxy' not in builddefaults and 'http_proxy' in builddefaults:
  725. builddefaults['git_http_proxy'] = builddefaults['http_proxy']
  726. if 'git_https_proxy' not in builddefaults and 'https_proxy' in builddefaults:
  727. builddefaults['git_https_proxy'] = builddefaults['https_proxy']
  728. if 'git_no_proxy' not in builddefaults and 'no_proxy' in builddefaults:
  729. builddefaults['git_no_proxy'] = builddefaults['no_proxy']
  730. # If we're actually defining a builddefaults config then create admission_plugin_config
  731. # then merge builddefaults[config] structure into admission_plugin_config
  732. # 'config' is the 'openshift_builddefaults_json' inventory variable
  733. if 'config' in builddefaults:
  734. if 'admission_plugin_config' not in facts['master']:
  735. # Scaffold out the full expected datastructure
  736. facts['master']['admission_plugin_config'] = {'BuildDefaults': {'configuration': {'env': {}}}}
  737. facts['master']['admission_plugin_config'].update(builddefaults['config'])
  738. if 'env' in facts['master']['admission_plugin_config']['BuildDefaults']['configuration']:
  739. delete_empty_keys(facts['master']['admission_plugin_config']['BuildDefaults']['configuration']['env'])
  740. return facts
  741. def delete_empty_keys(keylist):
  742. """ Delete dictionary elements from keylist where "value" is empty.
  743. Args:
  744. keylist(list): A list of builddefault configuration envs.
  745. Returns:
  746. none
  747. Example:
  748. keylist = [{'name': 'HTTP_PROXY', 'value': 'http://file.rdu.redhat.com:3128'},
  749. {'name': 'HTTPS_PROXY', 'value': 'http://file.rdu.redhat.com:3128'},
  750. {'name': 'NO_PROXY', 'value': ''}]
  751. After calling delete_empty_keys the provided list is modified to become:
  752. [{'name': 'HTTP_PROXY', 'value': 'http://file.rdu.redhat.com:3128'},
  753. {'name': 'HTTPS_PROXY', 'value': 'http://file.rdu.redhat.com:3128'}]
  754. """
  755. count = 0
  756. for i in range(0, len(keylist)):
  757. if len(keylist[i - count]['value']) == 0:
  758. del keylist[i - count]
  759. count += 1
  760. def set_buildoverrides_facts(facts):
  761. """ Set build overrides
  762. Args:
  763. facts(dict): existing facts
  764. Returns:
  765. facts(dict): Updated facts with missing values
  766. """
  767. if 'buildoverrides' in facts:
  768. buildoverrides = facts['buildoverrides']
  769. # If we're actually defining a buildoverrides config then create admission_plugin_config
  770. # then merge buildoverrides[config] structure into admission_plugin_config
  771. if 'config' in buildoverrides:
  772. if 'admission_plugin_config' not in facts['master']:
  773. facts['master']['admission_plugin_config'] = dict()
  774. facts['master']['admission_plugin_config'].update(buildoverrides['config'])
  775. return facts
  776. def pop_obsolete_local_facts(local_facts):
  777. """Remove unused keys from local_facts"""
  778. keys_to_remove = {
  779. 'master': ('etcd_port', 'etcd_use_ssl', 'etcd_hosts')
  780. }
  781. for role in keys_to_remove:
  782. if role in local_facts:
  783. for key in keys_to_remove[role]:
  784. local_facts[role].pop(key, None)
  785. class OpenShiftFactsUnsupportedRoleError(Exception):
  786. """Origin Facts Unsupported Role Error"""
  787. pass
  788. class OpenShiftFactsFileWriteError(Exception):
  789. """Origin Facts File Write Error"""
  790. pass
  791. class OpenShiftFactsMetadataUnavailableError(Exception):
  792. """Origin Facts Metadata Unavailable Error"""
  793. pass
  794. class OpenShiftFacts(object):
  795. """ Origin Facts
  796. Attributes:
  797. facts (dict): facts for the host
  798. Args:
  799. module (AnsibleModule): an AnsibleModule object
  800. role (str): role for setting local facts
  801. filename (str): local facts file to use
  802. local_facts (dict): local facts to set
  803. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  804. '.' notation ex: ['master.named_certificates']
  805. Raises:
  806. OpenShiftFactsUnsupportedRoleError:
  807. """
  808. known_roles = ['builddefaults',
  809. 'buildoverrides',
  810. 'cloudprovider',
  811. 'common',
  812. 'etcd',
  813. 'master',
  814. 'node']
  815. # Disabling too-many-arguments, this should be cleaned up as a TODO item.
  816. # pylint: disable=too-many-arguments,no-value-for-parameter
  817. def __init__(self, role, filename, local_facts,
  818. additive_facts_to_overwrite=None):
  819. self.changed = False
  820. self.filename = filename
  821. if role not in self.known_roles:
  822. raise OpenShiftFactsUnsupportedRoleError(
  823. "Role %s is not supported by this module" % role
  824. )
  825. self.role = role
  826. # Collect system facts and preface each fact with 'ansible_'.
  827. try:
  828. # pylint: disable=too-many-function-args,invalid-name
  829. self.system_facts = ansible_facts(module, ['hardware', 'network', 'virtual', 'facter']) # noqa: F405
  830. additional_facts = {}
  831. for (k, v) in self.system_facts.items():
  832. additional_facts["ansible_%s" % k.replace('-', '_')] = v
  833. self.system_facts.update(additional_facts)
  834. except UnboundLocalError:
  835. # ansible-2.2,2.3
  836. self.system_facts = get_all_facts(module)['ansible_facts'] # noqa: F405
  837. self.facts = self.generate_facts(local_facts,
  838. additive_facts_to_overwrite)
  839. def generate_facts(self,
  840. local_facts,
  841. additive_facts_to_overwrite):
  842. """ Generate facts
  843. Args:
  844. local_facts (dict): local_facts for overriding generated defaults
  845. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  846. '.' notation ex: ['master.named_certificates']
  847. Returns:
  848. dict: The generated facts
  849. """
  850. local_facts = self.init_local_facts(local_facts,
  851. additive_facts_to_overwrite)
  852. roles = local_facts.keys()
  853. defaults = self.get_defaults(roles)
  854. provider_facts = self.init_provider_facts()
  855. facts = apply_provider_facts(defaults, provider_facts)
  856. facts = merge_facts(facts,
  857. local_facts,
  858. additive_facts_to_overwrite)
  859. facts['current_config'] = get_current_config(facts)
  860. facts = set_url_facts_if_unset(facts)
  861. facts = set_sdn_facts_if_unset(facts, self.system_facts)
  862. facts = build_controller_args(facts)
  863. facts = build_api_server_args(facts)
  864. facts = set_aggregate_facts(facts)
  865. facts = set_proxy_facts(facts)
  866. facts = set_builddefaults_facts(facts)
  867. facts = set_buildoverrides_facts(facts)
  868. facts = set_nodename(facts)
  869. return dict(openshift=facts)
  870. def get_defaults(self, roles):
  871. """ Get default fact values
  872. Args:
  873. roles (list): list of roles for this host
  874. Returns:
  875. dict: The generated default facts
  876. """
  877. defaults = {}
  878. ip_addr = self.system_facts['ansible_default_ipv4']['address']
  879. exit_code, output, _ = module.run_command(['hostname', '-f']) # noqa: F405
  880. hostname_f = output.strip() if exit_code == 0 else ''
  881. hostname_values = [hostname_f, self.system_facts['ansible_nodename'],
  882. self.system_facts['ansible_fqdn']]
  883. hostname = choose_hostname(hostname_values, ip_addr).lower()
  884. exit_code, output, _ = module.run_command(['hostname']) # noqa: F405
  885. raw_hostname = output.strip() if exit_code == 0 else hostname
  886. defaults['common'] = dict(ip=ip_addr,
  887. public_ip=ip_addr,
  888. raw_hostname=raw_hostname,
  889. hostname=hostname,
  890. public_hostname=hostname,
  891. portal_net='172.30.0.0/16',
  892. dns_domain='cluster.local',
  893. config_base='/etc/origin')
  894. if 'master' in roles:
  895. defaults['master'] = dict(api_use_ssl=True, api_port='8443',
  896. controllers_port='8444',
  897. console_use_ssl=True,
  898. console_path='/console',
  899. console_port='8443',
  900. portal_net='172.30.0.0/16',
  901. bind_addr='0.0.0.0',
  902. session_max_seconds=3600,
  903. session_name='ssn')
  904. if 'cloudprovider' in roles:
  905. defaults['cloudprovider'] = dict(kind=None)
  906. return defaults
  907. def guess_host_provider(self):
  908. """ Guess the host provider
  909. Returns:
  910. dict: The generated default facts for the detected provider
  911. """
  912. # TODO: cloud provider facts should probably be submitted upstream
  913. product_name = self.system_facts['ansible_product_name']
  914. product_version = self.system_facts['ansible_product_version']
  915. virt_type = self.system_facts['ansible_virtualization_type']
  916. virt_role = self.system_facts['ansible_virtualization_role']
  917. bios_vendor = self.system_facts['ansible_system_vendor']
  918. provider = None
  919. metadata = None
  920. if bios_vendor == 'Google':
  921. provider = 'gce'
  922. metadata_url = ('http://metadata.google.internal/'
  923. 'computeMetadata/v1/?recursive=true')
  924. headers = {'Metadata-Flavor': 'Google'}
  925. metadata = get_provider_metadata(metadata_url, True, headers,
  926. True)
  927. # Filter sshKeys and serviceAccounts from gce metadata
  928. if metadata:
  929. metadata['project']['attributes'].pop('sshKeys', None)
  930. metadata['instance'].pop('serviceAccounts', None)
  931. elif bios_vendor == 'Amazon EC2':
  932. # Adds support for Amazon EC2 C5 instance types
  933. provider = 'aws'
  934. metadata_url = 'http://169.254.169.254/latest/meta-data/'
  935. metadata = get_provider_metadata(metadata_url)
  936. elif virt_type == 'xen' and virt_role == 'guest' and re.match(r'.*\.amazon$', product_version):
  937. provider = 'aws'
  938. metadata_url = 'http://169.254.169.254/latest/meta-data/'
  939. metadata = get_provider_metadata(metadata_url)
  940. elif re.search(r'OpenStack', product_name):
  941. provider = 'openstack'
  942. metadata_url = ('http://169.254.169.254/openstack/latest/'
  943. 'meta_data.json')
  944. metadata = get_provider_metadata(metadata_url, True, None,
  945. True)
  946. if metadata:
  947. ec2_compat_url = 'http://169.254.169.254/latest/meta-data/'
  948. metadata['ec2_compat'] = get_provider_metadata(
  949. ec2_compat_url
  950. )
  951. # disable pylint maybe-no-member because overloaded use of
  952. # the module name causes pylint to not detect that results
  953. # is an array or hash
  954. # pylint: disable=maybe-no-member
  955. # Filter public_keys and random_seed from openstack metadata
  956. metadata.pop('public_keys', None)
  957. metadata.pop('random_seed', None)
  958. if not metadata['ec2_compat']:
  959. metadata = None
  960. return dict(name=provider, metadata=metadata)
  961. def init_provider_facts(self):
  962. """ Initialize the provider facts
  963. Returns:
  964. dict: The normalized provider facts
  965. """
  966. provider_info = self.guess_host_provider()
  967. provider_facts = normalize_provider_facts(
  968. provider_info.get('name'),
  969. provider_info.get('metadata')
  970. )
  971. return provider_facts
  972. # Disabling too-many-branches and too-many-locals.
  973. # This should be cleaned up as a TODO item.
  974. # pylint: disable=too-many-branches, too-many-locals
  975. def init_local_facts(self, facts=None,
  976. additive_facts_to_overwrite=None):
  977. """ Initialize the local facts
  978. Args:
  979. facts (dict): local facts to set
  980. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  981. '.' notation ex: ['master.named_certificates']
  982. Returns:
  983. dict: The result of merging the provided facts with existing
  984. local facts
  985. """
  986. changed = False
  987. facts_to_set = dict()
  988. if facts is not None:
  989. facts_to_set[self.role] = facts
  990. local_facts = get_local_facts_from_file(self.filename)
  991. migrated_facts = migrate_local_facts(local_facts)
  992. new_local_facts = merge_facts(migrated_facts,
  993. facts_to_set,
  994. additive_facts_to_overwrite)
  995. new_local_facts = self.remove_empty_facts(new_local_facts)
  996. pop_obsolete_local_facts(new_local_facts)
  997. if new_local_facts != local_facts:
  998. changed = True
  999. if not module.check_mode: # noqa: F405
  1000. save_local_facts(self.filename, new_local_facts)
  1001. self.changed = changed
  1002. return new_local_facts
  1003. def remove_empty_facts(self, facts=None):
  1004. """ Remove empty facts
  1005. Args:
  1006. facts (dict): facts to clean
  1007. """
  1008. facts_to_remove = []
  1009. for fact, value in iteritems(facts):
  1010. if isinstance(facts[fact], dict):
  1011. facts[fact] = self.remove_empty_facts(facts[fact])
  1012. else:
  1013. if value == "" or value == [""] or value is None:
  1014. facts_to_remove.append(fact)
  1015. for fact in facts_to_remove:
  1016. del facts[fact]
  1017. return facts
  1018. def main():
  1019. """ main """
  1020. # disabling pylint errors for global-variable-undefined and invalid-name
  1021. # for 'global module' usage, since it is required to use ansible_facts
  1022. # pylint: disable=global-variable-undefined, invalid-name
  1023. global module
  1024. module = AnsibleModule( # noqa: F405
  1025. argument_spec=dict(
  1026. role=dict(default='common', required=False,
  1027. choices=OpenShiftFacts.known_roles),
  1028. local_facts=dict(default=None, type='dict', required=False),
  1029. additive_facts_to_overwrite=dict(default=[], type='list', required=False),
  1030. ),
  1031. supports_check_mode=True,
  1032. add_file_common_args=True,
  1033. )
  1034. module.params['gather_subset'] = ['hardware', 'network', 'virtual', 'facter'] # noqa: F405
  1035. module.params['gather_timeout'] = 10 # noqa: F405
  1036. module.params['filter'] = '*' # noqa: F405
  1037. role = module.params['role'] # noqa: F405
  1038. local_facts = module.params['local_facts'] # noqa: F405
  1039. additive_facts_to_overwrite = module.params['additive_facts_to_overwrite'] # noqa: F405
  1040. fact_file = '/etc/ansible/facts.d/openshift.fact'
  1041. openshift_facts = OpenShiftFacts(role,
  1042. fact_file,
  1043. local_facts,
  1044. additive_facts_to_overwrite)
  1045. file_params = module.params.copy() # noqa: F405
  1046. file_params['path'] = fact_file
  1047. file_args = module.load_file_common_arguments(file_params) # noqa: F405
  1048. changed = module.set_fs_attributes_if_different(file_args, # noqa: F405
  1049. openshift_facts.changed)
  1050. return module.exit_json(changed=changed, # noqa: F405
  1051. ansible_facts=openshift_facts.facts)
  1052. if __name__ == '__main__':
  1053. main()