oc_adm_policy_user.py 73 KB

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