oc_obj.py 51 KB

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