oc_version.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443
  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):
  88. ''' Exception class for Yedit '''
  89. pass
  90. # pylint: disable=too-many-public-methods
  91. class Yedit(object):
  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 % ''.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 % ''.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, None)
  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, None)
  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. %s' % 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 ' +
  405. 'dict with non-dict type. value=[%s] [%s]' % (value, type(value))) # noqa: E501
  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=[%s] vtype=[%s]' % (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 ' +
  522. 'value. value=[%s] vtype=[%s]'
  523. % (type(inc_value), vtype))
  524. return inc_value
  525. @staticmethod
  526. def process_edits(edits, yamlfile):
  527. '''run through a list of edits and process them one-by-one'''
  528. results = []
  529. for edit in edits:
  530. value = Yedit.parse_value(edit['value'], edit.get('value_type', ''))
  531. if 'action' in edit and edit['action'] == 'update':
  532. # pylint: disable=line-too-long
  533. curr_value = Yedit.get_curr_value(Yedit.parse_value(edit.get('curr_value', None)), # noqa: E501
  534. edit.get('curr_value_format', None)) # noqa: E501
  535. rval = yamlfile.update(edit['key'],
  536. value,
  537. edit.get('index', None),
  538. curr_value)
  539. elif 'action' in edit and edit['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 [%s]. Verify that the ' +
  559. 'file exists, that it is has correct' +
  560. ' permissions, and is valid yaml.'}
  561. if state == 'list':
  562. if params['content']:
  563. content = Yedit.parse_value(params['content'], params['content_type'])
  564. yamlfile.yaml_dict = content
  565. if params['key']:
  566. rval = yamlfile.get(params['key']) or {}
  567. return {'changed': False, 'result': rval, 'state': state}
  568. elif state == 'absent':
  569. if params['content']:
  570. content = Yedit.parse_value(params['content'], params['content_type'])
  571. yamlfile.yaml_dict = content
  572. if params['update']:
  573. rval = yamlfile.pop(params['key'], params['value'])
  574. else:
  575. rval = yamlfile.delete(params['key'])
  576. if rval[0] and params['src']:
  577. yamlfile.write()
  578. return {'changed': rval[0], 'result': rval[1], 'state': state}
  579. elif state == 'present':
  580. # check if content is different than what is in the file
  581. if params['content']:
  582. content = Yedit.parse_value(params['content'], params['content_type'])
  583. # We had no edits to make and the contents are the same
  584. if yamlfile.yaml_dict == content and \
  585. params['value'] is None:
  586. return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
  587. yamlfile.yaml_dict = content
  588. # If we were passed a key, value then
  589. # we enapsulate it in a list and process it
  590. # Key, Value passed to the module : Converted to Edits list #
  591. edits = []
  592. _edit = {}
  593. if params['value'] is not None:
  594. _edit['value'] = params['value']
  595. _edit['value_type'] = params['value_type']
  596. _edit['key'] = params['key']
  597. if params['update']:
  598. _edit['action'] = 'update'
  599. _edit['curr_value'] = params['curr_value']
  600. _edit['curr_value_format'] = params['curr_value_format']
  601. _edit['index'] = params['index']
  602. elif params['append']:
  603. _edit['action'] = 'append'
  604. edits.append(_edit)
  605. elif params['edits'] is not None:
  606. edits = params['edits']
  607. if edits:
  608. results = Yedit.process_edits(edits, yamlfile)
  609. # if there were changes and a src provided to us we need to write
  610. if results['changed'] and params['src']:
  611. yamlfile.write()
  612. return {'changed': results['changed'], 'result': results['results'], 'state': state}
  613. # no edits to make
  614. if params['src']:
  615. # pylint: disable=redefined-variable-type
  616. rval = yamlfile.write()
  617. return {'changed': rval[0],
  618. 'result': rval[1],
  619. 'state': state}
  620. # We were passed content but no src, key or value, or edits. Return contents in memory
  621. return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
  622. return {'failed': True, 'msg': 'Unkown state passed'}
  623. # -*- -*- -*- End included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  624. # -*- -*- -*- Begin included fragment: lib/base.py -*- -*- -*-
  625. # pylint: disable=too-many-lines
  626. # noqa: E301,E302,E303,T001
  627. class OpenShiftCLIError(Exception):
  628. '''Exception class for openshiftcli'''
  629. pass
  630. ADDITIONAL_PATH_LOOKUPS = ['/usr/local/bin', os.path.expanduser('~/bin')]
  631. def locate_oc_binary():
  632. ''' Find and return oc binary file '''
  633. # https://github.com/openshift/openshift-ansible/issues/3410
  634. # oc can be in /usr/local/bin in some cases, but that may not
  635. # be in $PATH due to ansible/sudo
  636. paths = os.environ.get("PATH", os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS
  637. oc_binary = 'oc'
  638. # Use shutil.which if it is available, otherwise fallback to a naive path search
  639. try:
  640. which_result = shutil.which(oc_binary, path=os.pathsep.join(paths))
  641. if which_result is not None:
  642. oc_binary = which_result
  643. except AttributeError:
  644. for path in paths:
  645. if os.path.exists(os.path.join(path, oc_binary)):
  646. oc_binary = os.path.join(path, oc_binary)
  647. break
  648. return oc_binary
  649. # pylint: disable=too-few-public-methods
  650. class OpenShiftCLI(object):
  651. ''' Class to wrap the command line tools '''
  652. def __init__(self,
  653. namespace,
  654. kubeconfig='/etc/origin/master/admin.kubeconfig',
  655. verbose=False,
  656. all_namespaces=False):
  657. ''' Constructor for OpenshiftCLI '''
  658. self.namespace = namespace
  659. self.verbose = verbose
  660. self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
  661. self.all_namespaces = all_namespaces
  662. self.oc_binary = locate_oc_binary()
  663. # Pylint allows only 5 arguments to be passed.
  664. # pylint: disable=too-many-arguments
  665. def _replace_content(self, resource, rname, content, force=False, sep='.'):
  666. ''' replace the current object with the content '''
  667. res = self._get(resource, rname)
  668. if not res['results']:
  669. return res
  670. fname = Utils.create_tmpfile(rname + '-')
  671. yed = Yedit(fname, res['results'][0], separator=sep)
  672. changes = []
  673. for key, value in content.items():
  674. changes.append(yed.put(key, value))
  675. if any([change[0] for change in changes]):
  676. yed.write()
  677. atexit.register(Utils.cleanup, [fname])
  678. return self._replace(fname, force)
  679. return {'returncode': 0, 'updated': False}
  680. def _replace(self, fname, force=False):
  681. '''replace the current object with oc replace'''
  682. cmd = ['replace', '-f', fname]
  683. if force:
  684. cmd.append('--force')
  685. return self.openshift_cmd(cmd)
  686. def _create_from_content(self, rname, content):
  687. '''create a temporary file and then call oc create on it'''
  688. fname = Utils.create_tmpfile(rname + '-')
  689. yed = Yedit(fname, content=content)
  690. yed.write()
  691. atexit.register(Utils.cleanup, [fname])
  692. return self._create(fname)
  693. def _create(self, fname):
  694. '''call oc create on a filename'''
  695. return self.openshift_cmd(['create', '-f', fname])
  696. def _delete(self, resource, rname, selector=None):
  697. '''call oc delete on a resource'''
  698. cmd = ['delete', resource, rname]
  699. if selector:
  700. cmd.append('--selector=%s' % selector)
  701. return self.openshift_cmd(cmd)
  702. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  703. '''process a template
  704. template_name: the name of the template to process
  705. create: whether to send to oc create after processing
  706. params: the parameters for the template
  707. template_data: the incoming template's data; instead of a file
  708. '''
  709. cmd = ['process']
  710. if template_data:
  711. cmd.extend(['-f', '-'])
  712. else:
  713. cmd.append(template_name)
  714. if params:
  715. param_str = ["%s=%s" % (key, value) for key, value in params.items()]
  716. cmd.append('-v')
  717. cmd.extend(param_str)
  718. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  719. if results['returncode'] != 0 or not create:
  720. return results
  721. fname = Utils.create_tmpfile(template_name + '-')
  722. yed = Yedit(fname, results['results'])
  723. yed.write()
  724. atexit.register(Utils.cleanup, [fname])
  725. return self.openshift_cmd(['create', '-f', fname])
  726. def _get(self, resource, rname=None, selector=None):
  727. '''return a resource by name '''
  728. cmd = ['get', resource]
  729. if selector:
  730. cmd.append('--selector=%s' % selector)
  731. elif rname:
  732. cmd.append(rname)
  733. cmd.extend(['-o', 'json'])
  734. rval = self.openshift_cmd(cmd, output=True)
  735. # Ensure results are retuned in an array
  736. if 'items' in rval:
  737. rval['results'] = rval['items']
  738. elif not isinstance(rval['results'], list):
  739. rval['results'] = [rval['results']]
  740. return rval
  741. def _schedulable(self, node=None, selector=None, schedulable=True):
  742. ''' perform oadm manage-node scheduable '''
  743. cmd = ['manage-node']
  744. if node:
  745. cmd.extend(node)
  746. else:
  747. cmd.append('--selector=%s' % selector)
  748. cmd.append('--schedulable=%s' % schedulable)
  749. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  750. def _list_pods(self, node=None, selector=None, pod_selector=None):
  751. ''' perform oadm list pods
  752. node: the node in which to list pods
  753. selector: the label selector filter if provided
  754. pod_selector: the pod selector filter if provided
  755. '''
  756. cmd = ['manage-node']
  757. if node:
  758. cmd.extend(node)
  759. else:
  760. cmd.append('--selector=%s' % selector)
  761. if pod_selector:
  762. cmd.append('--pod-selector=%s' % pod_selector)
  763. cmd.extend(['--list-pods', '-o', 'json'])
  764. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  765. # pylint: disable=too-many-arguments
  766. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  767. ''' perform oadm manage-node evacuate '''
  768. cmd = ['manage-node']
  769. if node:
  770. cmd.extend(node)
  771. else:
  772. cmd.append('--selector=%s' % selector)
  773. if dry_run:
  774. cmd.append('--dry-run')
  775. if pod_selector:
  776. cmd.append('--pod-selector=%s' % pod_selector)
  777. if grace_period:
  778. cmd.append('--grace-period=%s' % int(grace_period))
  779. if force:
  780. cmd.append('--force')
  781. cmd.append('--evacuate')
  782. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  783. def _version(self):
  784. ''' return the openshift version'''
  785. return self.openshift_cmd(['version'], output=True, output_type='raw')
  786. def _import_image(self, url=None, name=None, tag=None):
  787. ''' perform image import '''
  788. cmd = ['import-image']
  789. image = '{0}'.format(name)
  790. if tag:
  791. image += ':{0}'.format(tag)
  792. cmd.append(image)
  793. if url:
  794. cmd.append('--from={0}/{1}'.format(url, image))
  795. cmd.append('-n{0}'.format(self.namespace))
  796. cmd.append('--confirm')
  797. return self.openshift_cmd(cmd)
  798. def _run(self, cmds, input_data):
  799. ''' Actually executes the command. This makes mocking easier. '''
  800. curr_env = os.environ.copy()
  801. curr_env.update({'KUBECONFIG': self.kubeconfig})
  802. proc = subprocess.Popen(cmds,
  803. stdin=subprocess.PIPE,
  804. stdout=subprocess.PIPE,
  805. stderr=subprocess.PIPE,
  806. env=curr_env)
  807. stdout, stderr = proc.communicate(input_data)
  808. return proc.returncode, stdout.decode(), stderr.decode()
  809. # pylint: disable=too-many-arguments,too-many-branches
  810. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  811. '''Base command for oc '''
  812. cmds = [self.oc_binary]
  813. if oadm:
  814. cmds.append('adm')
  815. cmds.extend(cmd)
  816. if self.all_namespaces:
  817. cmds.extend(['--all-namespaces'])
  818. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  819. cmds.extend(['-n', self.namespace])
  820. rval = {}
  821. results = ''
  822. err = None
  823. if self.verbose:
  824. print(' '.join(cmds))
  825. try:
  826. returncode, stdout, stderr = self._run(cmds, input_data)
  827. except OSError as ex:
  828. returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
  829. rval = {"returncode": returncode,
  830. "results": results,
  831. "cmd": ' '.join(cmds)}
  832. if returncode == 0:
  833. if output:
  834. if output_type == 'json':
  835. try:
  836. rval['results'] = json.loads(stdout)
  837. except ValueError as verr:
  838. if "No JSON object could be decoded" in verr.args:
  839. err = verr.args
  840. elif output_type == 'raw':
  841. rval['results'] = stdout
  842. if self.verbose:
  843. print("STDOUT: {0}".format(stdout))
  844. print("STDERR: {0}".format(stderr))
  845. if err:
  846. rval.update({"err": err,
  847. "stderr": stderr,
  848. "stdout": stdout,
  849. "cmd": cmds})
  850. else:
  851. rval.update({"stderr": stderr,
  852. "stdout": stdout,
  853. "results": {}})
  854. return rval
  855. class Utils(object):
  856. ''' utilities for openshiftcli modules '''
  857. @staticmethod
  858. def _write(filename, contents):
  859. ''' Actually write the file contents to disk. This helps with mocking. '''
  860. with open(filename, 'w') as sfd:
  861. sfd.write(contents)
  862. @staticmethod
  863. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  864. ''' create a file in tmp with name and contents'''
  865. tmp = Utils.create_tmpfile(prefix=rname)
  866. if ftype == 'yaml':
  867. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  868. # pylint: disable=no-member
  869. if hasattr(yaml, 'RoundTripDumper'):
  870. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  871. else:
  872. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  873. elif ftype == 'json':
  874. Utils._write(tmp, json.dumps(data))
  875. else:
  876. Utils._write(tmp, data)
  877. # Register cleanup when module is done
  878. atexit.register(Utils.cleanup, [tmp])
  879. return tmp
  880. @staticmethod
  881. def create_tmpfile_copy(inc_file):
  882. '''create a temporary copy of a file'''
  883. tmpfile = Utils.create_tmpfile('lib_openshift-')
  884. Utils._write(tmpfile, open(inc_file).read())
  885. # Cleanup the tmpfile
  886. atexit.register(Utils.cleanup, [tmpfile])
  887. return tmpfile
  888. @staticmethod
  889. def create_tmpfile(prefix='tmp'):
  890. ''' Generates and returns a temporary file name '''
  891. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  892. return tmp.name
  893. @staticmethod
  894. def create_tmp_files_from_contents(content, content_type=None):
  895. '''Turn an array of dict: filename, content into a files array'''
  896. if not isinstance(content, list):
  897. content = [content]
  898. files = []
  899. for item in content:
  900. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  901. item['data'],
  902. ftype=content_type)
  903. files.append({'name': os.path.basename(item['path']),
  904. 'path': path})
  905. return files
  906. @staticmethod
  907. def cleanup(files):
  908. '''Clean up on exit '''
  909. for sfile in files:
  910. if os.path.exists(sfile):
  911. if os.path.isdir(sfile):
  912. shutil.rmtree(sfile)
  913. elif os.path.isfile(sfile):
  914. os.remove(sfile)
  915. @staticmethod
  916. def exists(results, _name):
  917. ''' Check to see if the results include the name '''
  918. if not results:
  919. return False
  920. if Utils.find_result(results, _name):
  921. return True
  922. return False
  923. @staticmethod
  924. def find_result(results, _name):
  925. ''' Find the specified result by name'''
  926. rval = None
  927. for result in results:
  928. if 'metadata' in result and result['metadata']['name'] == _name:
  929. rval = result
  930. break
  931. return rval
  932. @staticmethod
  933. def get_resource_file(sfile, sfile_type='yaml'):
  934. ''' return the service file '''
  935. contents = None
  936. with open(sfile) as sfd:
  937. contents = sfd.read()
  938. if sfile_type == 'yaml':
  939. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  940. # pylint: disable=no-member
  941. if hasattr(yaml, 'RoundTripLoader'):
  942. contents = yaml.load(contents, yaml.RoundTripLoader)
  943. else:
  944. contents = yaml.safe_load(contents)
  945. elif sfile_type == 'json':
  946. contents = json.loads(contents)
  947. return contents
  948. @staticmethod
  949. def filter_versions(stdout):
  950. ''' filter the oc version output '''
  951. version_dict = {}
  952. version_search = ['oc', 'openshift', 'kubernetes']
  953. for line in stdout.strip().split('\n'):
  954. for term in version_search:
  955. if not line:
  956. continue
  957. if line.startswith(term):
  958. version_dict[term] = line.split()[-1]
  959. # horrible hack to get openshift version in Openshift 3.2
  960. # By default "oc version in 3.2 does not return an "openshift" version
  961. if "openshift" not in version_dict:
  962. version_dict["openshift"] = version_dict["oc"]
  963. return version_dict
  964. @staticmethod
  965. def add_custom_versions(versions):
  966. ''' create custom versions strings '''
  967. versions_dict = {}
  968. for tech, version in versions.items():
  969. # clean up "-" from version
  970. if "-" in version:
  971. version = version.split("-")[0]
  972. if version.startswith('v'):
  973. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  974. # "v3.3.0.33" is what we have, we want "3.3"
  975. versions_dict[tech + '_short'] = version[1:4]
  976. return versions_dict
  977. @staticmethod
  978. def openshift_installed():
  979. ''' check if openshift is installed '''
  980. import yum
  981. yum_base = yum.YumBase()
  982. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  983. return True
  984. return False
  985. # Disabling too-many-branches. This is a yaml dictionary comparison function
  986. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  987. @staticmethod
  988. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  989. ''' Given a user defined definition, compare it with the results given back by our query. '''
  990. # Currently these values are autogenerated and we do not need to check them
  991. skip = ['metadata', 'status']
  992. if skip_keys:
  993. skip.extend(skip_keys)
  994. for key, value in result_def.items():
  995. if key in skip:
  996. continue
  997. # Both are lists
  998. if isinstance(value, list):
  999. if key not in user_def:
  1000. if debug:
  1001. print('User data does not have key [%s]' % key)
  1002. print('User data: %s' % user_def)
  1003. return False
  1004. if not isinstance(user_def[key], list):
  1005. if debug:
  1006. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  1007. return False
  1008. if len(user_def[key]) != len(value):
  1009. if debug:
  1010. print("List lengths are not equal.")
  1011. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  1012. print("user_def: %s" % user_def[key])
  1013. print("value: %s" % value)
  1014. return False
  1015. for values in zip(user_def[key], value):
  1016. if isinstance(values[0], dict) and isinstance(values[1], dict):
  1017. if debug:
  1018. print('sending list - list')
  1019. print(type(values[0]))
  1020. print(type(values[1]))
  1021. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  1022. if not result:
  1023. print('list compare returned false')
  1024. return False
  1025. elif value != user_def[key]:
  1026. if debug:
  1027. print('value should be identical')
  1028. print(user_def[key])
  1029. print(value)
  1030. return False
  1031. # recurse on a dictionary
  1032. elif isinstance(value, dict):
  1033. if key not in user_def:
  1034. if debug:
  1035. print("user_def does not have key [%s]" % key)
  1036. return False
  1037. if not isinstance(user_def[key], dict):
  1038. if debug:
  1039. print("dict returned false: not instance of dict")
  1040. return False
  1041. # before passing ensure keys match
  1042. api_values = set(value.keys()) - set(skip)
  1043. user_values = set(user_def[key].keys()) - set(skip)
  1044. if api_values != user_values:
  1045. if debug:
  1046. print("keys are not equal in dict")
  1047. print(user_values)
  1048. print(api_values)
  1049. return False
  1050. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1051. if not result:
  1052. if debug:
  1053. print("dict returned false")
  1054. print(result)
  1055. return False
  1056. # Verify each key, value pair is the same
  1057. else:
  1058. if key not in user_def or value != user_def[key]:
  1059. if debug:
  1060. print("value not equal; user_def does not have key")
  1061. print(key)
  1062. print(value)
  1063. if key in user_def:
  1064. print(user_def[key])
  1065. return False
  1066. if debug:
  1067. print('returning true')
  1068. return True
  1069. class OpenShiftCLIConfig(object):
  1070. '''Generic Config'''
  1071. def __init__(self, rname, namespace, kubeconfig, options):
  1072. self.kubeconfig = kubeconfig
  1073. self.name = rname
  1074. self.namespace = namespace
  1075. self._options = options
  1076. @property
  1077. def config_options(self):
  1078. ''' return config options '''
  1079. return self._options
  1080. def to_option_list(self):
  1081. '''return all options as a string'''
  1082. return self.stringify()
  1083. def stringify(self):
  1084. ''' return the options hash as cli params in a string '''
  1085. rval = []
  1086. for key in sorted(self.config_options.keys()):
  1087. data = self.config_options[key]
  1088. if data['include'] \
  1089. and (data['value'] or isinstance(data['value'], int)):
  1090. rval.append('--{}={}'.format(key.replace('_', '-'), data['value']))
  1091. return rval
  1092. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1093. # -*- -*- -*- Begin included fragment: class/oc_version.py -*- -*- -*-
  1094. # pylint: disable=too-many-instance-attributes
  1095. class OCVersion(OpenShiftCLI):
  1096. ''' Class to wrap the oc command line tools '''
  1097. # pylint allows 5
  1098. # pylint: disable=too-many-arguments
  1099. def __init__(self,
  1100. config,
  1101. debug):
  1102. ''' Constructor for OCVersion '''
  1103. super(OCVersion, self).__init__(None, config)
  1104. self.debug = debug
  1105. def get(self):
  1106. '''get and return version information '''
  1107. results = {}
  1108. version_results = self._version()
  1109. if version_results['returncode'] == 0:
  1110. filtered_vers = Utils.filter_versions(version_results['results'])
  1111. custom_vers = Utils.add_custom_versions(filtered_vers)
  1112. results['returncode'] = version_results['returncode']
  1113. results.update(filtered_vers)
  1114. results.update(custom_vers)
  1115. return results
  1116. raise OpenShiftCLIError('Problem detecting openshift version.')
  1117. @staticmethod
  1118. def run_ansible(params):
  1119. '''run the idempotent ansible code'''
  1120. oc_version = OCVersion(params['kubeconfig'], params['debug'])
  1121. if params['state'] == 'list':
  1122. #pylint: disable=protected-access
  1123. result = oc_version.get()
  1124. return {'state': params['state'],
  1125. 'results': result,
  1126. 'changed': False}
  1127. # -*- -*- -*- End included fragment: class/oc_version.py -*- -*- -*-
  1128. # -*- -*- -*- Begin included fragment: ansible/oc_version.py -*- -*- -*-
  1129. def main():
  1130. ''' ansible oc module for version '''
  1131. module = AnsibleModule(
  1132. argument_spec=dict(
  1133. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1134. state=dict(default='list', type='str',
  1135. choices=['list']),
  1136. debug=dict(default=False, type='bool'),
  1137. ),
  1138. supports_check_mode=True,
  1139. )
  1140. rval = OCVersion.run_ansible(module.params)
  1141. if 'failed' in rval:
  1142. module.fail_json(**rval)
  1143. module.exit_json(**rval)
  1144. if __name__ == '__main__':
  1145. main()
  1146. # -*- -*- -*- End included fragment: ansible/oc_version.py -*- -*- -*-