oc_group.py 52 KB

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