oc_adm_policy_group.py 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189
  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/policy_group -*- -*- -*-
  49. DOCUMENTATION = '''
  50. ---
  51. module: oc_adm_policy_group
  52. short_description: Module to manage openshift policy for groups
  53. description:
  54. - Manage openshift policy for groups.
  55. options:
  56. kubeconfig:
  57. description:
  58. - The path for the kubeconfig file to use for authentication
  59. required: false
  60. default: /etc/origin/master/admin.kubeconfig
  61. aliases: []
  62. namespace:
  63. description:
  64. - The namespace scope
  65. required: false
  66. default: None
  67. aliases: []
  68. debug:
  69. description:
  70. - Turn on debug output.
  71. required: false
  72. default: False
  73. aliases: []
  74. group:
  75. description:
  76. - The name of the group
  77. required: true
  78. default: None
  79. aliases: []
  80. resource_kind:
  81. description:
  82. - The kind of policy to affect
  83. required: true
  84. default: None
  85. choices: ["role", "cluster-role", "scc"]
  86. aliases: []
  87. resource_name:
  88. description:
  89. - The name of the policy
  90. required: true
  91. default: None
  92. aliases: []
  93. state:
  94. description:
  95. - Desired state of the policy
  96. required: true
  97. default: present
  98. choices: ["present", "absent"]
  99. aliases: []
  100. author:
  101. - "Kenny Woodson <kwoodson@redhat.com>"
  102. extends_documentation_fragment: []
  103. '''
  104. EXAMPLES = '''
  105. - name: oc adm policy remove-scc-from-group an-scc agroup
  106. oc_adm_policy_group:
  107. group: agroup
  108. resource_kind: scc
  109. resource_name: an-scc
  110. state: absent
  111. - name: oc adm policy add-cluster-role-to-group system:build-strategy-docker agroup
  112. oc_adm_policy_group:
  113. group: agroup
  114. resource_kind: cluster-role
  115. resource_name: system:build-strategy-docker
  116. state: present
  117. '''
  118. # -*- -*- -*- End included fragment: doc/policy_group -*- -*- -*-
  119. # -*- -*- -*- Begin included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  120. class YeditException(Exception): # pragma: no cover
  121. ''' Exception class for Yedit '''
  122. pass
  123. # pylint: disable=too-many-public-methods
  124. class Yedit(object): # pragma: no cover
  125. ''' Class to modify yaml files '''
  126. re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
  127. re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z{}/_-]+)"
  128. com_sep = set(['.', '#', '|', ':'])
  129. # pylint: disable=too-many-arguments
  130. def __init__(self,
  131. filename=None,
  132. content=None,
  133. content_type='yaml',
  134. separator='.',
  135. backup=False):
  136. self.content = content
  137. self._separator = separator
  138. self.filename = filename
  139. self.__yaml_dict = content
  140. self.content_type = content_type
  141. self.backup = backup
  142. self.load(content_type=self.content_type)
  143. if self.__yaml_dict is None:
  144. self.__yaml_dict = {}
  145. @property
  146. def separator(self):
  147. ''' getter method for separator '''
  148. return self._separator
  149. @separator.setter
  150. def separator(self, inc_sep):
  151. ''' setter method for separator '''
  152. self._separator = inc_sep
  153. @property
  154. def yaml_dict(self):
  155. ''' getter method for yaml_dict '''
  156. return self.__yaml_dict
  157. @yaml_dict.setter
  158. def yaml_dict(self, value):
  159. ''' setter method for yaml_dict '''
  160. self.__yaml_dict = value
  161. @staticmethod
  162. def parse_key(key, sep='.'):
  163. '''parse the key allowing the appropriate separator'''
  164. common_separators = list(Yedit.com_sep - set([sep]))
  165. return re.findall(Yedit.re_key.format(''.join(common_separators)), key)
  166. @staticmethod
  167. def valid_key(key, sep='.'):
  168. '''validate the incoming key'''
  169. common_separators = list(Yedit.com_sep - set([sep]))
  170. if not re.match(Yedit.re_valid_key.format(''.join(common_separators)), key):
  171. return False
  172. return True
  173. @staticmethod
  174. def remove_entry(data, key, sep='.'):
  175. ''' remove data at location key '''
  176. if key == '' and isinstance(data, dict):
  177. data.clear()
  178. return True
  179. elif key == '' and isinstance(data, list):
  180. del data[:]
  181. return True
  182. if not (key and Yedit.valid_key(key, sep)) and \
  183. isinstance(data, (list, dict)):
  184. return None
  185. key_indexes = Yedit.parse_key(key, sep)
  186. for arr_ind, dict_key in key_indexes[:-1]:
  187. if dict_key and isinstance(data, dict):
  188. data = data.get(dict_key)
  189. elif (arr_ind and isinstance(data, list) and
  190. int(arr_ind) <= len(data) - 1):
  191. data = data[int(arr_ind)]
  192. else:
  193. return None
  194. # process last index for remove
  195. # expected list entry
  196. if key_indexes[-1][0]:
  197. if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  198. del data[int(key_indexes[-1][0])]
  199. return True
  200. # expected dict entry
  201. elif key_indexes[-1][1]:
  202. if isinstance(data, dict):
  203. del data[key_indexes[-1][1]]
  204. return True
  205. @staticmethod
  206. def add_entry(data, key, item=None, sep='.'):
  207. ''' Get an item from a dictionary with key notation a.b.c
  208. d = {'a': {'b': 'c'}}}
  209. key = a#b
  210. return c
  211. '''
  212. if key == '':
  213. pass
  214. elif (not (key and Yedit.valid_key(key, sep)) and
  215. isinstance(data, (list, dict))):
  216. return None
  217. key_indexes = Yedit.parse_key(key, sep)
  218. for arr_ind, dict_key in key_indexes[:-1]:
  219. if dict_key:
  220. if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
  221. data = data[dict_key]
  222. continue
  223. elif data and not isinstance(data, dict):
  224. raise YeditException("Unexpected item type found while going through key " +
  225. "path: {} (at key: {})".format(key, dict_key))
  226. data[dict_key] = {}
  227. data = data[dict_key]
  228. elif (arr_ind and isinstance(data, list) and
  229. int(arr_ind) <= len(data) - 1):
  230. data = data[int(arr_ind)]
  231. else:
  232. raise YeditException("Unexpected item type found while going through key path: {}".format(key))
  233. if key == '':
  234. data = item
  235. # process last index for add
  236. # expected list entry
  237. elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  238. data[int(key_indexes[-1][0])] = item
  239. # expected dict entry
  240. elif key_indexes[-1][1] and isinstance(data, dict):
  241. data[key_indexes[-1][1]] = item
  242. # didn't add/update to an existing list, nor add/update key to a dict
  243. # so we must have been provided some syntax like a.b.c[<int>] = "data" for a
  244. # non-existent array
  245. else:
  246. raise YeditException("Error adding to object at path: {}".format(key))
  247. return data
  248. @staticmethod
  249. def get_entry(data, key, sep='.'):
  250. ''' Get an item from a dictionary with key notation a.b.c
  251. d = {'a': {'b': 'c'}}}
  252. key = a.b
  253. return c
  254. '''
  255. if key == '':
  256. pass
  257. elif (not (key and Yedit.valid_key(key, sep)) and
  258. isinstance(data, (list, dict))):
  259. return None
  260. key_indexes = Yedit.parse_key(key, sep)
  261. for arr_ind, dict_key in key_indexes:
  262. if dict_key and isinstance(data, dict):
  263. data = data.get(dict_key)
  264. elif (arr_ind and isinstance(data, list) and
  265. int(arr_ind) <= len(data) - 1):
  266. data = data[int(arr_ind)]
  267. else:
  268. return None
  269. return data
  270. @staticmethod
  271. def _write(filename, contents):
  272. ''' Actually write the file contents to disk. This helps with mocking. '''
  273. tmp_filename = filename + '.yedit'
  274. with open(tmp_filename, 'w') as yfd:
  275. yfd.write(contents)
  276. os.rename(tmp_filename, filename)
  277. def write(self):
  278. ''' write to file '''
  279. if not self.filename:
  280. raise YeditException('Please specify a filename.')
  281. if self.backup and self.file_exists():
  282. shutil.copy(self.filename, self.filename + '.orig')
  283. # Try to set format attributes if supported
  284. try:
  285. self.yaml_dict.fa.set_block_style()
  286. except AttributeError:
  287. pass
  288. # Try to use RoundTripDumper if supported.
  289. if self.content_type == 'yaml':
  290. try:
  291. Yedit._write(self.filename, yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
  292. except AttributeError:
  293. Yedit._write(self.filename, yaml.safe_dump(self.yaml_dict, default_flow_style=False))
  294. elif self.content_type == 'json':
  295. Yedit._write(self.filename, json.dumps(self.yaml_dict, indent=4, sort_keys=True))
  296. else:
  297. raise YeditException('Unsupported content_type: {}.'.format(self.content_type) +
  298. 'Please specify a content_type of yaml or json.')
  299. return (True, self.yaml_dict)
  300. def read(self):
  301. ''' read from file '''
  302. # check if it exists
  303. if self.filename is None or not self.file_exists():
  304. return None
  305. contents = None
  306. with open(self.filename) as yfd:
  307. contents = yfd.read()
  308. return contents
  309. def file_exists(self):
  310. ''' return whether file exists '''
  311. if os.path.exists(self.filename):
  312. return True
  313. return False
  314. def load(self, content_type='yaml'):
  315. ''' return yaml file '''
  316. contents = self.read()
  317. if not contents and not self.content:
  318. return None
  319. if self.content:
  320. if isinstance(self.content, dict):
  321. self.yaml_dict = self.content
  322. return self.yaml_dict
  323. elif isinstance(self.content, str):
  324. contents = self.content
  325. # check if it is yaml
  326. try:
  327. if content_type == 'yaml' and contents:
  328. # Try to set format attributes if supported
  329. try:
  330. self.yaml_dict.fa.set_block_style()
  331. except AttributeError:
  332. pass
  333. # Try to use RoundTripLoader if supported.
  334. try:
  335. self.yaml_dict = yaml.load(contents, yaml.RoundTripLoader)
  336. except AttributeError:
  337. self.yaml_dict = yaml.safe_load(contents)
  338. # Try to set format attributes if supported
  339. try:
  340. self.yaml_dict.fa.set_block_style()
  341. except AttributeError:
  342. pass
  343. elif content_type == 'json' and contents:
  344. self.yaml_dict = json.loads(contents)
  345. except yaml.YAMLError as err:
  346. # Error loading yaml or json
  347. raise YeditException('Problem with loading yaml file. {}'.format(err))
  348. return self.yaml_dict
  349. def get(self, key):
  350. ''' get a specified key'''
  351. try:
  352. entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
  353. except KeyError:
  354. entry = None
  355. return entry
  356. def pop(self, path, key_or_item):
  357. ''' remove a key, value pair from a dict or an item for a list'''
  358. try:
  359. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  360. except KeyError:
  361. entry = None
  362. if entry is None:
  363. return (False, self.yaml_dict)
  364. if isinstance(entry, dict):
  365. # AUDIT:maybe-no-member makes sense due to fuzzy types
  366. # pylint: disable=maybe-no-member
  367. if key_or_item in entry:
  368. entry.pop(key_or_item)
  369. return (True, self.yaml_dict)
  370. return (False, self.yaml_dict)
  371. elif isinstance(entry, list):
  372. # AUDIT:maybe-no-member makes sense due to fuzzy types
  373. # pylint: disable=maybe-no-member
  374. ind = None
  375. try:
  376. ind = entry.index(key_or_item)
  377. except ValueError:
  378. return (False, self.yaml_dict)
  379. entry.pop(ind)
  380. return (True, self.yaml_dict)
  381. return (False, self.yaml_dict)
  382. def delete(self, path):
  383. ''' remove path from a dict'''
  384. try:
  385. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  386. except KeyError:
  387. entry = None
  388. if entry is None:
  389. return (False, self.yaml_dict)
  390. result = Yedit.remove_entry(self.yaml_dict, path, self.separator)
  391. if not result:
  392. return (False, self.yaml_dict)
  393. return (True, self.yaml_dict)
  394. def exists(self, path, value):
  395. ''' check if value exists at path'''
  396. try:
  397. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  398. except KeyError:
  399. entry = None
  400. if isinstance(entry, list):
  401. if value in entry:
  402. return True
  403. return False
  404. elif isinstance(entry, dict):
  405. if isinstance(value, dict):
  406. rval = False
  407. for key, val in value.items():
  408. if entry[key] != val:
  409. rval = False
  410. break
  411. else:
  412. rval = True
  413. return rval
  414. return value in entry
  415. return entry == value
  416. def append(self, path, value):
  417. '''append value to a list'''
  418. try:
  419. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  420. except KeyError:
  421. entry = None
  422. if entry is None:
  423. self.put(path, [])
  424. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  425. if not isinstance(entry, list):
  426. return (False, self.yaml_dict)
  427. # AUDIT:maybe-no-member makes sense due to loading data from
  428. # a serialized format.
  429. # pylint: disable=maybe-no-member
  430. entry.append(value)
  431. return (True, self.yaml_dict)
  432. # pylint: disable=too-many-arguments
  433. def update(self, path, value, index=None, curr_value=None):
  434. ''' put path, value into a dict '''
  435. try:
  436. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  437. except KeyError:
  438. entry = None
  439. if isinstance(entry, dict):
  440. # AUDIT:maybe-no-member makes sense due to fuzzy types
  441. # pylint: disable=maybe-no-member
  442. if not isinstance(value, dict):
  443. raise YeditException('Cannot replace key, value entry in dict with non-dict type. ' +
  444. 'value=[{}] type=[{}]'.format(value, type(value)))
  445. entry.update(value)
  446. return (True, self.yaml_dict)
  447. elif isinstance(entry, list):
  448. # AUDIT:maybe-no-member makes sense due to fuzzy types
  449. # pylint: disable=maybe-no-member
  450. ind = None
  451. if curr_value:
  452. try:
  453. ind = entry.index(curr_value)
  454. except ValueError:
  455. return (False, self.yaml_dict)
  456. elif index is not None:
  457. ind = index
  458. if ind is not None and entry[ind] != value:
  459. entry[ind] = value
  460. return (True, self.yaml_dict)
  461. # see if it exists in the list
  462. try:
  463. ind = entry.index(value)
  464. except ValueError:
  465. # doesn't exist, append it
  466. entry.append(value)
  467. return (True, self.yaml_dict)
  468. # already exists, return
  469. if ind is not None:
  470. return (False, self.yaml_dict)
  471. return (False, self.yaml_dict)
  472. def put(self, path, value):
  473. ''' put path, value into a dict '''
  474. try:
  475. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  476. except KeyError:
  477. entry = None
  478. if entry == value:
  479. return (False, self.yaml_dict)
  480. # deepcopy didn't work
  481. # Try to use ruamel.yaml and fallback to pyyaml
  482. try:
  483. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  484. default_flow_style=False),
  485. yaml.RoundTripLoader)
  486. except AttributeError:
  487. tmp_copy = copy.deepcopy(self.yaml_dict)
  488. # set the format attributes if available
  489. try:
  490. tmp_copy.fa.set_block_style()
  491. except AttributeError:
  492. pass
  493. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  494. if result is None:
  495. return (False, self.yaml_dict)
  496. # When path equals "" it is a special case.
  497. # "" refers to the root of the document
  498. # Only update the root path (entire document) when its a list or dict
  499. if path == '':
  500. if isinstance(result, list) or isinstance(result, dict):
  501. self.yaml_dict = result
  502. return (True, self.yaml_dict)
  503. return (False, self.yaml_dict)
  504. self.yaml_dict = tmp_copy
  505. return (True, self.yaml_dict)
  506. def create(self, path, value):
  507. ''' create a yaml file '''
  508. if not self.file_exists():
  509. # deepcopy didn't work
  510. # Try to use ruamel.yaml and fallback to pyyaml
  511. try:
  512. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  513. default_flow_style=False),
  514. yaml.RoundTripLoader)
  515. except AttributeError:
  516. tmp_copy = copy.deepcopy(self.yaml_dict)
  517. # set the format attributes if available
  518. try:
  519. tmp_copy.fa.set_block_style()
  520. except AttributeError:
  521. pass
  522. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  523. if result is not None:
  524. self.yaml_dict = tmp_copy
  525. return (True, self.yaml_dict)
  526. return (False, self.yaml_dict)
  527. @staticmethod
  528. def get_curr_value(invalue, val_type):
  529. '''return the current value'''
  530. if invalue is None:
  531. return None
  532. curr_value = invalue
  533. if val_type == 'yaml':
  534. try:
  535. # AUDIT:maybe-no-member makes sense due to different yaml libraries
  536. # pylint: disable=maybe-no-member
  537. curr_value = yaml.safe_load(invalue, Loader=yaml.RoundTripLoader)
  538. except AttributeError:
  539. curr_value = yaml.safe_load(invalue)
  540. elif val_type == 'json':
  541. curr_value = json.loads(invalue)
  542. return curr_value
  543. @staticmethod
  544. def parse_value(inc_value, vtype=''):
  545. '''determine value type passed'''
  546. true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE',
  547. 'on', 'On', 'ON', ]
  548. false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE',
  549. 'off', 'Off', 'OFF']
  550. # It came in as a string but you didn't specify value_type as string
  551. # we will convert to bool if it matches any of the above cases
  552. if isinstance(inc_value, str) and 'bool' in vtype:
  553. if inc_value not in true_bools and inc_value not in false_bools:
  554. raise YeditException('Not a boolean type. str=[{}] vtype=[{}]'.format(inc_value, vtype))
  555. elif isinstance(inc_value, bool) and 'str' in vtype:
  556. inc_value = str(inc_value)
  557. # There is a special case where '' will turn into None after yaml loading it so skip
  558. if isinstance(inc_value, str) and inc_value == '':
  559. pass
  560. # If vtype is not str then go ahead and attempt to yaml load it.
  561. elif isinstance(inc_value, str) and 'str' not in vtype:
  562. try:
  563. inc_value = yaml.safe_load(inc_value)
  564. except Exception:
  565. raise YeditException('Could not determine type of incoming value. ' +
  566. 'value=[{}] vtype=[{}]'.format(type(inc_value), vtype))
  567. return inc_value
  568. @staticmethod
  569. def process_edits(edits, yamlfile):
  570. '''run through a list of edits and process them one-by-one'''
  571. results = []
  572. for edit in edits:
  573. value = Yedit.parse_value(edit['value'], edit.get('value_type', ''))
  574. if edit.get('action') == 'update':
  575. # pylint: disable=line-too-long
  576. curr_value = Yedit.get_curr_value(
  577. Yedit.parse_value(edit.get('curr_value')),
  578. edit.get('curr_value_format'))
  579. rval = yamlfile.update(edit['key'],
  580. value,
  581. edit.get('index'),
  582. curr_value)
  583. elif edit.get('action') == 'append':
  584. rval = yamlfile.append(edit['key'], value)
  585. else:
  586. rval = yamlfile.put(edit['key'], value)
  587. if rval[0]:
  588. results.append({'key': edit['key'], 'edit': rval[1]})
  589. return {'changed': len(results) > 0, 'results': results}
  590. # pylint: disable=too-many-return-statements,too-many-branches
  591. @staticmethod
  592. def run_ansible(params):
  593. '''perform the idempotent crud operations'''
  594. yamlfile = Yedit(filename=params['src'],
  595. backup=params['backup'],
  596. content_type=params['content_type'],
  597. separator=params['separator'])
  598. state = params['state']
  599. if params['src']:
  600. rval = yamlfile.load()
  601. if yamlfile.yaml_dict is None and state != 'present':
  602. return {'failed': True,
  603. 'msg': 'Error opening file [{}]. Verify that the '.format(params['src']) +
  604. 'file exists, that it is has correct permissions, and is valid yaml.'}
  605. if state == 'list':
  606. if params['content']:
  607. content = Yedit.parse_value(params['content'], params['content_type'])
  608. yamlfile.yaml_dict = content
  609. if params['key']:
  610. rval = yamlfile.get(params['key'])
  611. return {'changed': False, 'result': rval, 'state': state}
  612. elif state == 'absent':
  613. if params['content']:
  614. content = Yedit.parse_value(params['content'], params['content_type'])
  615. yamlfile.yaml_dict = content
  616. if params['update']:
  617. rval = yamlfile.pop(params['key'], params['value'])
  618. else:
  619. rval = yamlfile.delete(params['key'])
  620. if rval[0] and params['src']:
  621. yamlfile.write()
  622. return {'changed': rval[0], 'result': rval[1], 'state': state}
  623. elif state == 'present':
  624. # check if content is different than what is in the file
  625. if params['content']:
  626. content = Yedit.parse_value(params['content'], params['content_type'])
  627. # We had no edits to make and the contents are the same
  628. if yamlfile.yaml_dict == content and \
  629. params['value'] is None:
  630. return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
  631. yamlfile.yaml_dict = content
  632. # If we were passed a key, value then
  633. # we enapsulate it in a list and process it
  634. # Key, Value passed to the module : Converted to Edits list #
  635. edits = []
  636. _edit = {}
  637. if params['value'] is not None:
  638. _edit['value'] = params['value']
  639. _edit['value_type'] = params['value_type']
  640. _edit['key'] = params['key']
  641. if params['update']:
  642. _edit['action'] = 'update'
  643. _edit['curr_value'] = params['curr_value']
  644. _edit['curr_value_format'] = params['curr_value_format']
  645. _edit['index'] = params['index']
  646. elif params['append']:
  647. _edit['action'] = 'append'
  648. edits.append(_edit)
  649. elif params['edits'] is not None:
  650. edits = params['edits']
  651. if edits:
  652. results = Yedit.process_edits(edits, yamlfile)
  653. # if there were changes and a src provided to us we need to write
  654. if results['changed'] and params['src']:
  655. yamlfile.write()
  656. return {'changed': results['changed'], 'result': results['results'], 'state': state}
  657. # no edits to make
  658. if params['src']:
  659. # pylint: disable=redefined-variable-type
  660. rval = yamlfile.write()
  661. return {'changed': rval[0],
  662. 'result': rval[1],
  663. 'state': state}
  664. # We were passed content but no src, key or value, or edits. Return contents in memory
  665. return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
  666. return {'failed': True, 'msg': 'Unkown state passed'}
  667. # -*- -*- -*- End included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  668. # -*- -*- -*- Begin included fragment: lib/base.py -*- -*- -*-
  669. # pylint: disable=too-many-lines
  670. # noqa: E301,E302,E303,T001
  671. class OpenShiftCLIError(Exception):
  672. '''Exception class for openshiftcli'''
  673. pass
  674. ADDITIONAL_PATH_LOOKUPS = ['/usr/local/bin', os.path.expanduser('~/bin')]
  675. def locate_oc_binary():
  676. ''' Find and return oc binary file '''
  677. # https://github.com/openshift/openshift-ansible/issues/3410
  678. # oc can be in /usr/local/bin in some cases, but that may not
  679. # be in $PATH due to ansible/sudo
  680. paths = os.environ.get("PATH", os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS
  681. oc_binary = 'oc'
  682. # Use shutil.which if it is available, otherwise fallback to a naive path search
  683. try:
  684. which_result = shutil.which(oc_binary, path=os.pathsep.join(paths))
  685. if which_result is not None:
  686. oc_binary = which_result
  687. except AttributeError:
  688. for path in paths:
  689. if os.path.exists(os.path.join(path, oc_binary)):
  690. oc_binary = os.path.join(path, oc_binary)
  691. break
  692. return oc_binary
  693. # pylint: disable=too-few-public-methods
  694. class OpenShiftCLI(object):
  695. ''' Class to wrap the command line tools '''
  696. def __init__(self,
  697. namespace,
  698. kubeconfig='/etc/origin/master/admin.kubeconfig',
  699. verbose=False,
  700. all_namespaces=False):
  701. ''' Constructor for OpenshiftCLI '''
  702. self.namespace = namespace
  703. self.verbose = verbose
  704. self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
  705. self.all_namespaces = all_namespaces
  706. self.oc_binary = locate_oc_binary()
  707. # Pylint allows only 5 arguments to be passed.
  708. # pylint: disable=too-many-arguments
  709. def _replace_content(self, resource, rname, content, force=False, sep='.'):
  710. ''' replace the current object with the content '''
  711. res = self._get(resource, rname)
  712. if not res['results']:
  713. return res
  714. fname = Utils.create_tmpfile(rname + '-')
  715. yed = Yedit(fname, res['results'][0], separator=sep)
  716. changes = []
  717. for key, value in content.items():
  718. changes.append(yed.put(key, value))
  719. if any([change[0] for change in changes]):
  720. yed.write()
  721. atexit.register(Utils.cleanup, [fname])
  722. return self._replace(fname, force)
  723. return {'returncode': 0, 'updated': False}
  724. def _replace(self, fname, force=False):
  725. '''replace the current object with oc replace'''
  726. # We are removing the 'resourceVersion' to handle
  727. # a race condition when modifying oc objects
  728. yed = Yedit(fname)
  729. results = yed.delete('metadata.resourceVersion')
  730. if results[0]:
  731. yed.write()
  732. cmd = ['replace', '-f', fname]
  733. if force:
  734. cmd.append('--force')
  735. return self.openshift_cmd(cmd)
  736. def _create_from_content(self, rname, content):
  737. '''create a temporary file and then call oc create on it'''
  738. fname = Utils.create_tmpfile(rname + '-')
  739. yed = Yedit(fname, content=content)
  740. yed.write()
  741. atexit.register(Utils.cleanup, [fname])
  742. return self._create(fname)
  743. def _create(self, fname):
  744. '''call oc create on a filename'''
  745. return self.openshift_cmd(['create', '-f', fname])
  746. def _delete(self, resource, name=None, selector=None):
  747. '''call oc delete on a resource'''
  748. cmd = ['delete', resource]
  749. if selector is not None:
  750. cmd.append('--selector={}'.format(selector))
  751. elif name is not None:
  752. cmd.append(name)
  753. else:
  754. raise OpenShiftCLIError('Either name or selector is required when calling delete.')
  755. return self.openshift_cmd(cmd)
  756. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  757. '''process a template
  758. template_name: the name of the template to process
  759. create: whether to send to oc create after processing
  760. params: the parameters for the template
  761. template_data: the incoming template's data; instead of a file
  762. '''
  763. cmd = ['process']
  764. if template_data:
  765. cmd.extend(['-f', '-'])
  766. else:
  767. cmd.append(template_name)
  768. if params:
  769. param_str = ["{}={}".format(key, str(value).replace("'", r'"')) for key, value in params.items()]
  770. cmd.append('-v')
  771. cmd.extend(param_str)
  772. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  773. if results['returncode'] != 0 or not create:
  774. return results
  775. fname = Utils.create_tmpfile(template_name + '-')
  776. yed = Yedit(fname, results['results'])
  777. yed.write()
  778. atexit.register(Utils.cleanup, [fname])
  779. return self.openshift_cmd(['create', '-f', fname])
  780. def _get(self, resource, name=None, selector=None):
  781. '''return a resource by name '''
  782. cmd = ['get', resource]
  783. if selector is not None:
  784. cmd.append('--selector={}'.format(selector))
  785. elif name is not None:
  786. cmd.append(name)
  787. cmd.extend(['-o', 'json'])
  788. rval = self.openshift_cmd(cmd, output=True)
  789. # Ensure results are retuned in an array
  790. if 'items' in rval:
  791. rval['results'] = rval['items']
  792. elif not isinstance(rval['results'], list):
  793. rval['results'] = [rval['results']]
  794. return rval
  795. def _schedulable(self, node=None, selector=None, schedulable=True):
  796. ''' perform oadm manage-node scheduable '''
  797. cmd = ['manage-node']
  798. if node:
  799. cmd.extend(node)
  800. else:
  801. cmd.append('--selector={}'.format(selector))
  802. cmd.append('--schedulable={}'.format(schedulable))
  803. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  804. def _list_pods(self, node=None, selector=None, pod_selector=None):
  805. ''' perform oadm list pods
  806. node: the node in which to list pods
  807. selector: the label selector filter if provided
  808. pod_selector: the pod selector filter if provided
  809. '''
  810. cmd = ['manage-node']
  811. if node:
  812. cmd.extend(node)
  813. else:
  814. cmd.append('--selector={}'.format(selector))
  815. if pod_selector:
  816. cmd.append('--pod-selector={}'.format(pod_selector))
  817. cmd.extend(['--list-pods', '-o', 'json'])
  818. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  819. # pylint: disable=too-many-arguments
  820. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  821. ''' perform oadm manage-node evacuate '''
  822. cmd = ['manage-node']
  823. if node:
  824. cmd.extend(node)
  825. else:
  826. cmd.append('--selector={}'.format(selector))
  827. if dry_run:
  828. cmd.append('--dry-run')
  829. if pod_selector:
  830. cmd.append('--pod-selector={}'.format(pod_selector))
  831. if grace_period:
  832. cmd.append('--grace-period={}'.format(int(grace_period)))
  833. if force:
  834. cmd.append('--force')
  835. cmd.append('--evacuate')
  836. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  837. def _version(self):
  838. ''' return the openshift version'''
  839. return self.openshift_cmd(['version'], output=True, output_type='raw')
  840. def _import_image(self, url=None, name=None, tag=None):
  841. ''' perform image import '''
  842. cmd = ['import-image']
  843. image = '{0}'.format(name)
  844. if tag:
  845. image += ':{0}'.format(tag)
  846. cmd.append(image)
  847. if url:
  848. cmd.append('--from={0}/{1}'.format(url, image))
  849. cmd.append('-n{0}'.format(self.namespace))
  850. cmd.append('--confirm')
  851. return self.openshift_cmd(cmd)
  852. def _run(self, cmds, input_data):
  853. ''' Actually executes the command. This makes mocking easier. '''
  854. curr_env = os.environ.copy()
  855. curr_env.update({'KUBECONFIG': self.kubeconfig})
  856. proc = subprocess.Popen(cmds,
  857. stdin=subprocess.PIPE,
  858. stdout=subprocess.PIPE,
  859. stderr=subprocess.PIPE,
  860. env=curr_env)
  861. stdout, stderr = proc.communicate(input_data)
  862. return proc.returncode, stdout.decode('utf-8'), stderr.decode('utf-8')
  863. # pylint: disable=too-many-arguments,too-many-branches
  864. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  865. '''Base command for oc '''
  866. cmds = [self.oc_binary]
  867. if oadm:
  868. cmds.append('adm')
  869. cmds.extend(cmd)
  870. if self.all_namespaces:
  871. cmds.extend(['--all-namespaces'])
  872. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  873. cmds.extend(['-n', self.namespace])
  874. if self.verbose:
  875. print(' '.join(cmds))
  876. try:
  877. returncode, stdout, stderr = self._run(cmds, input_data)
  878. except OSError as ex:
  879. returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
  880. rval = {"returncode": returncode,
  881. "cmd": ' '.join(cmds)}
  882. if output_type == 'json':
  883. rval['results'] = {}
  884. if output and stdout:
  885. try:
  886. rval['results'] = json.loads(stdout)
  887. except ValueError as verr:
  888. if "No JSON object could be decoded" in verr.args:
  889. rval['err'] = verr.args
  890. elif output_type == 'raw':
  891. rval['results'] = stdout if output else ''
  892. if self.verbose:
  893. print("STDOUT: {0}".format(stdout))
  894. print("STDERR: {0}".format(stderr))
  895. if 'err' in rval or returncode != 0:
  896. rval.update({"stderr": stderr,
  897. "stdout": stdout})
  898. return rval
  899. class Utils(object): # pragma: no cover
  900. ''' utilities for openshiftcli modules '''
  901. @staticmethod
  902. def _write(filename, contents):
  903. ''' Actually write the file contents to disk. This helps with mocking. '''
  904. with open(filename, 'w') as sfd:
  905. sfd.write(str(contents))
  906. @staticmethod
  907. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  908. ''' create a file in tmp with name and contents'''
  909. tmp = Utils.create_tmpfile(prefix=rname)
  910. if ftype == 'yaml':
  911. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  912. # pylint: disable=no-member
  913. if hasattr(yaml, 'RoundTripDumper'):
  914. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  915. else:
  916. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  917. elif ftype == 'json':
  918. Utils._write(tmp, json.dumps(data))
  919. else:
  920. Utils._write(tmp, data)
  921. # Register cleanup when module is done
  922. atexit.register(Utils.cleanup, [tmp])
  923. return tmp
  924. @staticmethod
  925. def create_tmpfile_copy(inc_file):
  926. '''create a temporary copy of a file'''
  927. tmpfile = Utils.create_tmpfile('lib_openshift-')
  928. Utils._write(tmpfile, open(inc_file).read())
  929. # Cleanup the tmpfile
  930. atexit.register(Utils.cleanup, [tmpfile])
  931. return tmpfile
  932. @staticmethod
  933. def create_tmpfile(prefix='tmp'):
  934. ''' Generates and returns a temporary file name '''
  935. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  936. return tmp.name
  937. @staticmethod
  938. def create_tmp_files_from_contents(content, content_type=None):
  939. '''Turn an array of dict: filename, content into a files array'''
  940. if not isinstance(content, list):
  941. content = [content]
  942. files = []
  943. for item in content:
  944. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  945. item['data'],
  946. ftype=content_type)
  947. files.append({'name': os.path.basename(item['path']),
  948. 'path': path})
  949. return files
  950. @staticmethod
  951. def cleanup(files):
  952. '''Clean up on exit '''
  953. for sfile in files:
  954. if os.path.exists(sfile):
  955. if os.path.isdir(sfile):
  956. shutil.rmtree(sfile)
  957. elif os.path.isfile(sfile):
  958. os.remove(sfile)
  959. @staticmethod
  960. def exists(results, _name):
  961. ''' Check to see if the results include the name '''
  962. if not results:
  963. return False
  964. if Utils.find_result(results, _name):
  965. return True
  966. return False
  967. @staticmethod
  968. def find_result(results, _name):
  969. ''' Find the specified result by name'''
  970. rval = None
  971. for result in results:
  972. if 'metadata' in result and result['metadata']['name'] == _name:
  973. rval = result
  974. break
  975. return rval
  976. @staticmethod
  977. def get_resource_file(sfile, sfile_type='yaml'):
  978. ''' return the service file '''
  979. contents = None
  980. with open(sfile) as sfd:
  981. contents = sfd.read()
  982. if sfile_type == 'yaml':
  983. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  984. # pylint: disable=no-member
  985. if hasattr(yaml, 'RoundTripLoader'):
  986. contents = yaml.load(contents, yaml.RoundTripLoader)
  987. else:
  988. contents = yaml.safe_load(contents)
  989. elif sfile_type == 'json':
  990. contents = json.loads(contents)
  991. return contents
  992. @staticmethod
  993. def filter_versions(stdout):
  994. ''' filter the oc version output '''
  995. version_dict = {}
  996. version_search = ['oc', 'openshift', 'kubernetes']
  997. for line in stdout.strip().split('\n'):
  998. for term in version_search:
  999. if not line:
  1000. continue
  1001. if line.startswith(term):
  1002. version_dict[term] = line.split()[-1]
  1003. # horrible hack to get openshift version in Openshift 3.2
  1004. # By default "oc version in 3.2 does not return an "openshift" version
  1005. if "openshift" not in version_dict:
  1006. version_dict["openshift"] = version_dict["oc"]
  1007. return version_dict
  1008. @staticmethod
  1009. def add_custom_versions(versions):
  1010. ''' create custom versions strings '''
  1011. versions_dict = {}
  1012. for tech, version in versions.items():
  1013. # clean up "-" from version
  1014. if "-" in version:
  1015. version = version.split("-")[0]
  1016. if version.startswith('v'):
  1017. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  1018. # "v3.3.0.33" is what we have, we want "3.3"
  1019. versions_dict[tech + '_short'] = version[1:4]
  1020. return versions_dict
  1021. @staticmethod
  1022. def openshift_installed():
  1023. ''' check if openshift is installed '''
  1024. import rpm
  1025. transaction_set = rpm.TransactionSet()
  1026. rpmquery = transaction_set.dbMatch("name", "atomic-openshift")
  1027. return rpmquery.count() > 0
  1028. # Disabling too-many-branches. This is a yaml dictionary comparison function
  1029. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  1030. @staticmethod
  1031. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  1032. ''' Given a user defined definition, compare it with the results given back by our query. '''
  1033. # Currently these values are autogenerated and we do not need to check them
  1034. skip = ['metadata', 'status']
  1035. if skip_keys:
  1036. skip.extend(skip_keys)
  1037. for key, value in result_def.items():
  1038. if key in skip:
  1039. continue
  1040. # Both are lists
  1041. if isinstance(value, list):
  1042. if key not in user_def:
  1043. if debug:
  1044. print('User data does not have key [%s]' % key)
  1045. print('User data: %s' % user_def)
  1046. return False
  1047. if not isinstance(user_def[key], list):
  1048. if debug:
  1049. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  1050. return False
  1051. if len(user_def[key]) != len(value):
  1052. if debug:
  1053. print("List lengths are not equal.")
  1054. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  1055. print("user_def: %s" % user_def[key])
  1056. print("value: %s" % value)
  1057. return False
  1058. for values in zip(user_def[key], value):
  1059. if isinstance(values[0], dict) and isinstance(values[1], dict):
  1060. if debug:
  1061. print('sending list - list')
  1062. print(type(values[0]))
  1063. print(type(values[1]))
  1064. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  1065. if not result:
  1066. print('list compare returned false')
  1067. return False
  1068. elif value != user_def[key]:
  1069. if debug:
  1070. print('value should be identical')
  1071. print(user_def[key])
  1072. print(value)
  1073. return False
  1074. # recurse on a dictionary
  1075. elif isinstance(value, dict):
  1076. if key not in user_def:
  1077. if debug:
  1078. print("user_def does not have key [%s]" % key)
  1079. return False
  1080. if not isinstance(user_def[key], dict):
  1081. if debug:
  1082. print("dict returned false: not instance of dict")
  1083. return False
  1084. # before passing ensure keys match
  1085. api_values = set(value.keys()) - set(skip)
  1086. user_values = set(user_def[key].keys()) - set(skip)
  1087. if api_values != user_values:
  1088. if debug:
  1089. print("keys are not equal in dict")
  1090. print(user_values)
  1091. print(api_values)
  1092. return False
  1093. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1094. if not result:
  1095. if debug:
  1096. print("dict returned false")
  1097. print(result)
  1098. return False
  1099. # Verify each key, value pair is the same
  1100. else:
  1101. if key not in user_def or value != user_def[key]:
  1102. if debug:
  1103. print("value not equal; user_def does not have key")
  1104. print(key)
  1105. print(value)
  1106. if key in user_def:
  1107. print(user_def[key])
  1108. return False
  1109. if debug:
  1110. print('returning true')
  1111. return True
  1112. class OpenShiftCLIConfig(object):
  1113. '''Generic Config'''
  1114. def __init__(self, rname, namespace, kubeconfig, options):
  1115. self.kubeconfig = kubeconfig
  1116. self.name = rname
  1117. self.namespace = namespace
  1118. self._options = options
  1119. @property
  1120. def config_options(self):
  1121. ''' return config options '''
  1122. return self._options
  1123. def to_option_list(self, ascommalist=''):
  1124. '''return all options as a string
  1125. if ascommalist is set to the name of a key, and
  1126. the value of that key is a dict, format the dict
  1127. as a list of comma delimited key=value pairs'''
  1128. return self.stringify(ascommalist)
  1129. def stringify(self, ascommalist=''):
  1130. ''' return the options hash as cli params in a string
  1131. if ascommalist is set to the name of a key, and
  1132. the value of that key is a dict, format the dict
  1133. as a list of comma delimited key=value pairs '''
  1134. rval = []
  1135. for key in sorted(self.config_options.keys()):
  1136. data = self.config_options[key]
  1137. if data['include'] \
  1138. and (data['value'] is not None or isinstance(data['value'], int)):
  1139. if key == ascommalist:
  1140. val = ','.join(['{}={}'.format(kk, vv) for kk, vv in sorted(data['value'].items())])
  1141. else:
  1142. val = data['value']
  1143. rval.append('--{}={}'.format(key.replace('_', '-'), val))
  1144. return rval
  1145. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1146. # -*- -*- -*- Begin included fragment: lib/rolebinding.py -*- -*- -*-
  1147. # pylint: disable=too-many-instance-attributes
  1148. class RoleBindingConfig(object):
  1149. ''' Handle rolebinding config '''
  1150. # pylint: disable=too-many-arguments
  1151. def __init__(self,
  1152. name,
  1153. namespace,
  1154. kubeconfig,
  1155. group_names=None,
  1156. role_ref=None,
  1157. subjects=None,
  1158. usernames=None):
  1159. ''' constructor for handling rolebinding options '''
  1160. self.kubeconfig = kubeconfig
  1161. self.name = name
  1162. self.namespace = namespace
  1163. self.group_names = group_names
  1164. self.role_ref = role_ref
  1165. self.subjects = subjects
  1166. self.usernames = usernames
  1167. self.data = {}
  1168. self.create_dict()
  1169. def create_dict(self):
  1170. ''' create a default rolebinding as a dict '''
  1171. self.data['apiVersion'] = 'v1'
  1172. self.data['kind'] = 'RoleBinding'
  1173. self.data['groupNames'] = self.group_names
  1174. self.data['metadata']['name'] = self.name
  1175. self.data['metadata']['namespace'] = self.namespace
  1176. self.data['roleRef'] = self.role_ref
  1177. self.data['subjects'] = self.subjects
  1178. self.data['userNames'] = self.usernames
  1179. # pylint: disable=too-many-instance-attributes,too-many-public-methods
  1180. class RoleBinding(Yedit):
  1181. ''' Class to model a rolebinding openshift object'''
  1182. group_names_path = "groupNames"
  1183. role_ref_path = "roleRef"
  1184. subjects_path = "subjects"
  1185. user_names_path = "userNames"
  1186. kind = 'RoleBinding'
  1187. def __init__(self, content):
  1188. '''RoleBinding constructor'''
  1189. super(RoleBinding, self).__init__(content=content)
  1190. self._subjects = None
  1191. self._role_ref = None
  1192. self._group_names = None
  1193. self._user_names = None
  1194. @property
  1195. def subjects(self):
  1196. ''' subjects property '''
  1197. if self._subjects is None:
  1198. self._subjects = self.get_subjects()
  1199. return self._subjects
  1200. @subjects.setter
  1201. def subjects(self, data):
  1202. ''' subjects property setter'''
  1203. self._subjects = data
  1204. @property
  1205. def role_ref(self):
  1206. ''' role_ref property '''
  1207. if self._role_ref is None:
  1208. self._role_ref = self.get_role_ref()
  1209. return self._role_ref
  1210. @role_ref.setter
  1211. def role_ref(self, data):
  1212. ''' role_ref property setter'''
  1213. self._role_ref = data
  1214. @property
  1215. def group_names(self):
  1216. ''' group_names property '''
  1217. if self._group_names is None:
  1218. self._group_names = self.get_group_names()
  1219. return self._group_names
  1220. @group_names.setter
  1221. def group_names(self, data):
  1222. ''' group_names property setter'''
  1223. self._group_names = data
  1224. @property
  1225. def user_names(self):
  1226. ''' user_names property '''
  1227. if self._user_names is None:
  1228. self._user_names = self.get_user_names()
  1229. return self._user_names
  1230. @user_names.setter
  1231. def user_names(self, data):
  1232. ''' user_names property setter'''
  1233. self._user_names = data
  1234. def get_group_names(self):
  1235. ''' return groupNames '''
  1236. return self.get(RoleBinding.group_names_path) or []
  1237. def get_user_names(self):
  1238. ''' return usernames '''
  1239. return self.get(RoleBinding.user_names_path) or []
  1240. def get_role_ref(self):
  1241. ''' return role_ref '''
  1242. return self.get(RoleBinding.role_ref_path) or {}
  1243. def get_subjects(self):
  1244. ''' return subjects '''
  1245. return self.get(RoleBinding.subjects_path) or []
  1246. #### ADD #####
  1247. def add_subject(self, inc_subject):
  1248. ''' add a subject '''
  1249. if self.subjects:
  1250. # pylint: disable=no-member
  1251. self.subjects.append(inc_subject)
  1252. else:
  1253. self.put(RoleBinding.subjects_path, [inc_subject])
  1254. return True
  1255. def add_role_ref(self, inc_role_ref):
  1256. ''' add a role_ref '''
  1257. if not self.role_ref:
  1258. self.put(RoleBinding.role_ref_path, {"name": inc_role_ref})
  1259. return True
  1260. return False
  1261. def add_group_names(self, inc_group_names):
  1262. ''' add a group_names '''
  1263. if self.group_names:
  1264. # pylint: disable=no-member
  1265. self.group_names.append(inc_group_names)
  1266. else:
  1267. self.put(RoleBinding.group_names_path, [inc_group_names])
  1268. return True
  1269. def add_user_name(self, inc_user_name):
  1270. ''' add a username '''
  1271. if self.user_names:
  1272. # pylint: disable=no-member
  1273. self.user_names.append(inc_user_name)
  1274. else:
  1275. self.put(RoleBinding.user_names_path, [inc_user_name])
  1276. return True
  1277. #### /ADD #####
  1278. #### Remove #####
  1279. def remove_subject(self, inc_subject):
  1280. ''' remove a subject '''
  1281. try:
  1282. # pylint: disable=no-member
  1283. self.subjects.remove(inc_subject)
  1284. except ValueError as _:
  1285. return False
  1286. return True
  1287. def remove_role_ref(self, inc_role_ref):
  1288. ''' remove a role_ref '''
  1289. if self.role_ref and self.role_ref['name'] == inc_role_ref:
  1290. del self.role_ref['name']
  1291. return True
  1292. return False
  1293. def remove_group_name(self, inc_group_name):
  1294. ''' remove a groupname '''
  1295. try:
  1296. # pylint: disable=no-member
  1297. self.group_names.remove(inc_group_name)
  1298. except ValueError as _:
  1299. return False
  1300. return True
  1301. def remove_user_name(self, inc_user_name):
  1302. ''' remove a username '''
  1303. try:
  1304. # pylint: disable=no-member
  1305. self.user_names.remove(inc_user_name)
  1306. except ValueError as _:
  1307. return False
  1308. return True
  1309. #### /REMOVE #####
  1310. #### UPDATE #####
  1311. def update_subject(self, inc_subject):
  1312. ''' update a subject '''
  1313. try:
  1314. # pylint: disable=no-member
  1315. index = self.subjects.index(inc_subject)
  1316. except ValueError as _:
  1317. return self.add_subject(inc_subject)
  1318. self.subjects[index] = inc_subject
  1319. return True
  1320. def update_group_name(self, inc_group_name):
  1321. ''' update a groupname '''
  1322. try:
  1323. # pylint: disable=no-member
  1324. index = self.group_names.index(inc_group_name)
  1325. except ValueError as _:
  1326. return self.add_group_names(inc_group_name)
  1327. self.group_names[index] = inc_group_name
  1328. return True
  1329. def update_user_name(self, inc_user_name):
  1330. ''' update a username '''
  1331. try:
  1332. # pylint: disable=no-member
  1333. index = self.user_names.index(inc_user_name)
  1334. except ValueError as _:
  1335. return self.add_user_name(inc_user_name)
  1336. self.user_names[index] = inc_user_name
  1337. return True
  1338. def update_role_ref(self, inc_role_ref):
  1339. ''' update a role_ref '''
  1340. self.role_ref['name'] = inc_role_ref
  1341. return True
  1342. #### /UPDATE #####
  1343. #### FIND ####
  1344. def find_subject(self, inc_subject):
  1345. ''' find a subject '''
  1346. index = None
  1347. try:
  1348. # pylint: disable=no-member
  1349. index = self.subjects.index(inc_subject)
  1350. except ValueError as _:
  1351. return index
  1352. return index
  1353. def find_group_name(self, inc_group_name):
  1354. ''' find a group_name '''
  1355. index = None
  1356. try:
  1357. # pylint: disable=no-member
  1358. index = self.group_names.index(inc_group_name)
  1359. except ValueError as _:
  1360. return index
  1361. return index
  1362. def find_user_name(self, inc_user_name):
  1363. ''' find a user_name '''
  1364. index = None
  1365. try:
  1366. # pylint: disable=no-member
  1367. index = self.user_names.index(inc_user_name)
  1368. except ValueError as _:
  1369. return index
  1370. return index
  1371. def find_role_ref(self, inc_role_ref):
  1372. ''' find a user_name '''
  1373. if self.role_ref and self.role_ref['name'] == inc_role_ref['name']:
  1374. return self.role_ref
  1375. return None
  1376. # -*- -*- -*- End included fragment: lib/rolebinding.py -*- -*- -*-
  1377. # -*- -*- -*- Begin included fragment: lib/scc.py -*- -*- -*-
  1378. # pylint: disable=too-many-instance-attributes
  1379. class SecurityContextConstraintsConfig(object):
  1380. ''' Handle scc options '''
  1381. # pylint: disable=too-many-arguments
  1382. def __init__(self,
  1383. sname,
  1384. kubeconfig,
  1385. options=None,
  1386. fs_group='MustRunAs',
  1387. default_add_capabilities=None,
  1388. groups=None,
  1389. priority=None,
  1390. required_drop_capabilities=None,
  1391. run_as_user='MustRunAsRange',
  1392. se_linux_context='MustRunAs',
  1393. supplemental_groups='RunAsAny',
  1394. users=None,
  1395. annotations=None):
  1396. ''' constructor for handling scc options '''
  1397. self.kubeconfig = kubeconfig
  1398. self.name = sname
  1399. self.options = options
  1400. self.fs_group = fs_group
  1401. self.default_add_capabilities = default_add_capabilities
  1402. self.groups = groups
  1403. self.priority = priority
  1404. self.required_drop_capabilities = required_drop_capabilities
  1405. self.run_as_user = run_as_user
  1406. self.se_linux_context = se_linux_context
  1407. self.supplemental_groups = supplemental_groups
  1408. self.users = users
  1409. self.annotations = annotations
  1410. self.data = {}
  1411. self.create_dict()
  1412. def create_dict(self):
  1413. ''' assign the correct properties for a scc dict '''
  1414. # allow options
  1415. if self.options:
  1416. for key, value in self.options.items():
  1417. self.data[key] = value
  1418. else:
  1419. self.data['allowHostDirVolumePlugin'] = False
  1420. self.data['allowHostIPC'] = False
  1421. self.data['allowHostNetwork'] = False
  1422. self.data['allowHostPID'] = False
  1423. self.data['allowHostPorts'] = False
  1424. self.data['allowPrivilegedContainer'] = False
  1425. self.data['allowedCapabilities'] = None
  1426. # version
  1427. self.data['apiVersion'] = 'v1'
  1428. # kind
  1429. self.data['kind'] = 'SecurityContextConstraints'
  1430. # defaultAddCapabilities
  1431. self.data['defaultAddCapabilities'] = self.default_add_capabilities
  1432. # fsGroup
  1433. self.data['fsGroup']['type'] = self.fs_group
  1434. # groups
  1435. self.data['groups'] = []
  1436. if self.groups:
  1437. self.data['groups'] = self.groups
  1438. # metadata
  1439. self.data['metadata'] = {}
  1440. self.data['metadata']['name'] = self.name
  1441. if self.annotations:
  1442. for key, value in self.annotations.items():
  1443. self.data['metadata'][key] = value
  1444. # priority
  1445. self.data['priority'] = self.priority
  1446. # requiredDropCapabilities
  1447. self.data['requiredDropCapabilities'] = self.required_drop_capabilities
  1448. # runAsUser
  1449. self.data['runAsUser'] = {'type': self.run_as_user}
  1450. # seLinuxContext
  1451. self.data['seLinuxContext'] = {'type': self.se_linux_context}
  1452. # supplementalGroups
  1453. self.data['supplementalGroups'] = {'type': self.supplemental_groups}
  1454. # users
  1455. self.data['users'] = []
  1456. if self.users:
  1457. self.data['users'] = self.users
  1458. # pylint: disable=too-many-instance-attributes,too-many-public-methods,no-member
  1459. class SecurityContextConstraints(Yedit):
  1460. ''' Class to wrap the oc command line tools '''
  1461. default_add_capabilities_path = "defaultAddCapabilities"
  1462. fs_group_path = "fsGroup"
  1463. groups_path = "groups"
  1464. priority_path = "priority"
  1465. required_drop_capabilities_path = "requiredDropCapabilities"
  1466. run_as_user_path = "runAsUser"
  1467. se_linux_context_path = "seLinuxContext"
  1468. supplemental_groups_path = "supplementalGroups"
  1469. users_path = "users"
  1470. kind = 'SecurityContextConstraints'
  1471. def __init__(self, content):
  1472. '''SecurityContextConstraints constructor'''
  1473. super(SecurityContextConstraints, self).__init__(content=content)
  1474. self._users = None
  1475. self._groups = None
  1476. @property
  1477. def users(self):
  1478. ''' users property getter '''
  1479. if self._users is None:
  1480. self._users = self.get_users()
  1481. return self._users
  1482. @property
  1483. def groups(self):
  1484. ''' groups property getter '''
  1485. if self._groups is None:
  1486. self._groups = self.get_groups()
  1487. return self._groups
  1488. @users.setter
  1489. def users(self, data):
  1490. ''' users property setter'''
  1491. self._users = data
  1492. @groups.setter
  1493. def groups(self, data):
  1494. ''' groups property setter'''
  1495. self._groups = data
  1496. def get_users(self):
  1497. '''get scc users'''
  1498. return self.get(SecurityContextConstraints.users_path) or []
  1499. def get_groups(self):
  1500. '''get scc groups'''
  1501. return self.get(SecurityContextConstraints.groups_path) or []
  1502. def add_user(self, inc_user):
  1503. ''' add a user '''
  1504. if self.users:
  1505. self.users.append(inc_user)
  1506. else:
  1507. self.put(SecurityContextConstraints.users_path, [inc_user])
  1508. return True
  1509. def add_group(self, inc_group):
  1510. ''' add a group '''
  1511. if self.groups:
  1512. self.groups.append(inc_group)
  1513. else:
  1514. self.put(SecurityContextConstraints.groups_path, [inc_group])
  1515. return True
  1516. def remove_user(self, inc_user):
  1517. ''' remove a user '''
  1518. try:
  1519. self.users.remove(inc_user)
  1520. except ValueError as _:
  1521. return False
  1522. return True
  1523. def remove_group(self, inc_group):
  1524. ''' remove a group '''
  1525. try:
  1526. self.groups.remove(inc_group)
  1527. except ValueError as _:
  1528. return False
  1529. return True
  1530. def update_user(self, inc_user):
  1531. ''' update a user '''
  1532. try:
  1533. index = self.users.index(inc_user)
  1534. except ValueError as _:
  1535. return self.add_user(inc_user)
  1536. self.users[index] = inc_user
  1537. return True
  1538. def update_group(self, inc_group):
  1539. ''' update a group '''
  1540. try:
  1541. index = self.groups.index(inc_group)
  1542. except ValueError as _:
  1543. return self.add_group(inc_group)
  1544. self.groups[index] = inc_group
  1545. return True
  1546. def find_user(self, inc_user):
  1547. ''' find a user '''
  1548. index = None
  1549. try:
  1550. index = self.users.index(inc_user)
  1551. except ValueError as _:
  1552. return index
  1553. return index
  1554. def find_group(self, inc_group):
  1555. ''' find a group '''
  1556. index = None
  1557. try:
  1558. index = self.groups.index(inc_group)
  1559. except ValueError as _:
  1560. return index
  1561. return index
  1562. # -*- -*- -*- End included fragment: lib/scc.py -*- -*- -*-
  1563. # -*- -*- -*- Begin included fragment: class/oc_adm_policy_group.py -*- -*- -*-
  1564. class PolicyGroupException(Exception):
  1565. ''' PolicyGroup exception'''
  1566. pass
  1567. class PolicyGroupConfig(OpenShiftCLIConfig):
  1568. ''' PolicyGroupConfig is a DTO for group related policy. '''
  1569. def __init__(self, namespace, kubeconfig, policy_options):
  1570. super(PolicyGroupConfig, self).__init__(policy_options['name']['value'],
  1571. namespace, kubeconfig, policy_options)
  1572. self.kind = self.get_kind()
  1573. self.namespace = namespace
  1574. def get_kind(self):
  1575. ''' return the kind we are working with '''
  1576. if self.config_options['resource_kind']['value'] == 'role':
  1577. return 'rolebinding'
  1578. elif self.config_options['resource_kind']['value'] == 'cluster-role':
  1579. return 'clusterrolebinding'
  1580. elif self.config_options['resource_kind']['value'] == 'scc':
  1581. return 'scc'
  1582. return None
  1583. # pylint: disable=too-many-return-statements
  1584. class PolicyGroup(OpenShiftCLI):
  1585. ''' Class to handle attaching policies to users '''
  1586. def __init__(self,
  1587. config,
  1588. verbose=False):
  1589. ''' Constructor for PolicyGroup '''
  1590. super(PolicyGroup, self).__init__(config.namespace, config.kubeconfig, verbose)
  1591. self.config = config
  1592. self.verbose = verbose
  1593. self._rolebinding = None
  1594. self._scc = None
  1595. self._cluster_role_bindings = None
  1596. self._role_bindings = None
  1597. @property
  1598. def rolebindings(self):
  1599. if self._role_bindings is None:
  1600. results = self._get('rolebindings', None)
  1601. if results['returncode'] != 0:
  1602. raise OpenShiftCLIError('Could not retrieve rolebindings')
  1603. self._role_bindings = results['results'][0]['items']
  1604. return self._role_bindings
  1605. @property
  1606. def clusterrolebindings(self):
  1607. if self._cluster_role_bindings is None:
  1608. results = self._get('clusterrolebindings', None)
  1609. if results['returncode'] != 0:
  1610. raise OpenShiftCLIError('Could not retrieve clusterrolebindings')
  1611. self._cluster_role_bindings = results['results'][0]['items']
  1612. return self._cluster_role_bindings
  1613. @property
  1614. def role_binding(self):
  1615. ''' role_binding getter '''
  1616. return self._rolebinding
  1617. @role_binding.setter
  1618. def role_binding(self, binding):
  1619. ''' role_binding setter '''
  1620. self._rolebinding = binding
  1621. @property
  1622. def security_context_constraint(self):
  1623. ''' security_context_constraint getter '''
  1624. return self._scc
  1625. @security_context_constraint.setter
  1626. def security_context_constraint(self, scc):
  1627. ''' security_context_constraint setter '''
  1628. self._scc = scc
  1629. def get(self):
  1630. '''fetch the desired kind'''
  1631. resource_name = self.config.config_options['name']['value']
  1632. if resource_name == 'cluster-reader':
  1633. resource_name += 's'
  1634. # oc adm policy add-... creates policy bindings with the name
  1635. # "[resource_name]-binding", however some bindings in the system
  1636. # simply use "[resource_name]". So try both.
  1637. results = self._get(self.config.kind, resource_name)
  1638. if results['returncode'] == 0:
  1639. return results
  1640. # Now try -binding naming convention
  1641. return self._get(self.config.kind, resource_name + "-binding")
  1642. def exists_role_binding(self):
  1643. ''' return whether role_binding exists '''
  1644. bindings = None
  1645. if self.config.config_options['resource_kind']['value'] == 'cluster-role':
  1646. bindings = self.clusterrolebindings
  1647. else:
  1648. bindings = self.rolebindings
  1649. if bindings is None:
  1650. return False
  1651. for binding in bindings:
  1652. if binding['roleRef']['name'] == self.config.config_options['name']['value'] and \
  1653. binding['groupNames'] is not None and \
  1654. self.config.config_options['group']['value'] in binding['groupNames']:
  1655. self.role_binding = binding
  1656. return True
  1657. return False
  1658. def exists_scc(self):
  1659. ''' return whether scc exists '''
  1660. results = self.get()
  1661. if results['returncode'] == 0:
  1662. self.security_context_constraint = SecurityContextConstraints(results['results'][0])
  1663. if self.security_context_constraint.find_group(self.config.config_options['group']['value']) != None:
  1664. return True
  1665. return False
  1666. return results
  1667. def exists(self):
  1668. '''does the object exist?'''
  1669. if self.config.config_options['resource_kind']['value'] == 'cluster-role':
  1670. return self.exists_role_binding()
  1671. elif self.config.config_options['resource_kind']['value'] == 'role':
  1672. return self.exists_role_binding()
  1673. elif self.config.config_options['resource_kind']['value'] == 'scc':
  1674. return self.exists_scc()
  1675. return False
  1676. def perform(self):
  1677. '''perform action on resource'''
  1678. cmd = ['policy',
  1679. self.config.config_options['action']['value'],
  1680. self.config.config_options['name']['value'],
  1681. self.config.config_options['group']['value']]
  1682. return self.openshift_cmd(cmd, oadm=True)
  1683. @staticmethod
  1684. def run_ansible(params, check_mode):
  1685. '''run the idempotent ansible code'''
  1686. state = params['state']
  1687. action = None
  1688. if state == 'present':
  1689. action = 'add-' + params['resource_kind'] + '-to-group'
  1690. else:
  1691. action = 'remove-' + params['resource_kind'] + '-from-group'
  1692. nconfig = PolicyGroupConfig(params['namespace'],
  1693. params['kubeconfig'],
  1694. {'action': {'value': action, 'include': False},
  1695. 'group': {'value': params['group'], 'include': False},
  1696. 'resource_kind': {'value': params['resource_kind'], 'include': False},
  1697. 'name': {'value': params['resource_name'], 'include': False},
  1698. })
  1699. policygroup = PolicyGroup(nconfig, params['debug'])
  1700. # Run the oc adm policy group related command
  1701. ########
  1702. # Delete
  1703. ########
  1704. if state == 'absent':
  1705. if not policygroup.exists():
  1706. return {'changed': False, 'state': 'absent'}
  1707. if check_mode:
  1708. return {'changed': False, 'msg': 'CHECK_MODE: would have performed a delete.'}
  1709. api_rval = policygroup.perform()
  1710. if api_rval['returncode'] != 0:
  1711. return {'msg': api_rval}
  1712. return {'changed': True, 'results' : api_rval, state:'absent'}
  1713. if state == 'present':
  1714. ########
  1715. # Create
  1716. ########
  1717. results = policygroup.exists()
  1718. if isinstance(results, dict) and 'returncode' in results and results['returncode'] != 0:
  1719. return {'msg': results}
  1720. if not results:
  1721. if check_mode:
  1722. return {'changed': False, 'msg': 'CHECK_MODE: would have performed a create.'}
  1723. api_rval = policygroup.perform()
  1724. if api_rval['returncode'] != 0:
  1725. return {'msg': api_rval}
  1726. return {'changed': True, 'results': api_rval, state: 'present'}
  1727. return {'changed': False, state: 'present'}
  1728. return {'failed': True, 'changed': False, 'results': 'Unknown state passed. %s' % state, state: 'unknown'}
  1729. # -*- -*- -*- End included fragment: class/oc_adm_policy_group.py -*- -*- -*-
  1730. # -*- -*- -*- Begin included fragment: ansible/oc_adm_policy_group.py -*- -*- -*-
  1731. def main():
  1732. '''
  1733. ansible oc adm module for group policy
  1734. '''
  1735. module = AnsibleModule(
  1736. argument_spec=dict(
  1737. state=dict(default='present', type='str',
  1738. choices=['present', 'absent']),
  1739. debug=dict(default=False, type='bool'),
  1740. resource_name=dict(required=True, type='str'),
  1741. namespace=dict(default='default', type='str'),
  1742. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1743. group=dict(required=True, type='str'),
  1744. resource_kind=dict(required=True, choices=['role', 'cluster-role', 'scc'], type='str'),
  1745. ),
  1746. supports_check_mode=True,
  1747. )
  1748. results = PolicyGroup.run_ansible(module.params, module.check_mode)
  1749. if 'failed' in results:
  1750. module.fail_json(**results)
  1751. module.exit_json(**results)
  1752. if __name__ == "__main__":
  1753. main()
  1754. # -*- -*- -*- End included fragment: ansible/oc_adm_policy_group.py -*- -*- -*-