oc_version.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442
  1. #!/usr/bin/env python
  2. # pylint: disable=missing-docstring
  3. # flake8: noqa: T001
  4. # ___ ___ _ _ ___ ___ _ _____ ___ ___
  5. # / __| __| \| | __| _ \ /_\_ _| __| \
  6. # | (_ | _|| .` | _|| / / _ \| | | _|| |) |
  7. # \___|___|_|\_|___|_|_\/_/_\_\_|_|___|___/_ _____
  8. # | \ / _ \ | \| |/ _ \_ _| | __| \_ _|_ _|
  9. # | |) | (_) | | .` | (_) || | | _|| |) | | | |
  10. # |___/ \___/ |_|\_|\___/ |_| |___|___/___| |_|
  11. #
  12. # Copyright 2016 Red Hat, Inc. and/or its affiliates
  13. # and other contributors as indicated by the @author tags.
  14. #
  15. # Licensed under the Apache License, Version 2.0 (the "License");
  16. # you may not use this file except in compliance with the License.
  17. # You may obtain a copy of the License at
  18. #
  19. # http://www.apache.org/licenses/LICENSE-2.0
  20. #
  21. # Unless required by applicable law or agreed to in writing, software
  22. # distributed under the License is distributed on an "AS IS" BASIS,
  23. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24. # See the License for the specific language governing permissions and
  25. # limitations under the License.
  26. #
  27. # -*- -*- -*- Begin included fragment: lib/import.py -*- -*- -*-
  28. '''
  29. OpenShiftCLI class that wraps the oc commands in a subprocess
  30. '''
  31. # pylint: disable=too-many-lines
  32. from __future__ import print_function
  33. import atexit
  34. import copy
  35. import json
  36. import os
  37. import re
  38. import shutil
  39. import subprocess
  40. import tempfile
  41. # pylint: disable=import-error
  42. try:
  43. import ruamel.yaml as yaml
  44. except ImportError:
  45. import yaml
  46. from ansible.module_utils.basic import AnsibleModule
  47. # -*- -*- -*- End included fragment: lib/import.py -*- -*- -*-
  48. # -*- -*- -*- Begin included fragment: doc/version -*- -*- -*-
  49. DOCUMENTATION = '''
  50. ---
  51. module: oc_version
  52. short_description: Return the current openshift version
  53. description:
  54. - Return the openshift installed version. `oc version`
  55. options:
  56. state:
  57. description:
  58. - Currently list is only supported state.
  59. required: true
  60. default: list
  61. choices: ["list"]
  62. aliases: []
  63. kubeconfig:
  64. description:
  65. - The path for the kubeconfig file to use for authentication
  66. required: false
  67. default: /etc/origin/master/admin.kubeconfig
  68. aliases: []
  69. debug:
  70. description:
  71. - Turn on debug output.
  72. required: false
  73. default: False
  74. aliases: []
  75. author:
  76. - "Kenny Woodson <kwoodson@redhat.com>"
  77. extends_documentation_fragment: []
  78. '''
  79. EXAMPLES = '''
  80. oc_version:
  81. - name: get oc version
  82. oc_version:
  83. register: oc_version
  84. '''
  85. # -*- -*- -*- End included fragment: doc/version -*- -*- -*-
  86. # -*- -*- -*- Begin included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  87. class YeditException(Exception): # pragma: no cover
  88. ''' Exception class for Yedit '''
  89. pass
  90. # pylint: disable=too-many-public-methods
  91. class Yedit(object): # pragma: no cover
  92. ''' Class to modify yaml files '''
  93. re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
  94. re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z%s/_-]+)"
  95. com_sep = set(['.', '#', '|', ':'])
  96. # pylint: disable=too-many-arguments
  97. def __init__(self,
  98. filename=None,
  99. content=None,
  100. content_type='yaml',
  101. separator='.',
  102. backup=False):
  103. self.content = content
  104. self._separator = separator
  105. self.filename = filename
  106. self.__yaml_dict = content
  107. self.content_type = content_type
  108. self.backup = backup
  109. self.load(content_type=self.content_type)
  110. if self.__yaml_dict is None:
  111. self.__yaml_dict = {}
  112. @property
  113. def separator(self):
  114. ''' getter method for separator '''
  115. return self._separator
  116. @separator.setter
  117. def separator(self, inc_sep):
  118. ''' setter method for separator '''
  119. self._separator = inc_sep
  120. @property
  121. def yaml_dict(self):
  122. ''' getter method for yaml_dict '''
  123. return self.__yaml_dict
  124. @yaml_dict.setter
  125. def yaml_dict(self, value):
  126. ''' setter method for yaml_dict '''
  127. self.__yaml_dict = value
  128. @staticmethod
  129. def parse_key(key, sep='.'):
  130. '''parse the key allowing the appropriate separator'''
  131. common_separators = list(Yedit.com_sep - set([sep]))
  132. return re.findall(Yedit.re_key.format(''.join(common_separators)), key)
  133. @staticmethod
  134. def valid_key(key, sep='.'):
  135. '''validate the incoming key'''
  136. common_separators = list(Yedit.com_sep - set([sep]))
  137. if not re.match(Yedit.re_valid_key.format(''.join(common_separators)), key):
  138. return False
  139. return True
  140. @staticmethod
  141. def remove_entry(data, key, sep='.'):
  142. ''' remove data at location key '''
  143. if key == '' and isinstance(data, dict):
  144. data.clear()
  145. return True
  146. elif key == '' and isinstance(data, list):
  147. del data[:]
  148. return True
  149. if not (key and Yedit.valid_key(key, sep)) and \
  150. isinstance(data, (list, dict)):
  151. return None
  152. key_indexes = Yedit.parse_key(key, sep)
  153. for arr_ind, dict_key in key_indexes[:-1]:
  154. if dict_key and isinstance(data, dict):
  155. data = data.get(dict_key)
  156. elif (arr_ind and isinstance(data, list) and
  157. int(arr_ind) <= len(data) - 1):
  158. data = data[int(arr_ind)]
  159. else:
  160. return None
  161. # process last index for remove
  162. # expected list entry
  163. if key_indexes[-1][0]:
  164. if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  165. del data[int(key_indexes[-1][0])]
  166. return True
  167. # expected dict entry
  168. elif key_indexes[-1][1]:
  169. if isinstance(data, dict):
  170. del data[key_indexes[-1][1]]
  171. return True
  172. @staticmethod
  173. def add_entry(data, key, item=None, sep='.'):
  174. ''' Get an item from a dictionary with key notation a.b.c
  175. d = {'a': {'b': 'c'}}}
  176. key = a#b
  177. return c
  178. '''
  179. if key == '':
  180. pass
  181. elif (not (key and Yedit.valid_key(key, sep)) and
  182. isinstance(data, (list, dict))):
  183. return None
  184. key_indexes = Yedit.parse_key(key, sep)
  185. for arr_ind, dict_key in key_indexes[:-1]:
  186. if dict_key:
  187. if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
  188. data = data[dict_key]
  189. continue
  190. elif data and not isinstance(data, dict):
  191. raise YeditException("Unexpected item type found while going through key " +
  192. "path: {} (at key: {})".format(key, dict_key))
  193. data[dict_key] = {}
  194. data = data[dict_key]
  195. elif (arr_ind and isinstance(data, list) and
  196. int(arr_ind) <= len(data) - 1):
  197. data = data[int(arr_ind)]
  198. else:
  199. raise YeditException("Unexpected item type found while going through key path: {}".format(key))
  200. if key == '':
  201. data = item
  202. # process last index for add
  203. # expected list entry
  204. elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  205. data[int(key_indexes[-1][0])] = item
  206. # expected dict entry
  207. elif key_indexes[-1][1] and isinstance(data, dict):
  208. data[key_indexes[-1][1]] = item
  209. # didn't add/update to an existing list, nor add/update key to a dict
  210. # so we must have been provided some syntax like a.b.c[<int>] = "data" for a
  211. # non-existent array
  212. else:
  213. raise YeditException("Error adding to object at path: {}".format(key))
  214. return data
  215. @staticmethod
  216. def get_entry(data, key, sep='.'):
  217. ''' Get an item from a dictionary with key notation a.b.c
  218. d = {'a': {'b': 'c'}}}
  219. key = a.b
  220. return c
  221. '''
  222. if key == '':
  223. pass
  224. elif (not (key and Yedit.valid_key(key, sep)) and
  225. isinstance(data, (list, dict))):
  226. return None
  227. key_indexes = Yedit.parse_key(key, sep)
  228. for arr_ind, dict_key in key_indexes:
  229. if dict_key and isinstance(data, dict):
  230. data = data.get(dict_key)
  231. elif (arr_ind and isinstance(data, list) and
  232. int(arr_ind) <= len(data) - 1):
  233. data = data[int(arr_ind)]
  234. else:
  235. return None
  236. return data
  237. @staticmethod
  238. def _write(filename, contents):
  239. ''' Actually write the file contents to disk. This helps with mocking. '''
  240. tmp_filename = filename + '.yedit'
  241. with open(tmp_filename, 'w') as yfd:
  242. yfd.write(contents)
  243. os.rename(tmp_filename, filename)
  244. def write(self):
  245. ''' write to file '''
  246. if not self.filename:
  247. raise YeditException('Please specify a filename.')
  248. if self.backup and self.file_exists():
  249. shutil.copy(self.filename, self.filename + '.orig')
  250. # Try to set format attributes if supported
  251. try:
  252. self.yaml_dict.fa.set_block_style()
  253. except AttributeError:
  254. pass
  255. # Try to use RoundTripDumper if supported.
  256. try:
  257. Yedit._write(self.filename, yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
  258. except AttributeError:
  259. Yedit._write(self.filename, yaml.safe_dump(self.yaml_dict, default_flow_style=False))
  260. return (True, self.yaml_dict)
  261. def read(self):
  262. ''' read from file '''
  263. # check if it exists
  264. if self.filename is None or not self.file_exists():
  265. return None
  266. contents = None
  267. with open(self.filename) as yfd:
  268. contents = yfd.read()
  269. return contents
  270. def file_exists(self):
  271. ''' return whether file exists '''
  272. if os.path.exists(self.filename):
  273. return True
  274. return False
  275. def load(self, content_type='yaml'):
  276. ''' return yaml file '''
  277. contents = self.read()
  278. if not contents and not self.content:
  279. return None
  280. if self.content:
  281. if isinstance(self.content, dict):
  282. self.yaml_dict = self.content
  283. return self.yaml_dict
  284. elif isinstance(self.content, str):
  285. contents = self.content
  286. # check if it is yaml
  287. try:
  288. if content_type == 'yaml' and contents:
  289. # Try to set format attributes if supported
  290. try:
  291. self.yaml_dict.fa.set_block_style()
  292. except AttributeError:
  293. pass
  294. # Try to use RoundTripLoader if supported.
  295. try:
  296. self.yaml_dict = yaml.safe_load(contents, yaml.RoundTripLoader)
  297. except AttributeError:
  298. self.yaml_dict = yaml.safe_load(contents)
  299. # Try to set format attributes if supported
  300. try:
  301. self.yaml_dict.fa.set_block_style()
  302. except AttributeError:
  303. pass
  304. elif content_type == 'json' and contents:
  305. self.yaml_dict = json.loads(contents)
  306. except yaml.YAMLError as err:
  307. # Error loading yaml or json
  308. raise YeditException('Problem with loading yaml file. {}'.format(err))
  309. return self.yaml_dict
  310. def get(self, key):
  311. ''' get a specified key'''
  312. try:
  313. entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
  314. except KeyError:
  315. entry = None
  316. return entry
  317. def pop(self, path, key_or_item):
  318. ''' remove a key, value pair from a dict or an item for a list'''
  319. try:
  320. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  321. except KeyError:
  322. entry = None
  323. if entry is None:
  324. return (False, self.yaml_dict)
  325. if isinstance(entry, dict):
  326. # AUDIT:maybe-no-member makes sense due to fuzzy types
  327. # pylint: disable=maybe-no-member
  328. if key_or_item in entry:
  329. entry.pop(key_or_item)
  330. return (True, self.yaml_dict)
  331. return (False, self.yaml_dict)
  332. elif isinstance(entry, list):
  333. # AUDIT:maybe-no-member makes sense due to fuzzy types
  334. # pylint: disable=maybe-no-member
  335. ind = None
  336. try:
  337. ind = entry.index(key_or_item)
  338. except ValueError:
  339. return (False, self.yaml_dict)
  340. entry.pop(ind)
  341. return (True, self.yaml_dict)
  342. return (False, self.yaml_dict)
  343. def delete(self, path):
  344. ''' remove path from a dict'''
  345. try:
  346. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  347. except KeyError:
  348. entry = None
  349. if entry is None:
  350. return (False, self.yaml_dict)
  351. result = Yedit.remove_entry(self.yaml_dict, path, self.separator)
  352. if not result:
  353. return (False, self.yaml_dict)
  354. return (True, self.yaml_dict)
  355. def exists(self, path, value):
  356. ''' check if value exists at path'''
  357. try:
  358. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  359. except KeyError:
  360. entry = None
  361. if isinstance(entry, list):
  362. if value in entry:
  363. return True
  364. return False
  365. elif isinstance(entry, dict):
  366. if isinstance(value, dict):
  367. rval = False
  368. for key, val in value.items():
  369. if entry[key] != val:
  370. rval = False
  371. break
  372. else:
  373. rval = True
  374. return rval
  375. return value in entry
  376. return entry == value
  377. def append(self, path, value):
  378. '''append value to a list'''
  379. try:
  380. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  381. except KeyError:
  382. entry = None
  383. if entry is None:
  384. self.put(path, [])
  385. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  386. if not isinstance(entry, list):
  387. return (False, self.yaml_dict)
  388. # AUDIT:maybe-no-member makes sense due to loading data from
  389. # a serialized format.
  390. # pylint: disable=maybe-no-member
  391. entry.append(value)
  392. return (True, self.yaml_dict)
  393. # pylint: disable=too-many-arguments
  394. def update(self, path, value, index=None, curr_value=None):
  395. ''' put path, value into a dict '''
  396. try:
  397. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  398. except KeyError:
  399. entry = None
  400. if isinstance(entry, dict):
  401. # AUDIT:maybe-no-member makes sense due to fuzzy types
  402. # pylint: disable=maybe-no-member
  403. if not isinstance(value, dict):
  404. raise YeditException('Cannot replace key, value entry in dict with non-dict type. ' +
  405. 'value=[{}] type=[{}]'.format(value, type(value)))
  406. entry.update(value)
  407. return (True, self.yaml_dict)
  408. elif isinstance(entry, list):
  409. # AUDIT:maybe-no-member makes sense due to fuzzy types
  410. # pylint: disable=maybe-no-member
  411. ind = None
  412. if curr_value:
  413. try:
  414. ind = entry.index(curr_value)
  415. except ValueError:
  416. return (False, self.yaml_dict)
  417. elif index is not None:
  418. ind = index
  419. if ind is not None and entry[ind] != value:
  420. entry[ind] = value
  421. return (True, self.yaml_dict)
  422. # see if it exists in the list
  423. try:
  424. ind = entry.index(value)
  425. except ValueError:
  426. # doesn't exist, append it
  427. entry.append(value)
  428. return (True, self.yaml_dict)
  429. # already exists, return
  430. if ind is not None:
  431. return (False, self.yaml_dict)
  432. return (False, self.yaml_dict)
  433. def put(self, path, value):
  434. ''' put path, value into a dict '''
  435. try:
  436. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  437. except KeyError:
  438. entry = None
  439. if entry == value:
  440. return (False, self.yaml_dict)
  441. # deepcopy didn't work
  442. # Try to use ruamel.yaml and fallback to pyyaml
  443. try:
  444. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  445. default_flow_style=False),
  446. yaml.RoundTripLoader)
  447. except AttributeError:
  448. tmp_copy = copy.deepcopy(self.yaml_dict)
  449. # set the format attributes if available
  450. try:
  451. tmp_copy.fa.set_block_style()
  452. except AttributeError:
  453. pass
  454. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  455. if result is None:
  456. return (False, self.yaml_dict)
  457. # When path equals "" it is a special case.
  458. # "" refers to the root of the document
  459. # Only update the root path (entire document) when its a list or dict
  460. if path == '':
  461. if isinstance(result, list) or isinstance(result, dict):
  462. self.yaml_dict = result
  463. return (True, self.yaml_dict)
  464. return (False, self.yaml_dict)
  465. self.yaml_dict = tmp_copy
  466. return (True, self.yaml_dict)
  467. def create(self, path, value):
  468. ''' create a yaml file '''
  469. if not self.file_exists():
  470. # deepcopy didn't work
  471. # Try to use ruamel.yaml and fallback to pyyaml
  472. try:
  473. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  474. default_flow_style=False),
  475. yaml.RoundTripLoader)
  476. except AttributeError:
  477. tmp_copy = copy.deepcopy(self.yaml_dict)
  478. # set the format attributes if available
  479. try:
  480. tmp_copy.fa.set_block_style()
  481. except AttributeError:
  482. pass
  483. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  484. if result is not None:
  485. self.yaml_dict = tmp_copy
  486. return (True, self.yaml_dict)
  487. return (False, self.yaml_dict)
  488. @staticmethod
  489. def get_curr_value(invalue, val_type):
  490. '''return the current value'''
  491. if invalue is None:
  492. return None
  493. curr_value = invalue
  494. if val_type == 'yaml':
  495. curr_value = yaml.load(invalue)
  496. elif val_type == 'json':
  497. curr_value = json.loads(invalue)
  498. return curr_value
  499. @staticmethod
  500. def parse_value(inc_value, vtype=''):
  501. '''determine value type passed'''
  502. true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE',
  503. 'on', 'On', 'ON', ]
  504. false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE',
  505. 'off', 'Off', 'OFF']
  506. # It came in as a string but you didn't specify value_type as string
  507. # we will convert to bool if it matches any of the above cases
  508. if isinstance(inc_value, str) and 'bool' in vtype:
  509. if inc_value not in true_bools and inc_value not in false_bools:
  510. raise YeditException('Not a boolean type. str=[{}] vtype=[{}]'.format(inc_value, vtype))
  511. elif isinstance(inc_value, bool) and 'str' in vtype:
  512. inc_value = str(inc_value)
  513. # There is a special case where '' will turn into None after yaml loading it so skip
  514. if isinstance(inc_value, str) and inc_value == '':
  515. pass
  516. # If vtype is not str then go ahead and attempt to yaml load it.
  517. elif isinstance(inc_value, str) and 'str' not in vtype:
  518. try:
  519. inc_value = yaml.safe_load(inc_value)
  520. except Exception:
  521. raise YeditException('Could not determine type of incoming value. ' +
  522. 'value=[{}] vtype=[{}]'.format(type(inc_value), vtype))
  523. return inc_value
  524. @staticmethod
  525. def process_edits(edits, yamlfile):
  526. '''run through a list of edits and process them one-by-one'''
  527. results = []
  528. for edit in edits:
  529. value = Yedit.parse_value(edit['value'], edit.get('value_type', ''))
  530. if edit.get('action') == 'update':
  531. # pylint: disable=line-too-long
  532. curr_value = Yedit.get_curr_value(
  533. Yedit.parse_value(edit.get('curr_value')),
  534. edit.get('curr_value_format'))
  535. rval = yamlfile.update(edit['key'],
  536. value,
  537. edit.get('index'),
  538. curr_value)
  539. elif edit.get('action') == 'append':
  540. rval = yamlfile.append(edit['key'], value)
  541. else:
  542. rval = yamlfile.put(edit['key'], value)
  543. if rval[0]:
  544. results.append({'key': edit['key'], 'edit': rval[1]})
  545. return {'changed': len(results) > 0, 'results': results}
  546. # pylint: disable=too-many-return-statements,too-many-branches
  547. @staticmethod
  548. def run_ansible(params):
  549. '''perform the idempotent crud operations'''
  550. yamlfile = Yedit(filename=params['src'],
  551. backup=params['backup'],
  552. separator=params['separator'])
  553. state = params['state']
  554. if params['src']:
  555. rval = yamlfile.load()
  556. if yamlfile.yaml_dict is None and state != 'present':
  557. return {'failed': True,
  558. 'msg': 'Error opening file [{}]. Verify that the '.format(params['src']) +
  559. 'file exists, that it is has correct permissions, and is valid yaml.'}
  560. if state == 'list':
  561. if params['content']:
  562. content = Yedit.parse_value(params['content'], params['content_type'])
  563. yamlfile.yaml_dict = content
  564. if params['key']:
  565. rval = yamlfile.get(params['key']) or {}
  566. return {'changed': False, 'result': rval, 'state': state}
  567. elif state == 'absent':
  568. if params['content']:
  569. content = Yedit.parse_value(params['content'], params['content_type'])
  570. yamlfile.yaml_dict = content
  571. if params['update']:
  572. rval = yamlfile.pop(params['key'], params['value'])
  573. else:
  574. rval = yamlfile.delete(params['key'])
  575. if rval[0] and params['src']:
  576. yamlfile.write()
  577. return {'changed': rval[0], 'result': rval[1], 'state': state}
  578. elif state == 'present':
  579. # check if content is different than what is in the file
  580. if params['content']:
  581. content = Yedit.parse_value(params['content'], params['content_type'])
  582. # We had no edits to make and the contents are the same
  583. if yamlfile.yaml_dict == content and \
  584. params['value'] is None:
  585. return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
  586. yamlfile.yaml_dict = content
  587. # If we were passed a key, value then
  588. # we enapsulate it in a list and process it
  589. # Key, Value passed to the module : Converted to Edits list #
  590. edits = []
  591. _edit = {}
  592. if params['value'] is not None:
  593. _edit['value'] = params['value']
  594. _edit['value_type'] = params['value_type']
  595. _edit['key'] = params['key']
  596. if params['update']:
  597. _edit['action'] = 'update'
  598. _edit['curr_value'] = params['curr_value']
  599. _edit['curr_value_format'] = params['curr_value_format']
  600. _edit['index'] = params['index']
  601. elif params['append']:
  602. _edit['action'] = 'append'
  603. edits.append(_edit)
  604. elif params['edits'] is not None:
  605. edits = params['edits']
  606. if edits:
  607. results = Yedit.process_edits(edits, yamlfile)
  608. # if there were changes and a src provided to us we need to write
  609. if results['changed'] and params['src']:
  610. yamlfile.write()
  611. return {'changed': results['changed'], 'result': results['results'], 'state': state}
  612. # no edits to make
  613. if params['src']:
  614. # pylint: disable=redefined-variable-type
  615. rval = yamlfile.write()
  616. return {'changed': rval[0],
  617. 'result': rval[1],
  618. 'state': state}
  619. # We were passed content but no src, key or value, or edits. Return contents in memory
  620. return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
  621. return {'failed': True, 'msg': 'Unkown state passed'}
  622. # -*- -*- -*- End included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  623. # -*- -*- -*- Begin included fragment: lib/base.py -*- -*- -*-
  624. # pylint: disable=too-many-lines
  625. # noqa: E301,E302,E303,T001
  626. class OpenShiftCLIError(Exception):
  627. '''Exception class for openshiftcli'''
  628. pass
  629. ADDITIONAL_PATH_LOOKUPS = ['/usr/local/bin', os.path.expanduser('~/bin')]
  630. def locate_oc_binary():
  631. ''' Find and return oc binary file '''
  632. # https://github.com/openshift/openshift-ansible/issues/3410
  633. # oc can be in /usr/local/bin in some cases, but that may not
  634. # be in $PATH due to ansible/sudo
  635. paths = os.environ.get("PATH", os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS
  636. oc_binary = 'oc'
  637. # Use shutil.which if it is available, otherwise fallback to a naive path search
  638. try:
  639. which_result = shutil.which(oc_binary, path=os.pathsep.join(paths))
  640. if which_result is not None:
  641. oc_binary = which_result
  642. except AttributeError:
  643. for path in paths:
  644. if os.path.exists(os.path.join(path, oc_binary)):
  645. oc_binary = os.path.join(path, oc_binary)
  646. break
  647. return oc_binary
  648. # pylint: disable=too-few-public-methods
  649. class OpenShiftCLI(object):
  650. ''' Class to wrap the command line tools '''
  651. def __init__(self,
  652. namespace,
  653. kubeconfig='/etc/origin/master/admin.kubeconfig',
  654. verbose=False,
  655. all_namespaces=False):
  656. ''' Constructor for OpenshiftCLI '''
  657. self.namespace = namespace
  658. self.verbose = verbose
  659. self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
  660. self.all_namespaces = all_namespaces
  661. self.oc_binary = locate_oc_binary()
  662. # Pylint allows only 5 arguments to be passed.
  663. # pylint: disable=too-many-arguments
  664. def _replace_content(self, resource, rname, content, force=False, sep='.'):
  665. ''' replace the current object with the content '''
  666. res = self._get(resource, rname)
  667. if not res['results']:
  668. return res
  669. fname = Utils.create_tmpfile(rname + '-')
  670. yed = Yedit(fname, res['results'][0], separator=sep)
  671. changes = []
  672. for key, value in content.items():
  673. changes.append(yed.put(key, value))
  674. if any([change[0] for change in changes]):
  675. yed.write()
  676. atexit.register(Utils.cleanup, [fname])
  677. return self._replace(fname, force)
  678. return {'returncode': 0, 'updated': False}
  679. def _replace(self, fname, force=False):
  680. '''replace the current object with oc replace'''
  681. cmd = ['replace', '-f', fname]
  682. if force:
  683. cmd.append('--force')
  684. return self.openshift_cmd(cmd)
  685. def _create_from_content(self, rname, content):
  686. '''create a temporary file and then call oc create on it'''
  687. fname = Utils.create_tmpfile(rname + '-')
  688. yed = Yedit(fname, content=content)
  689. yed.write()
  690. atexit.register(Utils.cleanup, [fname])
  691. return self._create(fname)
  692. def _create(self, fname):
  693. '''call oc create on a filename'''
  694. return self.openshift_cmd(['create', '-f', fname])
  695. def _delete(self, resource, rname, selector=None):
  696. '''call oc delete on a resource'''
  697. cmd = ['delete', resource, rname]
  698. if selector:
  699. cmd.append('--selector=%s' % selector)
  700. return self.openshift_cmd(cmd)
  701. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  702. '''process a template
  703. template_name: the name of the template to process
  704. create: whether to send to oc create after processing
  705. params: the parameters for the template
  706. template_data: the incoming template's data; instead of a file
  707. '''
  708. cmd = ['process']
  709. if template_data:
  710. cmd.extend(['-f', '-'])
  711. else:
  712. cmd.append(template_name)
  713. if params:
  714. param_str = ["%s=%s" % (key, value) for key, value in params.items()]
  715. cmd.append('-v')
  716. cmd.extend(param_str)
  717. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  718. if results['returncode'] != 0 or not create:
  719. return results
  720. fname = Utils.create_tmpfile(template_name + '-')
  721. yed = Yedit(fname, results['results'])
  722. yed.write()
  723. atexit.register(Utils.cleanup, [fname])
  724. return self.openshift_cmd(['create', '-f', fname])
  725. def _get(self, resource, rname=None, selector=None):
  726. '''return a resource by name '''
  727. cmd = ['get', resource]
  728. if selector:
  729. cmd.append('--selector=%s' % selector)
  730. elif rname:
  731. cmd.append(rname)
  732. cmd.extend(['-o', 'json'])
  733. rval = self.openshift_cmd(cmd, output=True)
  734. # Ensure results are retuned in an array
  735. if 'items' in rval:
  736. rval['results'] = rval['items']
  737. elif not isinstance(rval['results'], list):
  738. rval['results'] = [rval['results']]
  739. return rval
  740. def _schedulable(self, node=None, selector=None, schedulable=True):
  741. ''' perform oadm manage-node scheduable '''
  742. cmd = ['manage-node']
  743. if node:
  744. cmd.extend(node)
  745. else:
  746. cmd.append('--selector=%s' % selector)
  747. cmd.append('--schedulable=%s' % schedulable)
  748. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  749. def _list_pods(self, node=None, selector=None, pod_selector=None):
  750. ''' perform oadm list pods
  751. node: the node in which to list pods
  752. selector: the label selector filter if provided
  753. pod_selector: the pod selector filter if provided
  754. '''
  755. cmd = ['manage-node']
  756. if node:
  757. cmd.extend(node)
  758. else:
  759. cmd.append('--selector=%s' % selector)
  760. if pod_selector:
  761. cmd.append('--pod-selector=%s' % pod_selector)
  762. cmd.extend(['--list-pods', '-o', 'json'])
  763. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  764. # pylint: disable=too-many-arguments
  765. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  766. ''' perform oadm manage-node evacuate '''
  767. cmd = ['manage-node']
  768. if node:
  769. cmd.extend(node)
  770. else:
  771. cmd.append('--selector=%s' % selector)
  772. if dry_run:
  773. cmd.append('--dry-run')
  774. if pod_selector:
  775. cmd.append('--pod-selector=%s' % pod_selector)
  776. if grace_period:
  777. cmd.append('--grace-period=%s' % int(grace_period))
  778. if force:
  779. cmd.append('--force')
  780. cmd.append('--evacuate')
  781. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  782. def _version(self):
  783. ''' return the openshift version'''
  784. return self.openshift_cmd(['version'], output=True, output_type='raw')
  785. def _import_image(self, url=None, name=None, tag=None):
  786. ''' perform image import '''
  787. cmd = ['import-image']
  788. image = '{0}'.format(name)
  789. if tag:
  790. image += ':{0}'.format(tag)
  791. cmd.append(image)
  792. if url:
  793. cmd.append('--from={0}/{1}'.format(url, image))
  794. cmd.append('-n{0}'.format(self.namespace))
  795. cmd.append('--confirm')
  796. return self.openshift_cmd(cmd)
  797. def _run(self, cmds, input_data):
  798. ''' Actually executes the command. This makes mocking easier. '''
  799. curr_env = os.environ.copy()
  800. curr_env.update({'KUBECONFIG': self.kubeconfig})
  801. proc = subprocess.Popen(cmds,
  802. stdin=subprocess.PIPE,
  803. stdout=subprocess.PIPE,
  804. stderr=subprocess.PIPE,
  805. env=curr_env)
  806. stdout, stderr = proc.communicate(input_data)
  807. return proc.returncode, stdout.decode(), stderr.decode()
  808. # pylint: disable=too-many-arguments,too-many-branches
  809. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  810. '''Base command for oc '''
  811. cmds = [self.oc_binary]
  812. if oadm:
  813. cmds.append('adm')
  814. cmds.extend(cmd)
  815. if self.all_namespaces:
  816. cmds.extend(['--all-namespaces'])
  817. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  818. cmds.extend(['-n', self.namespace])
  819. rval = {}
  820. results = ''
  821. err = None
  822. if self.verbose:
  823. print(' '.join(cmds))
  824. try:
  825. returncode, stdout, stderr = self._run(cmds, input_data)
  826. except OSError as ex:
  827. returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
  828. rval = {"returncode": returncode,
  829. "results": results,
  830. "cmd": ' '.join(cmds)}
  831. if returncode == 0:
  832. if output:
  833. if output_type == 'json':
  834. try:
  835. rval['results'] = json.loads(stdout)
  836. except ValueError as verr:
  837. if "No JSON object could be decoded" in verr.args:
  838. err = verr.args
  839. elif output_type == 'raw':
  840. rval['results'] = stdout
  841. if self.verbose:
  842. print("STDOUT: {0}".format(stdout))
  843. print("STDERR: {0}".format(stderr))
  844. if err:
  845. rval.update({"err": err,
  846. "stderr": stderr,
  847. "stdout": stdout,
  848. "cmd": cmds})
  849. else:
  850. rval.update({"stderr": stderr,
  851. "stdout": stdout,
  852. "results": {}})
  853. return rval
  854. class Utils(object): # pragma: no cover
  855. ''' utilities for openshiftcli modules '''
  856. @staticmethod
  857. def _write(filename, contents):
  858. ''' Actually write the file contents to disk. This helps with mocking. '''
  859. with open(filename, 'w') as sfd:
  860. sfd.write(contents)
  861. @staticmethod
  862. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  863. ''' create a file in tmp with name and contents'''
  864. tmp = Utils.create_tmpfile(prefix=rname)
  865. if ftype == 'yaml':
  866. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  867. # pylint: disable=no-member
  868. if hasattr(yaml, 'RoundTripDumper'):
  869. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  870. else:
  871. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  872. elif ftype == 'json':
  873. Utils._write(tmp, json.dumps(data))
  874. else:
  875. Utils._write(tmp, data)
  876. # Register cleanup when module is done
  877. atexit.register(Utils.cleanup, [tmp])
  878. return tmp
  879. @staticmethod
  880. def create_tmpfile_copy(inc_file):
  881. '''create a temporary copy of a file'''
  882. tmpfile = Utils.create_tmpfile('lib_openshift-')
  883. Utils._write(tmpfile, open(inc_file).read())
  884. # Cleanup the tmpfile
  885. atexit.register(Utils.cleanup, [tmpfile])
  886. return tmpfile
  887. @staticmethod
  888. def create_tmpfile(prefix='tmp'):
  889. ''' Generates and returns a temporary file name '''
  890. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  891. return tmp.name
  892. @staticmethod
  893. def create_tmp_files_from_contents(content, content_type=None):
  894. '''Turn an array of dict: filename, content into a files array'''
  895. if not isinstance(content, list):
  896. content = [content]
  897. files = []
  898. for item in content:
  899. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  900. item['data'],
  901. ftype=content_type)
  902. files.append({'name': os.path.basename(item['path']),
  903. 'path': path})
  904. return files
  905. @staticmethod
  906. def cleanup(files):
  907. '''Clean up on exit '''
  908. for sfile in files:
  909. if os.path.exists(sfile):
  910. if os.path.isdir(sfile):
  911. shutil.rmtree(sfile)
  912. elif os.path.isfile(sfile):
  913. os.remove(sfile)
  914. @staticmethod
  915. def exists(results, _name):
  916. ''' Check to see if the results include the name '''
  917. if not results:
  918. return False
  919. if Utils.find_result(results, _name):
  920. return True
  921. return False
  922. @staticmethod
  923. def find_result(results, _name):
  924. ''' Find the specified result by name'''
  925. rval = None
  926. for result in results:
  927. if 'metadata' in result and result['metadata']['name'] == _name:
  928. rval = result
  929. break
  930. return rval
  931. @staticmethod
  932. def get_resource_file(sfile, sfile_type='yaml'):
  933. ''' return the service file '''
  934. contents = None
  935. with open(sfile) as sfd:
  936. contents = sfd.read()
  937. if sfile_type == 'yaml':
  938. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  939. # pylint: disable=no-member
  940. if hasattr(yaml, 'RoundTripLoader'):
  941. contents = yaml.load(contents, yaml.RoundTripLoader)
  942. else:
  943. contents = yaml.safe_load(contents)
  944. elif sfile_type == 'json':
  945. contents = json.loads(contents)
  946. return contents
  947. @staticmethod
  948. def filter_versions(stdout):
  949. ''' filter the oc version output '''
  950. version_dict = {}
  951. version_search = ['oc', 'openshift', 'kubernetes']
  952. for line in stdout.strip().split('\n'):
  953. for term in version_search:
  954. if not line:
  955. continue
  956. if line.startswith(term):
  957. version_dict[term] = line.split()[-1]
  958. # horrible hack to get openshift version in Openshift 3.2
  959. # By default "oc version in 3.2 does not return an "openshift" version
  960. if "openshift" not in version_dict:
  961. version_dict["openshift"] = version_dict["oc"]
  962. return version_dict
  963. @staticmethod
  964. def add_custom_versions(versions):
  965. ''' create custom versions strings '''
  966. versions_dict = {}
  967. for tech, version in versions.items():
  968. # clean up "-" from version
  969. if "-" in version:
  970. version = version.split("-")[0]
  971. if version.startswith('v'):
  972. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  973. # "v3.3.0.33" is what we have, we want "3.3"
  974. versions_dict[tech + '_short'] = version[1:4]
  975. return versions_dict
  976. @staticmethod
  977. def openshift_installed():
  978. ''' check if openshift is installed '''
  979. import yum
  980. yum_base = yum.YumBase()
  981. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  982. return True
  983. return False
  984. # Disabling too-many-branches. This is a yaml dictionary comparison function
  985. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  986. @staticmethod
  987. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  988. ''' Given a user defined definition, compare it with the results given back by our query. '''
  989. # Currently these values are autogenerated and we do not need to check them
  990. skip = ['metadata', 'status']
  991. if skip_keys:
  992. skip.extend(skip_keys)
  993. for key, value in result_def.items():
  994. if key in skip:
  995. continue
  996. # Both are lists
  997. if isinstance(value, list):
  998. if key not in user_def:
  999. if debug:
  1000. print('User data does not have key [%s]' % key)
  1001. print('User data: %s' % user_def)
  1002. return False
  1003. if not isinstance(user_def[key], list):
  1004. if debug:
  1005. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  1006. return False
  1007. if len(user_def[key]) != len(value):
  1008. if debug:
  1009. print("List lengths are not equal.")
  1010. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  1011. print("user_def: %s" % user_def[key])
  1012. print("value: %s" % value)
  1013. return False
  1014. for values in zip(user_def[key], value):
  1015. if isinstance(values[0], dict) and isinstance(values[1], dict):
  1016. if debug:
  1017. print('sending list - list')
  1018. print(type(values[0]))
  1019. print(type(values[1]))
  1020. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  1021. if not result:
  1022. print('list compare returned false')
  1023. return False
  1024. elif value != user_def[key]:
  1025. if debug:
  1026. print('value should be identical')
  1027. print(user_def[key])
  1028. print(value)
  1029. return False
  1030. # recurse on a dictionary
  1031. elif isinstance(value, dict):
  1032. if key not in user_def:
  1033. if debug:
  1034. print("user_def does not have key [%s]" % key)
  1035. return False
  1036. if not isinstance(user_def[key], dict):
  1037. if debug:
  1038. print("dict returned false: not instance of dict")
  1039. return False
  1040. # before passing ensure keys match
  1041. api_values = set(value.keys()) - set(skip)
  1042. user_values = set(user_def[key].keys()) - set(skip)
  1043. if api_values != user_values:
  1044. if debug:
  1045. print("keys are not equal in dict")
  1046. print(user_values)
  1047. print(api_values)
  1048. return False
  1049. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1050. if not result:
  1051. if debug:
  1052. print("dict returned false")
  1053. print(result)
  1054. return False
  1055. # Verify each key, value pair is the same
  1056. else:
  1057. if key not in user_def or value != user_def[key]:
  1058. if debug:
  1059. print("value not equal; user_def does not have key")
  1060. print(key)
  1061. print(value)
  1062. if key in user_def:
  1063. print(user_def[key])
  1064. return False
  1065. if debug:
  1066. print('returning true')
  1067. return True
  1068. class OpenShiftCLIConfig(object):
  1069. '''Generic Config'''
  1070. def __init__(self, rname, namespace, kubeconfig, options):
  1071. self.kubeconfig = kubeconfig
  1072. self.name = rname
  1073. self.namespace = namespace
  1074. self._options = options
  1075. @property
  1076. def config_options(self):
  1077. ''' return config options '''
  1078. return self._options
  1079. def to_option_list(self):
  1080. '''return all options as a string'''
  1081. return self.stringify()
  1082. def stringify(self):
  1083. ''' return the options hash as cli params in a string '''
  1084. rval = []
  1085. for key in sorted(self.config_options.keys()):
  1086. data = self.config_options[key]
  1087. if data['include'] \
  1088. and (data['value'] or isinstance(data['value'], int)):
  1089. rval.append('--{}={}'.format(key.replace('_', '-'), data['value']))
  1090. return rval
  1091. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1092. # -*- -*- -*- Begin included fragment: class/oc_version.py -*- -*- -*-
  1093. # pylint: disable=too-many-instance-attributes
  1094. class OCVersion(OpenShiftCLI):
  1095. ''' Class to wrap the oc command line tools '''
  1096. # pylint allows 5
  1097. # pylint: disable=too-many-arguments
  1098. def __init__(self,
  1099. config,
  1100. debug):
  1101. ''' Constructor for OCVersion '''
  1102. super(OCVersion, self).__init__(None, config)
  1103. self.debug = debug
  1104. def get(self):
  1105. '''get and return version information '''
  1106. results = {}
  1107. version_results = self._version()
  1108. if version_results['returncode'] == 0:
  1109. filtered_vers = Utils.filter_versions(version_results['results'])
  1110. custom_vers = Utils.add_custom_versions(filtered_vers)
  1111. results['returncode'] = version_results['returncode']
  1112. results.update(filtered_vers)
  1113. results.update(custom_vers)
  1114. return results
  1115. raise OpenShiftCLIError('Problem detecting openshift version.')
  1116. @staticmethod
  1117. def run_ansible(params):
  1118. '''run the idempotent ansible code'''
  1119. oc_version = OCVersion(params['kubeconfig'], params['debug'])
  1120. if params['state'] == 'list':
  1121. #pylint: disable=protected-access
  1122. result = oc_version.get()
  1123. return {'state': params['state'],
  1124. 'results': result,
  1125. 'changed': False}
  1126. # -*- -*- -*- End included fragment: class/oc_version.py -*- -*- -*-
  1127. # -*- -*- -*- Begin included fragment: ansible/oc_version.py -*- -*- -*-
  1128. def main():
  1129. ''' ansible oc module for version '''
  1130. module = AnsibleModule(
  1131. argument_spec=dict(
  1132. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1133. state=dict(default='list', type='str',
  1134. choices=['list']),
  1135. debug=dict(default=False, type='bool'),
  1136. ),
  1137. supports_check_mode=True,
  1138. )
  1139. rval = OCVersion.run_ansible(module.params)
  1140. if 'failed' in rval:
  1141. module.fail_json(**rval)
  1142. module.exit_json(**rval)
  1143. if __name__ == '__main__':
  1144. main()
  1145. # -*- -*- -*- End included fragment: ansible/oc_version.py -*- -*- -*-