openshift_facts.py 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813
  1. #!/usr/bin/python
  2. # pylint: disable=too-many-lines
  3. # -*- coding: utf-8 -*-
  4. # vim: expandtab:tabstop=4:shiftwidth=4
  5. # Reason: Disable pylint too-many-lines because we don't want to split up this file.
  6. # Status: Permanently disabled to keep this module as self-contained as possible.
  7. """Ansible module for retrieving and setting openshift related facts"""
  8. DOCUMENTATION = '''
  9. ---
  10. module: openshift_facts
  11. short_description: Cluster Facts
  12. author: Jason DeTiberus
  13. requirements: [ ]
  14. '''
  15. EXAMPLES = '''
  16. '''
  17. import ConfigParser
  18. import copy
  19. import os
  20. import StringIO
  21. import yaml
  22. from distutils.util import strtobool
  23. from distutils.version import LooseVersion
  24. import struct
  25. import socket
  26. def migrate_docker_facts(facts):
  27. """ Apply migrations for docker facts """
  28. params = {
  29. 'common': (
  30. 'additional_registries',
  31. 'insecure_registries',
  32. 'blocked_registries',
  33. 'options'
  34. ),
  35. 'node': (
  36. 'log_driver',
  37. 'log_options'
  38. )
  39. }
  40. if 'docker' not in facts:
  41. facts['docker'] = {}
  42. for role in params.keys():
  43. if role in facts:
  44. for param in params[role]:
  45. old_param = 'docker_' + param
  46. if old_param in facts[role]:
  47. facts['docker'][param] = facts[role].pop(old_param)
  48. if 'node' in facts and 'portal_net' in facts['node']:
  49. facts['docker']['hosted_registry_insecure'] = True
  50. facts['docker']['hosted_registry_network'] = facts['node'].pop('portal_net')
  51. return facts
  52. def migrate_local_facts(facts):
  53. """ Apply migrations of local facts """
  54. migrated_facts = copy.deepcopy(facts)
  55. return migrate_docker_facts(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]
  64. itoa = lambda addr: socket.inet_ntoa(struct.pack("!I", addr))
  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. len(hostname.split('.')) < 2):
  79. return False
  80. return True
  81. def choose_hostname(hostnames=None, fallback=''):
  82. """ Choose a hostname from the provided hostnames
  83. Given a list of hostnames and a fallback value, choose a hostname to
  84. use. This function will prefer fqdns if they exist (excluding any that
  85. begin with localhost or end with localdomain) over ip addresses.
  86. Args:
  87. hostnames (list): list of hostnames
  88. fallback (str): default value to set if hostnames does not contain
  89. a valid hostname
  90. Returns:
  91. str: chosen hostname
  92. """
  93. hostname = fallback
  94. if hostnames is None:
  95. return hostname
  96. ip_regex = r'\A\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\Z'
  97. ips = [i for i in hostnames
  98. if (i is not None and isinstance(i, basestring)
  99. and re.match(ip_regex, i))]
  100. hosts = [i for i in hostnames
  101. if i is not None and i != '' and i not in ips]
  102. for host_list in (hosts, ips):
  103. for host in host_list:
  104. if hostname_valid(host):
  105. return host
  106. return hostname
  107. def query_metadata(metadata_url, headers=None, expect_json=False):
  108. """ Return metadata from the provided metadata_url
  109. Args:
  110. metadata_url (str): metadata url
  111. headers (dict): headers to set for metadata request
  112. expect_json (bool): does the metadata_url return json
  113. Returns:
  114. dict or list: metadata request result
  115. """
  116. result, info = fetch_url(module, metadata_url, headers=headers)
  117. if info['status'] != 200:
  118. raise OpenShiftFactsMetadataUnavailableError("Metadata unavailable")
  119. if expect_json:
  120. return module.from_json(result.read())
  121. else:
  122. return [line.strip() for line in result.readlines()]
  123. def walk_metadata(metadata_url, headers=None, expect_json=False):
  124. """ Walk the metadata tree and return a dictionary of the entire tree
  125. Args:
  126. metadata_url (str): metadata url
  127. headers (dict): headers to set for metadata request
  128. expect_json (bool): does the metadata_url return json
  129. Returns:
  130. dict: the result of walking the metadata tree
  131. """
  132. metadata = dict()
  133. for line in query_metadata(metadata_url, headers, expect_json):
  134. if line.endswith('/') and not line == 'public-keys/':
  135. key = line[:-1]
  136. metadata[key] = walk_metadata(metadata_url + line,
  137. headers, expect_json)
  138. else:
  139. results = query_metadata(metadata_url + line, headers,
  140. expect_json)
  141. if len(results) == 1:
  142. # disable pylint maybe-no-member because overloaded use of
  143. # the module name causes pylint to not detect that results
  144. # is an array or hash
  145. # pylint: disable=maybe-no-member
  146. metadata[line] = results.pop()
  147. else:
  148. metadata[line] = results
  149. return metadata
  150. def get_provider_metadata(metadata_url, supports_recursive=False,
  151. headers=None, expect_json=False):
  152. """ Retrieve the provider metadata
  153. Args:
  154. metadata_url (str): metadata url
  155. supports_recursive (bool): does the provider metadata api support
  156. recursion
  157. headers (dict): headers to set for metadata request
  158. expect_json (bool): does the metadata_url return json
  159. Returns:
  160. dict: the provider metadata
  161. """
  162. try:
  163. if supports_recursive:
  164. metadata = query_metadata(metadata_url, headers,
  165. expect_json)
  166. else:
  167. metadata = walk_metadata(metadata_url, headers,
  168. expect_json)
  169. except OpenShiftFactsMetadataUnavailableError:
  170. metadata = None
  171. return metadata
  172. def normalize_gce_facts(metadata, facts):
  173. """ Normalize gce facts
  174. Args:
  175. metadata (dict): provider metadata
  176. facts (dict): facts to update
  177. Returns:
  178. dict: the result of adding the normalized metadata to the provided
  179. facts dict
  180. """
  181. for interface in metadata['instance']['networkInterfaces']:
  182. int_info = dict(ips=[interface['ip']], network_type='gce')
  183. int_info['public_ips'] = [ac['externalIp'] for ac
  184. in interface['accessConfigs']]
  185. int_info['public_ips'].extend(interface['forwardedIps'])
  186. _, _, network_id = interface['network'].rpartition('/')
  187. int_info['network_id'] = network_id
  188. facts['network']['interfaces'].append(int_info)
  189. _, _, zone = metadata['instance']['zone'].rpartition('/')
  190. facts['zone'] = zone
  191. # GCE currently only supports a single interface
  192. facts['network']['ip'] = facts['network']['interfaces'][0]['ips'][0]
  193. pub_ip = facts['network']['interfaces'][0]['public_ips'][0]
  194. facts['network']['public_ip'] = pub_ip
  195. facts['network']['hostname'] = metadata['instance']['hostname']
  196. # TODO: attempt to resolve public_hostname
  197. facts['network']['public_hostname'] = facts['network']['public_ip']
  198. return facts
  199. def normalize_aws_facts(metadata, facts):
  200. """ Normalize aws facts
  201. Args:
  202. metadata (dict): provider metadata
  203. facts (dict): facts to update
  204. Returns:
  205. dict: the result of adding the normalized metadata to the provided
  206. facts dict
  207. """
  208. for interface in sorted(
  209. metadata['network']['interfaces']['macs'].values(),
  210. key=lambda x: x['device-number']
  211. ):
  212. int_info = dict()
  213. var_map = {'ips': 'local-ipv4s', 'public_ips': 'public-ipv4s'}
  214. for ips_var, int_var in var_map.iteritems():
  215. ips = interface.get(int_var)
  216. if isinstance(ips, basestring):
  217. int_info[ips_var] = [ips]
  218. else:
  219. int_info[ips_var] = ips
  220. if 'vpc-id' in interface:
  221. int_info['network_type'] = 'vpc'
  222. else:
  223. int_info['network_type'] = 'classic'
  224. if int_info['network_type'] == 'vpc':
  225. int_info['network_id'] = interface['subnet-id']
  226. else:
  227. int_info['network_id'] = None
  228. facts['network']['interfaces'].append(int_info)
  229. facts['zone'] = metadata['placement']['availability-zone']
  230. # TODO: actually attempt to determine default local and public ips
  231. # by using the ansible default ip fact and the ipv4-associations
  232. # from the ec2 metadata
  233. facts['network']['ip'] = metadata.get('local-ipv4')
  234. facts['network']['public_ip'] = metadata.get('public-ipv4')
  235. # TODO: verify that local hostname makes sense and is resolvable
  236. facts['network']['hostname'] = metadata.get('local-hostname')
  237. # TODO: verify that public hostname makes sense and is resolvable
  238. facts['network']['public_hostname'] = metadata.get('public-hostname')
  239. return facts
  240. def normalize_openstack_facts(metadata, facts):
  241. """ Normalize openstack facts
  242. Args:
  243. metadata (dict): provider metadata
  244. facts (dict): facts to update
  245. Returns:
  246. dict: the result of adding the normalized metadata to the provided
  247. facts dict
  248. """
  249. # openstack ec2 compat api does not support network interfaces and
  250. # the version tested on did not include the info in the openstack
  251. # metadata api, should be updated if neutron exposes this.
  252. facts['zone'] = metadata['availability_zone']
  253. local_ipv4 = metadata['ec2_compat']['local-ipv4'].split(',')[0]
  254. facts['network']['ip'] = local_ipv4
  255. facts['network']['public_ip'] = metadata['ec2_compat']['public-ipv4']
  256. # TODO: verify local hostname makes sense and is resolvable
  257. facts['network']['hostname'] = metadata['hostname']
  258. # TODO: verify that public hostname makes sense and is resolvable
  259. pub_h = metadata['ec2_compat']['public-hostname']
  260. facts['network']['public_hostname'] = pub_h
  261. return facts
  262. def normalize_provider_facts(provider, metadata):
  263. """ Normalize provider facts
  264. Args:
  265. provider (str): host provider
  266. metadata (dict): provider metadata
  267. Returns:
  268. dict: the normalized provider facts
  269. """
  270. if provider is None or metadata is None:
  271. return {}
  272. # TODO: test for ipv6_enabled where possible (gce, aws do not support)
  273. # and configure ipv6 facts if available
  274. # TODO: add support for setting user_data if available
  275. facts = dict(name=provider, metadata=metadata,
  276. network=dict(interfaces=[], ipv6_enabled=False))
  277. if provider == 'gce':
  278. facts = normalize_gce_facts(metadata, facts)
  279. elif provider == 'aws':
  280. facts = normalize_aws_facts(metadata, facts)
  281. elif provider == 'openstack':
  282. facts = normalize_openstack_facts(metadata, facts)
  283. return facts
  284. def set_flannel_facts_if_unset(facts):
  285. """ Set flannel facts if not already present in facts dict
  286. dict: the facts dict updated with the flannel facts if
  287. missing
  288. Args:
  289. facts (dict): existing facts
  290. Returns:
  291. dict: the facts dict updated with the flannel
  292. facts if they were not already present
  293. """
  294. if 'common' in facts:
  295. if 'use_flannel' not in facts['common']:
  296. use_flannel = False
  297. facts['common']['use_flannel'] = use_flannel
  298. return facts
  299. def set_nuage_facts_if_unset(facts):
  300. """ Set nuage facts if not already present in facts dict
  301. dict: the facts dict updated with the nuage facts if
  302. missing
  303. Args:
  304. facts (dict): existing facts
  305. Returns:
  306. dict: the facts dict updated with the nuage
  307. facts if they were not already present
  308. """
  309. if 'common' in facts:
  310. if 'use_nuage' not in facts['common']:
  311. use_nuage = False
  312. facts['common']['use_nuage'] = use_nuage
  313. return facts
  314. def set_node_schedulability(facts):
  315. """ Set schedulable facts if not already present in facts dict
  316. Args:
  317. facts (dict): existing facts
  318. Returns:
  319. dict: the facts dict updated with the generated schedulable
  320. facts if they were not already present
  321. """
  322. if 'node' in facts:
  323. if 'schedulable' not in facts['node']:
  324. if 'master' in facts:
  325. facts['node']['schedulable'] = False
  326. else:
  327. facts['node']['schedulable'] = True
  328. return facts
  329. def set_master_selectors(facts):
  330. """ Set selectors facts if not already present in facts dict
  331. Args:
  332. facts (dict): existing facts
  333. Returns:
  334. dict: the facts dict updated with the generated selectors
  335. facts if they were not already present
  336. """
  337. if 'master' in facts:
  338. if 'infra_nodes' in facts['master']:
  339. deployment_type = facts['common']['deployment_type']
  340. if deployment_type == 'online':
  341. selector = "type=infra"
  342. else:
  343. selector = "region=infra"
  344. if 'router_selector' not in facts['master']:
  345. facts['master']['router_selector'] = selector
  346. if 'registry_selector' not in facts['master']:
  347. facts['master']['registry_selector'] = selector
  348. return facts
  349. def set_metrics_facts_if_unset(facts):
  350. """ Set cluster metrics facts if not already present in facts dict
  351. dict: the facts dict updated with the generated cluster metrics facts if
  352. missing
  353. Args:
  354. facts (dict): existing facts
  355. Returns:
  356. dict: the facts dict updated with the generated cluster metrics
  357. facts if they were not already present
  358. """
  359. if 'common' in facts:
  360. if 'use_cluster_metrics' not in facts['common']:
  361. use_cluster_metrics = False
  362. facts['common']['use_cluster_metrics'] = use_cluster_metrics
  363. return facts
  364. def set_project_cfg_facts_if_unset(facts):
  365. """ Set Project Configuration facts if not already present in facts dict
  366. dict:
  367. Args:
  368. facts (dict): existing facts
  369. Returns:
  370. dict: the facts dict updated with the generated Project Configuration
  371. facts if they were not already present
  372. """
  373. config = {
  374. 'default_node_selector': '',
  375. 'project_request_message': '',
  376. 'project_request_template': '',
  377. 'mcs_allocator_range': 's0:/2',
  378. 'mcs_labels_per_project': 5,
  379. 'uid_allocator_range': '1000000000-1999999999/10000'
  380. }
  381. if 'master' in facts:
  382. for key, value in config.items():
  383. if key not in facts['master']:
  384. facts['master'][key] = value
  385. return facts
  386. def set_identity_providers_if_unset(facts):
  387. """ Set identity_providers fact if not already present in facts dict
  388. Args:
  389. facts (dict): existing facts
  390. Returns:
  391. dict: the facts dict updated with the generated identity providers
  392. facts if they were not already present
  393. """
  394. if 'master' in facts:
  395. deployment_type = facts['common']['deployment_type']
  396. if 'identity_providers' not in facts['master']:
  397. identity_provider = dict(
  398. name='allow_all', challenge=True, login=True,
  399. kind='AllowAllPasswordIdentityProvider'
  400. )
  401. if deployment_type in ['enterprise', 'atomic-enterprise', 'openshift-enterprise']:
  402. identity_provider = dict(
  403. name='deny_all', challenge=True, login=True,
  404. kind='DenyAllPasswordIdentityProvider'
  405. )
  406. facts['master']['identity_providers'] = [identity_provider]
  407. return facts
  408. def set_url_facts_if_unset(facts):
  409. """ Set url facts if not already present in facts dict
  410. Args:
  411. facts (dict): existing facts
  412. Returns:
  413. dict: the facts dict updated with the generated url facts if they
  414. were not already present
  415. """
  416. if 'master' in facts:
  417. hostname = facts['common']['hostname']
  418. cluster_hostname = facts['master'].get('cluster_hostname')
  419. cluster_public_hostname = facts['master'].get('cluster_public_hostname')
  420. public_hostname = facts['common']['public_hostname']
  421. api_hostname = cluster_hostname if cluster_hostname else hostname
  422. api_public_hostname = cluster_public_hostname if cluster_public_hostname else public_hostname
  423. console_path = facts['master']['console_path']
  424. etcd_hosts = facts['master']['etcd_hosts']
  425. use_ssl = dict(
  426. api=facts['master']['api_use_ssl'],
  427. public_api=facts['master']['api_use_ssl'],
  428. loopback_api=facts['master']['api_use_ssl'],
  429. console=facts['master']['console_use_ssl'],
  430. public_console=facts['master']['console_use_ssl'],
  431. etcd=facts['master']['etcd_use_ssl']
  432. )
  433. ports = dict(
  434. api=facts['master']['api_port'],
  435. public_api=facts['master']['api_port'],
  436. loopback_api=facts['master']['api_port'],
  437. console=facts['master']['console_port'],
  438. public_console=facts['master']['console_port'],
  439. etcd=facts['master']['etcd_port'],
  440. )
  441. etcd_urls = []
  442. if etcd_hosts != '':
  443. facts['master']['etcd_port'] = ports['etcd']
  444. facts['master']['embedded_etcd'] = False
  445. for host in etcd_hosts:
  446. etcd_urls.append(format_url(use_ssl['etcd'], host,
  447. ports['etcd']))
  448. else:
  449. etcd_urls = [format_url(use_ssl['etcd'], hostname,
  450. ports['etcd'])]
  451. facts['master'].setdefault('etcd_urls', etcd_urls)
  452. prefix_hosts = [('api', api_hostname),
  453. ('public_api', api_public_hostname),
  454. ('loopback_api', hostname)]
  455. for prefix, host in prefix_hosts:
  456. facts['master'].setdefault(prefix + '_url', format_url(use_ssl[prefix],
  457. host,
  458. ports[prefix]))
  459. r_lhn = "{0}:{1}".format(hostname, ports['api']).replace('.', '-')
  460. r_lhu = "system:openshift-master/{0}:{1}".format(api_hostname, ports['api']).replace('.', '-')
  461. facts['master'].setdefault('loopback_cluster_name', r_lhn)
  462. facts['master'].setdefault('loopback_context_name', "default/{0}/system:openshift-master".format(r_lhn))
  463. facts['master'].setdefault('loopback_user', r_lhu)
  464. prefix_hosts = [('console', api_hostname), ('public_console', api_public_hostname)]
  465. for prefix, host in prefix_hosts:
  466. facts['master'].setdefault(prefix + '_url', format_url(use_ssl[prefix],
  467. host,
  468. ports[prefix],
  469. console_path))
  470. return facts
  471. def set_aggregate_facts(facts):
  472. """ Set aggregate facts
  473. Args:
  474. facts (dict): existing facts
  475. Returns:
  476. dict: the facts dict updated with aggregated facts
  477. """
  478. all_hostnames = set()
  479. internal_hostnames = set()
  480. if 'common' in facts:
  481. all_hostnames.add(facts['common']['hostname'])
  482. all_hostnames.add(facts['common']['public_hostname'])
  483. all_hostnames.add(facts['common']['ip'])
  484. all_hostnames.add(facts['common']['public_ip'])
  485. internal_hostnames.add(facts['common']['hostname'])
  486. internal_hostnames.add(facts['common']['ip'])
  487. cluster_domain = facts['common']['dns_domain']
  488. if 'master' in facts:
  489. if 'cluster_hostname' in facts['master']:
  490. all_hostnames.add(facts['master']['cluster_hostname'])
  491. if 'cluster_public_hostname' in facts['master']:
  492. all_hostnames.add(facts['master']['cluster_public_hostname'])
  493. svc_names = ['openshift', 'openshift.default', 'openshift.default.svc',
  494. 'openshift.default.svc.' + cluster_domain, 'kubernetes', 'kubernetes.default',
  495. 'kubernetes.default.svc', 'kubernetes.default.svc.' + cluster_domain]
  496. all_hostnames.update(svc_names)
  497. internal_hostnames.update(svc_names)
  498. first_svc_ip = first_ip(facts['master']['portal_net'])
  499. all_hostnames.add(first_svc_ip)
  500. internal_hostnames.add(first_svc_ip)
  501. facts['common']['all_hostnames'] = list(all_hostnames)
  502. facts['common']['internal_hostnames'] = list(internal_hostnames)
  503. return facts
  504. def set_etcd_facts_if_unset(facts):
  505. """
  506. If using embedded etcd, loads the data directory from master-config.yaml.
  507. If using standalone etcd, loads ETCD_DATA_DIR from etcd.conf.
  508. If anything goes wrong parsing these, the fact will not be set.
  509. """
  510. if 'master' in facts and facts['master']['embedded_etcd']:
  511. etcd_facts = facts['etcd'] if 'etcd' in facts else dict()
  512. if 'etcd_data_dir' not in etcd_facts:
  513. try:
  514. # Parse master config to find actual etcd data dir:
  515. master_cfg_path = os.path.join(facts['common']['config_base'],
  516. 'master/master-config.yaml')
  517. master_cfg_f = open(master_cfg_path, 'r')
  518. config = yaml.safe_load(master_cfg_f.read())
  519. master_cfg_f.close()
  520. etcd_facts['etcd_data_dir'] = \
  521. config['etcdConfig']['storageDirectory']
  522. facts['etcd'] = etcd_facts
  523. # We don't want exceptions bubbling up here:
  524. # pylint: disable=broad-except
  525. except Exception:
  526. pass
  527. else:
  528. etcd_facts = facts['etcd'] if 'etcd' in facts else dict()
  529. # Read ETCD_DATA_DIR from /etc/etcd/etcd.conf:
  530. try:
  531. # Add a fake section for parsing:
  532. ini_str = '[root]\n' + open('/etc/etcd/etcd.conf', 'r').read()
  533. ini_fp = StringIO.StringIO(ini_str)
  534. config = ConfigParser.RawConfigParser()
  535. config.readfp(ini_fp)
  536. etcd_data_dir = config.get('root', 'ETCD_DATA_DIR')
  537. if etcd_data_dir.startswith('"') and etcd_data_dir.endswith('"'):
  538. etcd_data_dir = etcd_data_dir[1:-1]
  539. etcd_facts['etcd_data_dir'] = etcd_data_dir
  540. facts['etcd'] = etcd_facts
  541. # We don't want exceptions bubbling up here:
  542. # pylint: disable=broad-except
  543. except Exception:
  544. pass
  545. return facts
  546. def set_deployment_facts_if_unset(facts):
  547. """ Set Facts that vary based on deployment_type. This currently
  548. includes common.service_type, common.config_base, master.registry_url,
  549. node.registry_url, node.storage_plugin_deps
  550. Args:
  551. facts (dict): existing facts
  552. Returns:
  553. dict: the facts dict updated with the generated deployment_type
  554. facts
  555. """
  556. # disabled to avoid breaking up facts related to deployment type into
  557. # multiple methods for now.
  558. # pylint: disable=too-many-statements, too-many-branches
  559. if 'common' in facts:
  560. deployment_type = facts['common']['deployment_type']
  561. if 'service_type' not in facts['common']:
  562. service_type = 'atomic-openshift'
  563. if deployment_type == 'origin':
  564. service_type = 'origin'
  565. elif deployment_type in ['enterprise']:
  566. service_type = 'openshift'
  567. facts['common']['service_type'] = service_type
  568. if 'config_base' not in facts['common']:
  569. config_base = '/etc/origin'
  570. if deployment_type in ['enterprise']:
  571. config_base = '/etc/openshift'
  572. # Handle upgrade scenarios when symlinks don't yet exist:
  573. if not os.path.exists(config_base) and os.path.exists('/etc/openshift'):
  574. config_base = '/etc/openshift'
  575. facts['common']['config_base'] = config_base
  576. if 'data_dir' not in facts['common']:
  577. data_dir = '/var/lib/origin'
  578. if deployment_type in ['enterprise']:
  579. data_dir = '/var/lib/openshift'
  580. # Handle upgrade scenarios when symlinks don't yet exist:
  581. if not os.path.exists(data_dir) and os.path.exists('/var/lib/openshift'):
  582. data_dir = '/var/lib/openshift'
  583. facts['common']['data_dir'] = data_dir
  584. if 'docker' in facts:
  585. deployment_type = facts['common']['deployment_type']
  586. if deployment_type in ['enterprise', 'atomic-enterprise', 'openshift-enterprise']:
  587. addtl_regs = facts['docker'].get('additional_registries', [])
  588. ent_reg = 'registry.access.redhat.com'
  589. if ent_reg not in addtl_regs:
  590. facts['docker']['additional_registries'] = addtl_regs + [ent_reg]
  591. for role in ('master', 'node'):
  592. if role in facts:
  593. deployment_type = facts['common']['deployment_type']
  594. if 'registry_url' not in facts[role]:
  595. registry_url = 'openshift/origin-${component}:${version}'
  596. if deployment_type in ['enterprise', 'online', 'openshift-enterprise']:
  597. registry_url = 'openshift3/ose-${component}:${version}'
  598. elif deployment_type == 'atomic-enterprise':
  599. registry_url = 'aep3_beta/aep-${component}:${version}'
  600. facts[role]['registry_url'] = registry_url
  601. if 'master' in facts:
  602. deployment_type = facts['common']['deployment_type']
  603. openshift_features = ['Builder', 'S2IBuilder', 'WebConsole']
  604. if 'disabled_features' in facts['master']:
  605. if deployment_type == 'atomic-enterprise':
  606. curr_disabled_features = set(facts['master']['disabled_features'])
  607. facts['master']['disabled_features'] = list(curr_disabled_features.union(openshift_features))
  608. else:
  609. if deployment_type == 'atomic-enterprise':
  610. facts['master']['disabled_features'] = openshift_features
  611. if 'node' in facts:
  612. deployment_type = facts['common']['deployment_type']
  613. if 'storage_plugin_deps' not in facts['node']:
  614. if deployment_type in ['openshift-enterprise', 'atomic-enterprise', 'origin']:
  615. facts['node']['storage_plugin_deps'] = ['ceph', 'glusterfs', 'iscsi']
  616. else:
  617. facts['node']['storage_plugin_deps'] = []
  618. return facts
  619. def set_version_facts_if_unset(facts):
  620. """ Set version facts. This currently includes common.version and
  621. common.version_gte_3_1_or_1_1.
  622. Args:
  623. facts (dict): existing facts
  624. Returns:
  625. dict: the facts dict updated with version facts.
  626. """
  627. if 'common' in facts:
  628. deployment_type = facts['common']['deployment_type']
  629. facts['common']['version'] = version = get_openshift_version(facts)
  630. if version is not None:
  631. if deployment_type == 'origin':
  632. version_gte_3_1_or_1_1 = LooseVersion(version) >= LooseVersion('1.1.0')
  633. version_gte_3_1_1_or_1_1_1 = LooseVersion(version) >= LooseVersion('1.1.1')
  634. version_gte_3_2_or_1_2 = LooseVersion(version) >= LooseVersion('1.2.0')
  635. else:
  636. version_gte_3_1_or_1_1 = LooseVersion(version) >= LooseVersion('3.0.2.905')
  637. version_gte_3_1_1_or_1_1_1 = LooseVersion(version) >= LooseVersion('3.1.1')
  638. version_gte_3_2_or_1_2 = LooseVersion(version) >= LooseVersion('3.1.1.901')
  639. else:
  640. version_gte_3_1_or_1_1 = True
  641. version_gte_3_1_1_or_1_1_1 = True
  642. version_gte_3_2_or_1_2 = True
  643. facts['common']['version_gte_3_1_or_1_1'] = version_gte_3_1_or_1_1
  644. facts['common']['version_gte_3_1_1_or_1_1_1'] = version_gte_3_1_1_or_1_1_1
  645. facts['common']['version_gte_3_2_or_1_2'] = version_gte_3_2_or_1_2
  646. if version_gte_3_2_or_1_2:
  647. examples_content_version = 'v1.2'
  648. elif version_gte_3_1_or_1_1:
  649. examples_content_version = 'v1.1'
  650. else:
  651. examples_content_version = 'v1.0'
  652. facts['common']['examples_content_version'] = examples_content_version
  653. return facts
  654. def set_manageiq_facts_if_unset(facts):
  655. """ Set manageiq facts. This currently includes common.use_manageiq.
  656. Args:
  657. facts (dict): existing facts
  658. Returns:
  659. dict: the facts dict updated with version facts.
  660. Raises:
  661. OpenShiftFactsInternalError:
  662. """
  663. if 'common' not in facts:
  664. if 'version_gte_3_1_or_1_1' not in facts['common']:
  665. raise OpenShiftFactsInternalError(
  666. "Invalid invocation: The required facts are not set"
  667. )
  668. if 'use_manageiq' not in facts['common']:
  669. facts['common']['use_manageiq'] = facts['common']['version_gte_3_1_or_1_1']
  670. return facts
  671. def set_sdn_facts_if_unset(facts, system_facts):
  672. """ Set sdn facts if not already present in facts dict
  673. Args:
  674. facts (dict): existing facts
  675. system_facts (dict): ansible_facts
  676. Returns:
  677. dict: the facts dict updated with the generated sdn facts if they
  678. were not already present
  679. """
  680. if 'common' in facts:
  681. use_sdn = facts['common']['use_openshift_sdn']
  682. if not (use_sdn == '' or isinstance(use_sdn, bool)):
  683. use_sdn = safe_get_bool(use_sdn)
  684. facts['common']['use_openshift_sdn'] = use_sdn
  685. if 'sdn_network_plugin_name' not in facts['common']:
  686. plugin = 'redhat/openshift-ovs-subnet' if use_sdn else ''
  687. facts['common']['sdn_network_plugin_name'] = plugin
  688. if 'master' in facts:
  689. if 'sdn_cluster_network_cidr' not in facts['master']:
  690. facts['master']['sdn_cluster_network_cidr'] = '10.1.0.0/16'
  691. if 'sdn_host_subnet_length' not in facts['master']:
  692. facts['master']['sdn_host_subnet_length'] = '8'
  693. if 'node' in facts and 'sdn_mtu' not in facts['node']:
  694. node_ip = facts['common']['ip']
  695. # default MTU if interface MTU cannot be detected
  696. facts['node']['sdn_mtu'] = '1450'
  697. for val in system_facts.itervalues():
  698. if isinstance(val, dict) and 'mtu' in val:
  699. mtu = val['mtu']
  700. if 'ipv4' in val and val['ipv4'].get('address') == node_ip:
  701. facts['node']['sdn_mtu'] = str(mtu - 50)
  702. return facts
  703. def format_url(use_ssl, hostname, port, path=''):
  704. """ Format url based on ssl flag, hostname, port and path
  705. Args:
  706. use_ssl (bool): is ssl enabled
  707. hostname (str): hostname
  708. port (str): port
  709. path (str): url path
  710. Returns:
  711. str: The generated url string
  712. """
  713. scheme = 'https' if use_ssl else 'http'
  714. netloc = hostname
  715. if (use_ssl and port != '443') or (not use_ssl and port != '80'):
  716. netloc += ":%s" % port
  717. return urlparse.urlunparse((scheme, netloc, path, '', '', ''))
  718. def get_current_config(facts):
  719. """ Get current openshift config
  720. Args:
  721. facts (dict): existing facts
  722. Returns:
  723. dict: the facts dict updated with the current openshift config
  724. """
  725. current_config = dict()
  726. roles = [role for role in facts if role not in ['common', 'provider']]
  727. for role in roles:
  728. if 'roles' in current_config:
  729. current_config['roles'].append(role)
  730. else:
  731. current_config['roles'] = [role]
  732. # TODO: parse the /etc/sysconfig/openshift-{master,node} config to
  733. # determine the location of files.
  734. # TODO: I suspect this isn't working right now, but it doesn't prevent
  735. # anything from working properly as far as I can tell, perhaps because
  736. # we override the kubeconfig path everywhere we use it?
  737. # Query kubeconfig settings
  738. kubeconfig_dir = '/var/lib/origin/openshift.local.certificates'
  739. if role == 'node':
  740. kubeconfig_dir = os.path.join(
  741. kubeconfig_dir, "node-%s" % facts['common']['hostname']
  742. )
  743. kubeconfig_path = os.path.join(kubeconfig_dir, '.kubeconfig')
  744. if (os.path.isfile('/usr/bin/openshift')
  745. and os.path.isfile(kubeconfig_path)):
  746. try:
  747. _, output, _ = module.run_command(
  748. ["/usr/bin/openshift", "ex", "config", "view", "-o",
  749. "json", "--kubeconfig=%s" % kubeconfig_path],
  750. check_rc=False
  751. )
  752. config = json.loads(output)
  753. cad = 'certificate-authority-data'
  754. try:
  755. for cluster in config['clusters']:
  756. config['clusters'][cluster][cad] = 'masked'
  757. except KeyError:
  758. pass
  759. try:
  760. for user in config['users']:
  761. config['users'][user][cad] = 'masked'
  762. config['users'][user]['client-key-data'] = 'masked'
  763. except KeyError:
  764. pass
  765. current_config['kubeconfig'] = config
  766. # override pylint broad-except warning, since we do not want
  767. # to bubble up any exceptions if oc config view
  768. # fails
  769. # pylint: disable=broad-except
  770. except Exception:
  771. pass
  772. return current_config
  773. def build_kubelet_args(facts):
  774. """ Build node kubelet_args """
  775. cloud_cfg_path = os.path.join(facts['common']['config_base'],
  776. 'cloudprovider')
  777. if 'node' in facts:
  778. kubelet_args = {}
  779. if 'cloudprovider' in facts:
  780. if facts['cloudprovider']['kind'] == 'aws':
  781. kubelet_args['cloud-provider'] = ['aws']
  782. kubelet_args['cloud-config'] = [cloud_cfg_path + '/aws.conf']
  783. if facts['cloudprovider']['kind'] == 'openstack':
  784. kubelet_args['cloud-provider'] = ['openstack']
  785. kubelet_args['cloud-config'] = [cloud_cfg_path + '/openstack.conf']
  786. if kubelet_args != {}:
  787. facts = merge_facts({'node': {'kubelet_args': kubelet_args}}, facts, [], [])
  788. return facts
  789. def build_controller_args(facts):
  790. """ Build master controller_args """
  791. cloud_cfg_path = os.path.join(facts['common']['config_base'],
  792. 'cloudprovider')
  793. if 'master' in facts:
  794. controller_args = {}
  795. if 'cloudprovider' in facts:
  796. if facts['cloudprovider']['kind'] == 'aws':
  797. controller_args['cloud-provider'] = ['aws']
  798. controller_args['cloud-config'] = [cloud_cfg_path + '/aws.conf']
  799. if facts['cloudprovider']['kind'] == 'openstack':
  800. controller_args['cloud-provider'] = ['openstack']
  801. controller_args['cloud-config'] = [cloud_cfg_path + '/openstack.conf']
  802. if controller_args != {}:
  803. facts = merge_facts({'master': {'controller_args': controller_args}}, facts, [], [])
  804. return facts
  805. def build_api_server_args(facts):
  806. """ Build master api_server_args """
  807. cloud_cfg_path = os.path.join(facts['common']['config_base'],
  808. 'cloudprovider')
  809. if 'master' in facts:
  810. api_server_args = {}
  811. if 'cloudprovider' in facts:
  812. if facts['cloudprovider']['kind'] == 'aws':
  813. api_server_args['cloud-provider'] = ['aws']
  814. api_server_args['cloud-config'] = [cloud_cfg_path + '/aws.conf']
  815. if facts['cloudprovider']['kind'] == 'openstack':
  816. api_server_args['cloud-provider'] = ['openstack']
  817. api_server_args['cloud-config'] = [cloud_cfg_path + '/openstack.conf']
  818. if api_server_args != {}:
  819. facts = merge_facts({'master': {'api_server_args': api_server_args}}, facts, [], [])
  820. return facts
  821. def get_openshift_version(facts, cli_image=None):
  822. """ Get current version of openshift on the host
  823. Args:
  824. facts (dict): existing facts
  825. optional cli_image for pulling the version number
  826. Returns:
  827. version: the current openshift version
  828. """
  829. version = None
  830. # No need to run this method repeatedly on a system if we already know the
  831. # version
  832. if 'common' in facts:
  833. if 'version' in facts['common'] and facts['common']['version'] is not None:
  834. return facts['common']['version']
  835. if os.path.isfile('/usr/bin/openshift'):
  836. _, output, _ = module.run_command(['/usr/bin/openshift', 'version'])
  837. version = parse_openshift_version(output)
  838. if 'is_containerized' in facts['common'] and safe_get_bool(facts['common']['is_containerized']):
  839. container = None
  840. if 'master' in facts:
  841. if 'cluster_method' in facts['master']:
  842. container = facts['common']['service_type'] + '-master-api'
  843. else:
  844. container = facts['common']['service_type'] + '-master'
  845. elif 'node' in facts:
  846. container = facts['common']['service_type'] + '-node'
  847. if container is not None:
  848. exit_code, output, _ = module.run_command(['docker', 'exec', container, 'openshift', 'version'])
  849. # if for some reason the container is installed but not running
  850. # we'll fall back to using docker run later in this method.
  851. if exit_code == 0:
  852. version = parse_openshift_version(output)
  853. if version is None and cli_image is not None:
  854. # Assume we haven't installed the environment yet and we need
  855. # to query the latest image
  856. exit_code, output, _ = module.run_command(['docker', 'run', '--rm', cli_image, 'version'])
  857. version = parse_openshift_version(output)
  858. return version
  859. def parse_openshift_version(output):
  860. """ Apply provider facts to supplied facts dict
  861. Args:
  862. string: output of 'openshift version'
  863. Returns:
  864. string: the version number
  865. """
  866. versions = dict(e.split(' v') for e in output.splitlines() if ' v' in e)
  867. return versions.get('openshift', '')
  868. def apply_provider_facts(facts, provider_facts):
  869. """ Apply provider facts to supplied facts dict
  870. Args:
  871. facts (dict): facts dict to update
  872. provider_facts (dict): provider facts to apply
  873. roles: host roles
  874. Returns:
  875. dict: the merged facts
  876. """
  877. if not provider_facts:
  878. return facts
  879. common_vars = [('hostname', 'ip'), ('public_hostname', 'public_ip')]
  880. for h_var, ip_var in common_vars:
  881. ip_value = provider_facts['network'].get(ip_var)
  882. if ip_value:
  883. facts['common'][ip_var] = ip_value
  884. facts['common'][h_var] = choose_hostname(
  885. [provider_facts['network'].get(h_var)],
  886. facts['common'][ip_var]
  887. )
  888. facts['provider'] = provider_facts
  889. return facts
  890. # Disabling pylint too many branches. This function needs refactored
  891. # but is a very core part of openshift_facts.
  892. # pylint: disable=too-many-branches
  893. def merge_facts(orig, new, additive_facts_to_overwrite, protected_facts_to_overwrite):
  894. """ Recursively merge facts dicts
  895. Args:
  896. orig (dict): existing facts
  897. new (dict): facts to update
  898. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  899. '.' notation ex: ['master.named_certificates']
  900. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  901. '.' notation ex: ['master.master_count']
  902. Returns:
  903. dict: the merged facts
  904. """
  905. additive_facts = ['named_certificates']
  906. protected_facts = ['ha', 'master_count']
  907. facts = dict()
  908. for key, value in orig.iteritems():
  909. # Key exists in both old and new facts.
  910. if key in new:
  911. # Continue to recurse if old and new fact is a dictionary.
  912. if isinstance(value, dict) and isinstance(new[key], dict):
  913. # Collect the subset of additive facts to overwrite if
  914. # key matches. These will be passed to the subsequent
  915. # merge_facts call.
  916. relevant_additive_facts = []
  917. for item in additive_facts_to_overwrite:
  918. if '.' in item and item.startswith(key + '.'):
  919. relevant_additive_facts.append(item)
  920. # Collect the subset of protected facts to overwrite
  921. # if key matches. These will be passed to the
  922. # subsequent merge_facts call.
  923. relevant_protected_facts = []
  924. for item in protected_facts_to_overwrite:
  925. if '.' in item and item.startswith(key + '.'):
  926. relevant_protected_facts.append(item)
  927. facts[key] = merge_facts(value, new[key], relevant_additive_facts, relevant_protected_facts)
  928. # Key matches an additive fact and we are not overwriting
  929. # it so we will append the new value to the existing value.
  930. elif key in additive_facts and key not in [x.split('.')[-1] for x in additive_facts_to_overwrite]:
  931. if isinstance(value, list) and isinstance(new[key], list):
  932. new_fact = []
  933. for item in copy.deepcopy(value) + copy.deepcopy(new[key]):
  934. if item not in new_fact:
  935. new_fact.append(item)
  936. facts[key] = new_fact
  937. # Key matches a protected fact and we are not overwriting
  938. # it so we will determine if it is okay to change this
  939. # fact.
  940. elif key in protected_facts and key not in [x.split('.')[-1] for x in protected_facts_to_overwrite]:
  941. # The master count (int) can only increase unless it
  942. # has been passed as a protected fact to overwrite.
  943. if key == 'master_count':
  944. if int(value) <= int(new[key]):
  945. facts[key] = copy.deepcopy(new[key])
  946. else:
  947. module.fail_json(msg='openshift_facts received a lower value for openshift.master.master_count')
  948. # ha (bool) can not change unless it has been passed
  949. # as a protected fact to overwrite.
  950. if key == 'ha':
  951. if safe_get_bool(value) != safe_get_bool(new[key]):
  952. module.fail_json(msg='openshift_facts received a different value for openshift.master.ha')
  953. else:
  954. facts[key] = value
  955. # No other condition has been met. Overwrite the old fact
  956. # with the new value.
  957. else:
  958. facts[key] = copy.deepcopy(new[key])
  959. # Key isn't in new so add it to facts to keep it.
  960. else:
  961. facts[key] = copy.deepcopy(value)
  962. new_keys = set(new.keys()) - set(orig.keys())
  963. for key in new_keys:
  964. facts[key] = copy.deepcopy(new[key])
  965. return facts
  966. def save_local_facts(filename, facts):
  967. """ Save local facts
  968. Args:
  969. filename (str): local facts file
  970. facts (dict): facts to set
  971. """
  972. try:
  973. fact_dir = os.path.dirname(filename)
  974. if not os.path.exists(fact_dir):
  975. os.makedirs(fact_dir)
  976. with open(filename, 'w') as fact_file:
  977. fact_file.write(module.jsonify(facts))
  978. os.chmod(filename, 0o600)
  979. except (IOError, OSError) as ex:
  980. raise OpenShiftFactsFileWriteError(
  981. "Could not create fact file: %s, error: %s" % (filename, ex)
  982. )
  983. def get_local_facts_from_file(filename):
  984. """ Retrieve local facts from fact file
  985. Args:
  986. filename (str): local facts file
  987. Returns:
  988. dict: the retrieved facts
  989. """
  990. local_facts = dict()
  991. try:
  992. # Handle conversion of INI style facts file to json style
  993. ini_facts = ConfigParser.SafeConfigParser()
  994. ini_facts.read(filename)
  995. for section in ini_facts.sections():
  996. local_facts[section] = dict()
  997. for key, value in ini_facts.items(section):
  998. local_facts[section][key] = value
  999. except (ConfigParser.MissingSectionHeaderError,
  1000. ConfigParser.ParsingError):
  1001. try:
  1002. with open(filename, 'r') as facts_file:
  1003. local_facts = json.load(facts_file)
  1004. except (ValueError, IOError):
  1005. pass
  1006. return local_facts
  1007. def safe_get_bool(fact):
  1008. """ Get a boolean fact safely.
  1009. Args:
  1010. facts: fact to convert
  1011. Returns:
  1012. bool: given fact as a bool
  1013. """
  1014. return bool(strtobool(str(fact)))
  1015. # pylint: disable=too-many-statements
  1016. def set_container_facts_if_unset(facts):
  1017. """ Set containerized facts.
  1018. Args:
  1019. facts (dict): existing facts
  1020. Returns:
  1021. dict: the facts dict updated with the generated containerization
  1022. facts
  1023. """
  1024. deployment_type = facts['common']['deployment_type']
  1025. if deployment_type in ['enterprise', 'openshift-enterprise']:
  1026. master_image = 'openshift3/ose'
  1027. cli_image = master_image
  1028. node_image = 'openshift3/node'
  1029. ovs_image = 'openshift3/openvswitch'
  1030. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  1031. pod_image = 'openshift3/ose-pod'
  1032. router_image = 'openshift3/ose-haproxy-router'
  1033. registry_image = 'openshift3/ose-docker-registry'
  1034. deployer_image = 'openshift3/ose-deployer'
  1035. elif deployment_type == 'atomic-enterprise':
  1036. master_image = 'aep3_beta/aep'
  1037. cli_image = master_image
  1038. node_image = 'aep3_beta/node'
  1039. ovs_image = 'aep3_beta/openvswitch'
  1040. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  1041. pod_image = 'aep3_beta/aep-pod'
  1042. router_image = 'aep3_beta/aep-haproxy-router'
  1043. registry_image = 'aep3_beta/aep-docker-registry'
  1044. deployer_image = 'aep3_beta/aep-deployer'
  1045. else:
  1046. master_image = 'openshift/origin'
  1047. cli_image = master_image
  1048. node_image = 'openshift/node'
  1049. ovs_image = 'openshift/openvswitch'
  1050. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  1051. pod_image = 'openshift/origin-pod'
  1052. router_image = 'openshift/origin-haproxy-router'
  1053. registry_image = 'openshift/origin-docker-registry'
  1054. deployer_image = 'openshift/origin-deployer'
  1055. facts['common']['is_atomic'] = os.path.isfile('/run/ostree-booted')
  1056. if 'is_containerized' not in facts['common']:
  1057. facts['common']['is_containerized'] = facts['common']['is_atomic']
  1058. if 'cli_image' not in facts['common']:
  1059. facts['common']['cli_image'] = cli_image
  1060. if 'pod_image' not in facts['common']:
  1061. facts['common']['pod_image'] = pod_image
  1062. if 'router_image' not in facts['common']:
  1063. facts['common']['router_image'] = router_image
  1064. if 'registry_image' not in facts['common']:
  1065. facts['common']['registry_image'] = registry_image
  1066. if 'deployer_image' not in facts['common']:
  1067. facts['common']['deployer_image'] = deployer_image
  1068. if 'etcd' in facts and 'etcd_image' not in facts['etcd']:
  1069. facts['etcd']['etcd_image'] = etcd_image
  1070. if 'master' in facts and 'master_image' not in facts['master']:
  1071. facts['master']['master_image'] = master_image
  1072. if 'node' in facts:
  1073. if 'node_image' not in facts['node']:
  1074. facts['node']['node_image'] = node_image
  1075. if 'ovs_image' not in facts['node']:
  1076. facts['node']['ovs_image'] = ovs_image
  1077. if safe_get_bool(facts['common']['is_containerized']):
  1078. facts['common']['admin_binary'] = '/usr/local/bin/oadm'
  1079. facts['common']['client_binary'] = '/usr/local/bin/oc'
  1080. base_version = get_openshift_version(facts, cli_image).split('-')[0]
  1081. facts['common']['image_tag'] = "v" + base_version
  1082. return facts
  1083. def set_installed_variant_rpm_facts(facts):
  1084. """ Set RPM facts of installed variant
  1085. Args:
  1086. facts (dict): existing facts
  1087. Returns:
  1088. dict: the facts dict updated with installed_variant_rpms
  1089. """
  1090. installed_rpms = []
  1091. for base_rpm in ['openshift', 'atomic-openshift', 'origin']:
  1092. optional_rpms = ['master', 'node', 'clients', 'sdn-ovs']
  1093. variant_rpms = [base_rpm] + \
  1094. ['{0}-{1}'.format(base_rpm, r) for r in optional_rpms] + \
  1095. ['tuned-profiles-%s-node' % base_rpm]
  1096. for rpm in variant_rpms:
  1097. exit_code, _, _ = module.run_command(['rpm', '-q', rpm])
  1098. if exit_code == 0:
  1099. installed_rpms.append(rpm)
  1100. facts['common']['installed_variant_rpms'] = installed_rpms
  1101. return facts
  1102. class OpenShiftFactsInternalError(Exception):
  1103. """Origin Facts Error"""
  1104. pass
  1105. class OpenShiftFactsUnsupportedRoleError(Exception):
  1106. """Origin Facts Unsupported Role Error"""
  1107. pass
  1108. class OpenShiftFactsFileWriteError(Exception):
  1109. """Origin Facts File Write Error"""
  1110. pass
  1111. class OpenShiftFactsMetadataUnavailableError(Exception):
  1112. """Origin Facts Metadata Unavailable Error"""
  1113. pass
  1114. class OpenShiftFacts(object):
  1115. """ Origin Facts
  1116. Attributes:
  1117. facts (dict): facts for the host
  1118. Args:
  1119. module (AnsibleModule): an AnsibleModule object
  1120. role (str): role for setting local facts
  1121. filename (str): local facts file to use
  1122. local_facts (dict): local facts to set
  1123. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1124. '.' notation ex: ['master.named_certificates']
  1125. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  1126. '.' notation ex: ['master.master_count']
  1127. Raises:
  1128. OpenShiftFactsUnsupportedRoleError:
  1129. """
  1130. known_roles = ['cloudprovider',
  1131. 'common',
  1132. 'docker',
  1133. 'etcd',
  1134. 'hosted',
  1135. 'master',
  1136. 'node']
  1137. # Disabling too-many-arguments, this should be cleaned up as a TODO item.
  1138. # pylint: disable=too-many-arguments
  1139. def __init__(self, role, filename, local_facts,
  1140. additive_facts_to_overwrite=None,
  1141. openshift_env=None,
  1142. openshift_env_structures=None,
  1143. protected_facts_to_overwrite=None):
  1144. self.changed = False
  1145. self.filename = filename
  1146. if role not in self.known_roles:
  1147. raise OpenShiftFactsUnsupportedRoleError(
  1148. "Role %s is not supported by this module" % role
  1149. )
  1150. self.role = role
  1151. self.system_facts = ansible_facts(module)
  1152. self.facts = self.generate_facts(local_facts,
  1153. additive_facts_to_overwrite,
  1154. openshift_env,
  1155. openshift_env_structures,
  1156. protected_facts_to_overwrite)
  1157. def generate_facts(self,
  1158. local_facts,
  1159. additive_facts_to_overwrite,
  1160. openshift_env,
  1161. openshift_env_structures,
  1162. protected_facts_to_overwrite):
  1163. """ Generate facts
  1164. Args:
  1165. local_facts (dict): local_facts for overriding generated defaults
  1166. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1167. '.' notation ex: ['master.named_certificates']
  1168. openshift_env (dict): openshift_env facts for overriding generated defaults
  1169. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  1170. '.' notation ex: ['master.master_count']
  1171. Returns:
  1172. dict: The generated facts
  1173. """
  1174. local_facts = self.init_local_facts(local_facts,
  1175. additive_facts_to_overwrite,
  1176. openshift_env,
  1177. openshift_env_structures,
  1178. protected_facts_to_overwrite)
  1179. roles = local_facts.keys()
  1180. if 'common' in local_facts and 'deployment_type' in local_facts['common']:
  1181. deployment_type = local_facts['common']['deployment_type']
  1182. else:
  1183. deployment_type = 'origin'
  1184. defaults = self.get_defaults(roles, deployment_type)
  1185. provider_facts = self.init_provider_facts()
  1186. facts = apply_provider_facts(defaults, provider_facts)
  1187. facts = merge_facts(facts,
  1188. local_facts,
  1189. additive_facts_to_overwrite,
  1190. protected_facts_to_overwrite)
  1191. facts['current_config'] = get_current_config(facts)
  1192. facts = set_url_facts_if_unset(facts)
  1193. facts = set_project_cfg_facts_if_unset(facts)
  1194. facts = set_flannel_facts_if_unset(facts)
  1195. facts = set_nuage_facts_if_unset(facts)
  1196. facts = set_node_schedulability(facts)
  1197. facts = set_master_selectors(facts)
  1198. facts = set_metrics_facts_if_unset(facts)
  1199. facts = set_identity_providers_if_unset(facts)
  1200. facts = set_sdn_facts_if_unset(facts, self.system_facts)
  1201. facts = set_deployment_facts_if_unset(facts)
  1202. facts = set_container_facts_if_unset(facts)
  1203. facts = build_kubelet_args(facts)
  1204. facts = build_controller_args(facts)
  1205. facts = build_api_server_args(facts)
  1206. facts = set_version_facts_if_unset(facts)
  1207. facts = set_manageiq_facts_if_unset(facts)
  1208. facts = set_aggregate_facts(facts)
  1209. facts = set_etcd_facts_if_unset(facts)
  1210. if not safe_get_bool(facts['common']['is_containerized']):
  1211. facts = set_installed_variant_rpm_facts(facts)
  1212. return dict(openshift=facts)
  1213. def get_defaults(self, roles, deployment_type):
  1214. """ Get default fact values
  1215. Args:
  1216. roles (list): list of roles for this host
  1217. Returns:
  1218. dict: The generated default facts
  1219. """
  1220. defaults = {}
  1221. ip_addr = self.system_facts['default_ipv4']['address']
  1222. exit_code, output, _ = module.run_command(['hostname', '-f'])
  1223. hostname_f = output.strip() if exit_code == 0 else ''
  1224. hostname_values = [hostname_f, self.system_facts['nodename'],
  1225. self.system_facts['fqdn']]
  1226. hostname = choose_hostname(hostname_values, ip_addr)
  1227. defaults['common'] = dict(use_openshift_sdn=True, ip=ip_addr,
  1228. public_ip=ip_addr,
  1229. deployment_type=deployment_type,
  1230. hostname=hostname,
  1231. public_hostname=hostname,
  1232. client_binary='oc', admin_binary='oadm',
  1233. dns_domain='cluster.local',
  1234. install_examples=True,
  1235. debug_level=2)
  1236. if 'master' in roles:
  1237. defaults['master'] = dict(api_use_ssl=True, api_port='8443',
  1238. controllers_port='8444',
  1239. console_use_ssl=True,
  1240. console_path='/console',
  1241. console_port='8443', etcd_use_ssl=True,
  1242. etcd_hosts='', etcd_port='4001',
  1243. portal_net='172.30.0.0/16',
  1244. embedded_etcd=True, embedded_kube=True,
  1245. embedded_dns=True, dns_port='53',
  1246. bind_addr='0.0.0.0',
  1247. session_max_seconds=3600,
  1248. session_name='ssn',
  1249. session_secrets_file='',
  1250. access_token_max_seconds=86400,
  1251. auth_token_max_seconds=500,
  1252. oauth_grant_method='auto')
  1253. if 'node' in roles:
  1254. defaults['node'] = dict(labels={}, annotations={},
  1255. iptables_sync_period='5s',
  1256. local_quota_per_fsgroup="",
  1257. set_node_ip=False)
  1258. if 'docker' in roles:
  1259. defaults['docker'] = dict(disable_push_dockerhub=False)
  1260. if 'cloudprovider' in roles:
  1261. defaults['cloudprovider'] = dict(kind=None)
  1262. defaults['hosted'] = dict(
  1263. registry=dict(
  1264. storage=dict(
  1265. kind=None,
  1266. volume=dict(
  1267. name='registry',
  1268. size='5Gi'
  1269. ),
  1270. nfs=dict(
  1271. directory='/exports',
  1272. options='*(rw,root_squash)'),
  1273. host=None,
  1274. access_modes=['ReadWriteMany'],
  1275. create_pv=True
  1276. )
  1277. )
  1278. )
  1279. return defaults
  1280. def guess_host_provider(self):
  1281. """ Guess the host provider
  1282. Returns:
  1283. dict: The generated default facts for the detected provider
  1284. """
  1285. # TODO: cloud provider facts should probably be submitted upstream
  1286. product_name = self.system_facts['product_name']
  1287. product_version = self.system_facts['product_version']
  1288. virt_type = self.system_facts['virtualization_type']
  1289. virt_role = self.system_facts['virtualization_role']
  1290. provider = None
  1291. metadata = None
  1292. # TODO: this is not exposed through module_utils/facts.py in ansible,
  1293. # need to create PR for ansible to expose it
  1294. bios_vendor = get_file_content(
  1295. '/sys/devices/virtual/dmi/id/bios_vendor'
  1296. )
  1297. if bios_vendor == 'Google':
  1298. provider = 'gce'
  1299. metadata_url = ('http://metadata.google.internal/'
  1300. 'computeMetadata/v1/?recursive=true')
  1301. headers = {'Metadata-Flavor': 'Google'}
  1302. metadata = get_provider_metadata(metadata_url, True, headers,
  1303. True)
  1304. # Filter sshKeys and serviceAccounts from gce metadata
  1305. if metadata:
  1306. metadata['project']['attributes'].pop('sshKeys', None)
  1307. metadata['instance'].pop('serviceAccounts', None)
  1308. elif (virt_type == 'xen' and virt_role == 'guest'
  1309. and re.match(r'.*\.amazon$', product_version)):
  1310. provider = 'aws'
  1311. metadata_url = 'http://169.254.169.254/latest/meta-data/'
  1312. metadata = get_provider_metadata(metadata_url)
  1313. elif re.search(r'OpenStack', product_name):
  1314. provider = 'openstack'
  1315. metadata_url = ('http://169.254.169.254/openstack/latest/'
  1316. 'meta_data.json')
  1317. metadata = get_provider_metadata(metadata_url, True, None,
  1318. True)
  1319. if metadata:
  1320. ec2_compat_url = 'http://169.254.169.254/latest/meta-data/'
  1321. metadata['ec2_compat'] = get_provider_metadata(
  1322. ec2_compat_url
  1323. )
  1324. # disable pylint maybe-no-member because overloaded use of
  1325. # the module name causes pylint to not detect that results
  1326. # is an array or hash
  1327. # pylint: disable=maybe-no-member
  1328. # Filter public_keys and random_seed from openstack metadata
  1329. metadata.pop('public_keys', None)
  1330. metadata.pop('random_seed', None)
  1331. if not metadata['ec2_compat']:
  1332. metadata = None
  1333. return dict(name=provider, metadata=metadata)
  1334. def init_provider_facts(self):
  1335. """ Initialize the provider facts
  1336. Returns:
  1337. dict: The normalized provider facts
  1338. """
  1339. provider_info = self.guess_host_provider()
  1340. provider_facts = normalize_provider_facts(
  1341. provider_info.get('name'),
  1342. provider_info.get('metadata')
  1343. )
  1344. return provider_facts
  1345. @staticmethod
  1346. def split_openshift_env_fact_keys(openshift_env_fact, openshift_env_structures):
  1347. """ Split openshift_env facts based on openshift_env structures.
  1348. Args:
  1349. openshift_env_fact (string): the openshift_env fact to split
  1350. ex: 'openshift_cloudprovider_openstack_auth_url'
  1351. openshift_env_structures (list): a list of structures to determine fact keys
  1352. ex: ['openshift.cloudprovider.openstack.*']
  1353. Returns:
  1354. list: a list of keys that represent the fact
  1355. ex: ['openshift', 'cloudprovider', 'openstack', 'auth_url']
  1356. """
  1357. # By default, we'll split an openshift_env fact by underscores.
  1358. fact_keys = openshift_env_fact.split('_')
  1359. # Determine if any of the provided variable structures match the fact.
  1360. matching_structure = None
  1361. if openshift_env_structures != None:
  1362. for structure in openshift_env_structures:
  1363. if re.match(structure, openshift_env_fact):
  1364. matching_structure = structure
  1365. # Fact didn't match any variable structures so return the default fact keys.
  1366. if matching_structure is None:
  1367. return fact_keys
  1368. final_keys = []
  1369. structure_keys = matching_structure.split('.')
  1370. for structure_key in structure_keys:
  1371. # Matched current key. Add to final keys.
  1372. if structure_key == fact_keys[structure_keys.index(structure_key)]:
  1373. final_keys.append(structure_key)
  1374. # Wildcard means we will be taking everything from here to the end of the fact.
  1375. elif structure_key == '*':
  1376. final_keys.append('_'.join(fact_keys[structure_keys.index(structure_key):]))
  1377. # Shouldn't have gotten here, return the fact keys.
  1378. else:
  1379. return fact_keys
  1380. return final_keys
  1381. # Disabling too-many-branches and too-many-locals.
  1382. # This should be cleaned up as a TODO item.
  1383. #pylint: disable=too-many-branches, too-many-locals
  1384. def init_local_facts(self, facts=None,
  1385. additive_facts_to_overwrite=None,
  1386. openshift_env=None,
  1387. openshift_env_structures=None,
  1388. protected_facts_to_overwrite=None):
  1389. """ Initialize the local facts
  1390. Args:
  1391. facts (dict): local facts to set
  1392. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1393. '.' notation ex: ['master.named_certificates']
  1394. openshift_env (dict): openshift env facts to set
  1395. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  1396. '.' notation ex: ['master.master_count']
  1397. Returns:
  1398. dict: The result of merging the provided facts with existing
  1399. local facts
  1400. """
  1401. changed = False
  1402. facts_to_set = dict()
  1403. if facts is not None:
  1404. facts_to_set[self.role] = facts
  1405. if openshift_env != {} and openshift_env != None:
  1406. for fact, value in openshift_env.iteritems():
  1407. oo_env_facts = dict()
  1408. current_level = oo_env_facts
  1409. keys = self.split_openshift_env_fact_keys(fact, openshift_env_structures)[1:]
  1410. if len(keys) > 0 and keys[0] != self.role:
  1411. continue
  1412. for key in keys:
  1413. if key == keys[-1]:
  1414. current_level[key] = value
  1415. elif key not in current_level:
  1416. current_level[key] = dict()
  1417. current_level = current_level[key]
  1418. facts_to_set = merge_facts(orig=facts_to_set,
  1419. new=oo_env_facts,
  1420. additive_facts_to_overwrite=[],
  1421. protected_facts_to_overwrite=[])
  1422. local_facts = get_local_facts_from_file(self.filename)
  1423. migrated_facts = migrate_local_facts(local_facts)
  1424. new_local_facts = merge_facts(migrated_facts,
  1425. facts_to_set,
  1426. additive_facts_to_overwrite,
  1427. protected_facts_to_overwrite)
  1428. if 'docker' in new_local_facts:
  1429. # remove duplicate and empty strings from registry lists
  1430. for cat in ['additional', 'blocked', 'insecure']:
  1431. key = '{0}_registries'.format(cat)
  1432. if key in new_local_facts['docker']:
  1433. val = new_local_facts['docker'][key]
  1434. if isinstance(val, basestring):
  1435. val = [x.strip() for x in val.split(',')]
  1436. new_local_facts['docker'][key] = list(set(val) - set(['']))
  1437. for facts in new_local_facts.values():
  1438. keys_to_delete = []
  1439. if isinstance(facts, dict):
  1440. for fact, value in facts.iteritems():
  1441. if value == "" or value is None:
  1442. keys_to_delete.append(fact)
  1443. for key in keys_to_delete:
  1444. del facts[key]
  1445. if new_local_facts != local_facts:
  1446. self.validate_local_facts(new_local_facts)
  1447. changed = True
  1448. if not module.check_mode:
  1449. save_local_facts(self.filename, new_local_facts)
  1450. self.changed = changed
  1451. return new_local_facts
  1452. def validate_local_facts(self, facts=None):
  1453. """ Validate local facts
  1454. Args:
  1455. facts (dict): local facts to validate
  1456. """
  1457. invalid_facts = dict()
  1458. invalid_facts = self.validate_master_facts(facts, invalid_facts)
  1459. if invalid_facts:
  1460. msg = 'Invalid facts detected:\n'
  1461. for key in invalid_facts.keys():
  1462. msg += '{0}: {1}\n'.format(key, invalid_facts[key])
  1463. module.fail_json(msg=msg,
  1464. changed=self.changed)
  1465. # disabling pylint errors for line-too-long since we're dealing
  1466. # with best effort reduction of error messages here.
  1467. # disabling errors for too-many-branches since we require checking
  1468. # many conditions.
  1469. # pylint: disable=line-too-long, too-many-branches
  1470. @staticmethod
  1471. def validate_master_facts(facts, invalid_facts):
  1472. """ Validate master facts
  1473. Args:
  1474. facts (dict): local facts to validate
  1475. invalid_facts (dict): collected invalid_facts
  1476. Returns:
  1477. dict: Invalid facts
  1478. """
  1479. if 'master' in facts:
  1480. # openshift.master.session_auth_secrets
  1481. if 'session_auth_secrets' in facts['master']:
  1482. session_auth_secrets = facts['master']['session_auth_secrets']
  1483. if not issubclass(type(session_auth_secrets), list):
  1484. invalid_facts['session_auth_secrets'] = 'Expects session_auth_secrets is a list.'
  1485. elif 'session_encryption_secrets' not in facts['master']:
  1486. invalid_facts['session_auth_secrets'] = ('openshift_master_session_encryption secrets must be set '
  1487. 'if openshift_master_session_auth_secrets is provided.')
  1488. elif len(session_auth_secrets) != len(facts['master']['session_encryption_secrets']):
  1489. invalid_facts['session_auth_secrets'] = ('openshift_master_session_auth_secrets and '
  1490. 'openshift_master_session_encryption_secrets must be '
  1491. 'equal length.')
  1492. else:
  1493. for secret in session_auth_secrets:
  1494. if len(secret) < 32:
  1495. invalid_facts['session_auth_secrets'] = ('Invalid secret in session_auth_secrets. '
  1496. 'Secrets must be at least 32 characters in length.')
  1497. # openshift.master.session_encryption_secrets
  1498. if 'session_encryption_secrets' in facts['master']:
  1499. session_encryption_secrets = facts['master']['session_encryption_secrets']
  1500. if not issubclass(type(session_encryption_secrets), list):
  1501. invalid_facts['session_encryption_secrets'] = 'Expects session_encryption_secrets is a list.'
  1502. elif 'session_auth_secrets' not in facts['master']:
  1503. invalid_facts['session_encryption_secrets'] = ('openshift_master_session_auth_secrets must be '
  1504. 'set if openshift_master_session_encryption_secrets '
  1505. 'is provided.')
  1506. else:
  1507. for secret in session_encryption_secrets:
  1508. if len(secret) not in [16, 24, 32]:
  1509. invalid_facts['session_encryption_secrets'] = ('Invalid secret in session_encryption_secrets. '
  1510. 'Secrets must be 16, 24, or 32 characters in length.')
  1511. return invalid_facts
  1512. def main():
  1513. """ main """
  1514. # disabling pylint errors for global-variable-undefined and invalid-name
  1515. # for 'global module' usage, since it is required to use ansible_facts
  1516. # pylint: disable=global-variable-undefined, invalid-name
  1517. global module
  1518. module = AnsibleModule(
  1519. argument_spec=dict(
  1520. role=dict(default='common', required=False,
  1521. choices=OpenShiftFacts.known_roles),
  1522. local_facts=dict(default=None, type='dict', required=False),
  1523. additive_facts_to_overwrite=dict(default=[], type='list', required=False),
  1524. openshift_env=dict(default={}, type='dict', required=False),
  1525. openshift_env_structures=dict(default=[], type='list', required=False),
  1526. protected_facts_to_overwrite=dict(default=[], type='list', required=False),
  1527. ),
  1528. supports_check_mode=True,
  1529. add_file_common_args=True,
  1530. )
  1531. role = module.params['role']
  1532. local_facts = module.params['local_facts']
  1533. additive_facts_to_overwrite = module.params['additive_facts_to_overwrite']
  1534. openshift_env = module.params['openshift_env']
  1535. openshift_env_structures = module.params['openshift_env_structures']
  1536. protected_facts_to_overwrite = module.params['protected_facts_to_overwrite']
  1537. fact_file = '/etc/ansible/facts.d/openshift.fact'
  1538. openshift_facts = OpenShiftFacts(role,
  1539. fact_file,
  1540. local_facts,
  1541. additive_facts_to_overwrite,
  1542. openshift_env,
  1543. openshift_env_structures,
  1544. protected_facts_to_overwrite)
  1545. file_params = module.params.copy()
  1546. file_params['path'] = fact_file
  1547. file_args = module.load_file_common_arguments(file_params)
  1548. changed = module.set_fs_attributes_if_different(file_args,
  1549. openshift_facts.changed)
  1550. return module.exit_json(changed=changed,
  1551. ansible_facts=openshift_facts.facts)
  1552. # ignore pylint errors related to the module_utils import
  1553. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import
  1554. # import module snippets
  1555. from ansible.module_utils.basic import *
  1556. from ansible.module_utils.facts import *
  1557. from ansible.module_utils.urls import *
  1558. if __name__ == '__main__':
  1559. main()