oc_adm_policy_user.py 70 KB

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