oc_adm_policy_user.py 67 KB

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