oc_obj.py 53 KB

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