oc_obj.py 48 KB

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