oc_obj.py 51 KB

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