oc_adm_policy_user.py 72 KB

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