oc_adm_policy_group.py 72 KB

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