oc_adm_policy_group.py 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224
  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, edits=None, 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. updated = False
  737. if content is not None:
  738. changes = []
  739. for key, value in content.items():
  740. changes.append(yed.put(key, value))
  741. if any([change[0] for change in changes]):
  742. updated = True
  743. elif edits is not None:
  744. results = Yedit.process_edits(edits, yed)
  745. if results['changed']:
  746. updated = True
  747. if updated:
  748. yed.write()
  749. atexit.register(Utils.cleanup, [fname])
  750. return self._replace(fname, force)
  751. return {'returncode': 0, 'updated': False}
  752. def _replace(self, fname, force=False):
  753. '''replace the current object with oc replace'''
  754. # We are removing the 'resourceVersion' to handle
  755. # a race condition when modifying oc objects
  756. yed = Yedit(fname)
  757. results = yed.delete('metadata.resourceVersion')
  758. if results[0]:
  759. yed.write()
  760. cmd = ['replace', '-f', fname]
  761. if force:
  762. cmd.append('--force')
  763. return self.openshift_cmd(cmd)
  764. def _create_from_content(self, rname, content):
  765. '''create a temporary file and then call oc create on it'''
  766. fname = Utils.create_tmpfile(rname + '-')
  767. yed = Yedit(fname, content=content)
  768. yed.write()
  769. atexit.register(Utils.cleanup, [fname])
  770. return self._create(fname)
  771. def _create(self, fname):
  772. '''call oc create on a filename'''
  773. return self.openshift_cmd(['create', '-f', fname])
  774. def _delete(self, resource, name=None, selector=None):
  775. '''call oc delete on a resource'''
  776. cmd = ['delete', resource]
  777. if selector is not None:
  778. cmd.append('--selector={}'.format(selector))
  779. elif name is not None:
  780. cmd.append(name)
  781. else:
  782. raise OpenShiftCLIError('Either name or selector is required when calling delete.')
  783. return self.openshift_cmd(cmd)
  784. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  785. '''process a template
  786. template_name: the name of the template to process
  787. create: whether to send to oc create after processing
  788. params: the parameters for the template
  789. template_data: the incoming template's data; instead of a file
  790. '''
  791. cmd = ['process']
  792. if template_data:
  793. cmd.extend(['-f', '-'])
  794. else:
  795. cmd.append(template_name)
  796. if params:
  797. param_str = ["{}={}".format(key, str(value).replace("'", r'"')) for key, value in params.items()]
  798. cmd.append('-v')
  799. cmd.extend(param_str)
  800. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  801. if results['returncode'] != 0 or not create:
  802. return results
  803. fname = Utils.create_tmpfile(template_name + '-')
  804. yed = Yedit(fname, results['results'])
  805. yed.write()
  806. atexit.register(Utils.cleanup, [fname])
  807. return self.openshift_cmd(['create', '-f', fname])
  808. def _get(self, resource, name=None, selector=None):
  809. '''return a resource by name '''
  810. cmd = ['get', resource]
  811. if selector is not None:
  812. cmd.append('--selector={}'.format(selector))
  813. elif name is not None:
  814. cmd.append(name)
  815. cmd.extend(['-o', 'json'])
  816. rval = self.openshift_cmd(cmd, output=True)
  817. # Ensure results are retuned in an array
  818. if 'items' in rval:
  819. rval['results'] = rval['items']
  820. elif not isinstance(rval['results'], list):
  821. rval['results'] = [rval['results']]
  822. return rval
  823. def _schedulable(self, node=None, selector=None, schedulable=True):
  824. ''' perform oadm manage-node scheduable '''
  825. cmd = ['manage-node']
  826. if node:
  827. cmd.extend(node)
  828. else:
  829. cmd.append('--selector={}'.format(selector))
  830. cmd.append('--schedulable={}'.format(schedulable))
  831. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  832. def _list_pods(self, node=None, selector=None, pod_selector=None):
  833. ''' perform oadm list pods
  834. node: the node in which to list pods
  835. selector: the label selector filter if provided
  836. pod_selector: the pod selector filter if provided
  837. '''
  838. cmd = ['manage-node']
  839. if node:
  840. cmd.extend(node)
  841. else:
  842. cmd.append('--selector={}'.format(selector))
  843. if pod_selector:
  844. cmd.append('--pod-selector={}'.format(pod_selector))
  845. cmd.extend(['--list-pods', '-o', 'json'])
  846. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  847. # pylint: disable=too-many-arguments
  848. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  849. ''' perform oadm manage-node evacuate '''
  850. cmd = ['manage-node']
  851. if node:
  852. cmd.extend(node)
  853. else:
  854. cmd.append('--selector={}'.format(selector))
  855. if dry_run:
  856. cmd.append('--dry-run')
  857. if pod_selector:
  858. cmd.append('--pod-selector={}'.format(pod_selector))
  859. if grace_period:
  860. cmd.append('--grace-period={}'.format(int(grace_period)))
  861. if force:
  862. cmd.append('--force')
  863. cmd.append('--evacuate')
  864. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  865. def _version(self):
  866. ''' return the openshift version'''
  867. return self.openshift_cmd(['version'], output=True, output_type='raw')
  868. def _import_image(self, url=None, name=None, tag=None):
  869. ''' perform image import '''
  870. cmd = ['import-image']
  871. image = '{0}'.format(name)
  872. if tag:
  873. image += ':{0}'.format(tag)
  874. cmd.append(image)
  875. if url:
  876. cmd.append('--from={0}/{1}'.format(url, image))
  877. cmd.append('-n{0}'.format(self.namespace))
  878. cmd.append('--confirm')
  879. return self.openshift_cmd(cmd)
  880. def _run(self, cmds, input_data):
  881. ''' Actually executes the command. This makes mocking easier. '''
  882. curr_env = os.environ.copy()
  883. curr_env.update({'KUBECONFIG': self.kubeconfig})
  884. proc = subprocess.Popen(cmds,
  885. stdin=subprocess.PIPE,
  886. stdout=subprocess.PIPE,
  887. stderr=subprocess.PIPE,
  888. env=curr_env)
  889. stdout, stderr = proc.communicate(input_data)
  890. return proc.returncode, stdout.decode('utf-8'), stderr.decode('utf-8')
  891. # pylint: disable=too-many-arguments,too-many-branches
  892. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  893. '''Base command for oc '''
  894. cmds = [self.oc_binary]
  895. if oadm:
  896. cmds.append('adm')
  897. cmds.extend(cmd)
  898. if self.all_namespaces:
  899. cmds.extend(['--all-namespaces'])
  900. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  901. cmds.extend(['-n', self.namespace])
  902. if self.verbose:
  903. print(' '.join(cmds))
  904. try:
  905. returncode, stdout, stderr = self._run(cmds, input_data)
  906. except OSError as ex:
  907. returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
  908. rval = {"returncode": returncode,
  909. "cmd": ' '.join(cmds)}
  910. if output_type == 'json':
  911. rval['results'] = {}
  912. if output and stdout:
  913. try:
  914. rval['results'] = json.loads(stdout)
  915. except ValueError as verr:
  916. if "No JSON object could be decoded" in verr.args:
  917. rval['err'] = verr.args
  918. elif output_type == 'raw':
  919. rval['results'] = stdout if output else ''
  920. if self.verbose:
  921. print("STDOUT: {0}".format(stdout))
  922. print("STDERR: {0}".format(stderr))
  923. if 'err' in rval or returncode != 0:
  924. rval.update({"stderr": stderr,
  925. "stdout": stdout})
  926. return rval
  927. class Utils(object): # pragma: no cover
  928. ''' utilities for openshiftcli modules '''
  929. @staticmethod
  930. def _write(filename, contents):
  931. ''' Actually write the file contents to disk. This helps with mocking. '''
  932. with open(filename, 'w') as sfd:
  933. sfd.write(str(contents))
  934. @staticmethod
  935. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  936. ''' create a file in tmp with name and contents'''
  937. tmp = Utils.create_tmpfile(prefix=rname)
  938. if ftype == 'yaml':
  939. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  940. # pylint: disable=no-member
  941. if hasattr(yaml, 'RoundTripDumper'):
  942. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  943. else:
  944. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  945. elif ftype == 'json':
  946. Utils._write(tmp, json.dumps(data))
  947. else:
  948. Utils._write(tmp, data)
  949. # Register cleanup when module is done
  950. atexit.register(Utils.cleanup, [tmp])
  951. return tmp
  952. @staticmethod
  953. def create_tmpfile_copy(inc_file):
  954. '''create a temporary copy of a file'''
  955. tmpfile = Utils.create_tmpfile('lib_openshift-')
  956. Utils._write(tmpfile, open(inc_file).read())
  957. # Cleanup the tmpfile
  958. atexit.register(Utils.cleanup, [tmpfile])
  959. return tmpfile
  960. @staticmethod
  961. def create_tmpfile(prefix='tmp'):
  962. ''' Generates and returns a temporary file name '''
  963. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  964. return tmp.name
  965. @staticmethod
  966. def create_tmp_files_from_contents(content, content_type=None):
  967. '''Turn an array of dict: filename, content into a files array'''
  968. if not isinstance(content, list):
  969. content = [content]
  970. files = []
  971. for item in content:
  972. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  973. item['data'],
  974. ftype=content_type)
  975. files.append({'name': os.path.basename(item['path']),
  976. 'path': path})
  977. return files
  978. @staticmethod
  979. def cleanup(files):
  980. '''Clean up on exit '''
  981. for sfile in files:
  982. if os.path.exists(sfile):
  983. if os.path.isdir(sfile):
  984. shutil.rmtree(sfile)
  985. elif os.path.isfile(sfile):
  986. os.remove(sfile)
  987. @staticmethod
  988. def exists(results, _name):
  989. ''' Check to see if the results include the name '''
  990. if not results:
  991. return False
  992. if Utils.find_result(results, _name):
  993. return True
  994. return False
  995. @staticmethod
  996. def find_result(results, _name):
  997. ''' Find the specified result by name'''
  998. rval = None
  999. for result in results:
  1000. if 'metadata' in result and result['metadata']['name'] == _name:
  1001. rval = result
  1002. break
  1003. return rval
  1004. @staticmethod
  1005. def get_resource_file(sfile, sfile_type='yaml'):
  1006. ''' return the service file '''
  1007. contents = None
  1008. with open(sfile) as sfd:
  1009. contents = sfd.read()
  1010. if sfile_type == 'yaml':
  1011. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  1012. # pylint: disable=no-member
  1013. if hasattr(yaml, 'RoundTripLoader'):
  1014. contents = yaml.load(contents, yaml.RoundTripLoader)
  1015. else:
  1016. contents = yaml.safe_load(contents)
  1017. elif sfile_type == 'json':
  1018. contents = json.loads(contents)
  1019. return contents
  1020. @staticmethod
  1021. def filter_versions(stdout):
  1022. ''' filter the oc version output '''
  1023. version_dict = {}
  1024. version_search = ['oc', 'openshift', 'kubernetes']
  1025. for line in stdout.strip().split('\n'):
  1026. for term in version_search:
  1027. if not line:
  1028. continue
  1029. if line.startswith(term):
  1030. version_dict[term] = line.split()[-1]
  1031. # horrible hack to get openshift version in Openshift 3.2
  1032. # By default "oc version in 3.2 does not return an "openshift" version
  1033. if "openshift" not in version_dict:
  1034. version_dict["openshift"] = version_dict["oc"]
  1035. return version_dict
  1036. @staticmethod
  1037. def add_custom_versions(versions):
  1038. ''' create custom versions strings '''
  1039. versions_dict = {}
  1040. for tech, version in versions.items():
  1041. # clean up "-" from version
  1042. if "-" in version:
  1043. version = version.split("-")[0]
  1044. if version.startswith('v'):
  1045. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  1046. # "v3.3.0.33" is what we have, we want "3.3"
  1047. versions_dict[tech + '_short'] = version[1:4]
  1048. return versions_dict
  1049. @staticmethod
  1050. def openshift_installed():
  1051. ''' check if openshift is installed '''
  1052. import rpm
  1053. transaction_set = rpm.TransactionSet()
  1054. rpmquery = transaction_set.dbMatch("name", "atomic-openshift")
  1055. return rpmquery.count() > 0
  1056. # Disabling too-many-branches. This is a yaml dictionary comparison function
  1057. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  1058. @staticmethod
  1059. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  1060. ''' Given a user defined definition, compare it with the results given back by our query. '''
  1061. # Currently these values are autogenerated and we do not need to check them
  1062. skip = ['metadata', 'status']
  1063. if skip_keys:
  1064. skip.extend(skip_keys)
  1065. for key, value in result_def.items():
  1066. if key in skip:
  1067. continue
  1068. # Both are lists
  1069. if isinstance(value, list):
  1070. if key not in user_def:
  1071. if debug:
  1072. print('User data does not have key [%s]' % key)
  1073. print('User data: %s' % user_def)
  1074. return False
  1075. if not isinstance(user_def[key], list):
  1076. if debug:
  1077. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  1078. return False
  1079. if len(user_def[key]) != len(value):
  1080. if debug:
  1081. print("List lengths are not equal.")
  1082. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  1083. print("user_def: %s" % user_def[key])
  1084. print("value: %s" % value)
  1085. return False
  1086. for values in zip(user_def[key], value):
  1087. if isinstance(values[0], dict) and isinstance(values[1], dict):
  1088. if debug:
  1089. print('sending list - list')
  1090. print(type(values[0]))
  1091. print(type(values[1]))
  1092. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  1093. if not result:
  1094. print('list compare returned false')
  1095. return False
  1096. elif value != user_def[key]:
  1097. if debug:
  1098. print('value should be identical')
  1099. print(user_def[key])
  1100. print(value)
  1101. return False
  1102. # recurse on a dictionary
  1103. elif isinstance(value, dict):
  1104. if key not in user_def:
  1105. if debug:
  1106. print("user_def does not have key [%s]" % key)
  1107. return False
  1108. if not isinstance(user_def[key], dict):
  1109. if debug:
  1110. print("dict returned false: not instance of dict")
  1111. return False
  1112. # before passing ensure keys match
  1113. api_values = set(value.keys()) - set(skip)
  1114. user_values = set(user_def[key].keys()) - set(skip)
  1115. if api_values != user_values:
  1116. if debug:
  1117. print("keys are not equal in dict")
  1118. print(user_values)
  1119. print(api_values)
  1120. return False
  1121. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1122. if not result:
  1123. if debug:
  1124. print("dict returned false")
  1125. print(result)
  1126. return False
  1127. # Verify each key, value pair is the same
  1128. else:
  1129. if key not in user_def or value != user_def[key]:
  1130. if debug:
  1131. print("value not equal; user_def does not have key")
  1132. print(key)
  1133. print(value)
  1134. if key in user_def:
  1135. print(user_def[key])
  1136. return False
  1137. if debug:
  1138. print('returning true')
  1139. return True
  1140. class OpenShiftCLIConfig(object):
  1141. '''Generic Config'''
  1142. def __init__(self, rname, namespace, kubeconfig, options):
  1143. self.kubeconfig = kubeconfig
  1144. self.name = rname
  1145. self.namespace = namespace
  1146. self._options = options
  1147. @property
  1148. def config_options(self):
  1149. ''' return config options '''
  1150. return self._options
  1151. def to_option_list(self, ascommalist=''):
  1152. '''return all options as a string
  1153. if ascommalist is set to the name of a key, and
  1154. the value of that key is a dict, format the dict
  1155. as a list of comma delimited key=value pairs'''
  1156. return self.stringify(ascommalist)
  1157. def stringify(self, ascommalist=''):
  1158. ''' return the options hash as cli params in a string
  1159. if ascommalist is set to the name of a key, and
  1160. the value of that key is a dict, format the dict
  1161. as a list of comma delimited key=value pairs '''
  1162. rval = []
  1163. for key in sorted(self.config_options.keys()):
  1164. data = self.config_options[key]
  1165. if data['include'] \
  1166. and (data['value'] is not None or isinstance(data['value'], int)):
  1167. if key == ascommalist:
  1168. val = ','.join(['{}={}'.format(kk, vv) for kk, vv in sorted(data['value'].items())])
  1169. else:
  1170. val = data['value']
  1171. rval.append('--{}={}'.format(key.replace('_', '-'), val))
  1172. return rval
  1173. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1174. # -*- -*- -*- Begin included fragment: lib/rolebinding.py -*- -*- -*-
  1175. # pylint: disable=too-many-instance-attributes
  1176. class RoleBindingConfig(object):
  1177. ''' Handle rolebinding config '''
  1178. # pylint: disable=too-many-arguments
  1179. def __init__(self,
  1180. name,
  1181. namespace,
  1182. kubeconfig,
  1183. group_names=None,
  1184. role_ref=None,
  1185. subjects=None,
  1186. usernames=None):
  1187. ''' constructor for handling rolebinding options '''
  1188. self.kubeconfig = kubeconfig
  1189. self.name = name
  1190. self.namespace = namespace
  1191. self.group_names = group_names
  1192. self.role_ref = role_ref
  1193. self.subjects = subjects
  1194. self.usernames = usernames
  1195. self.data = {}
  1196. self.create_dict()
  1197. def create_dict(self):
  1198. ''' create a default rolebinding as a dict '''
  1199. self.data['apiVersion'] = 'v1'
  1200. self.data['kind'] = 'RoleBinding'
  1201. self.data['groupNames'] = self.group_names
  1202. self.data['metadata']['name'] = self.name
  1203. self.data['metadata']['namespace'] = self.namespace
  1204. self.data['roleRef'] = self.role_ref
  1205. self.data['subjects'] = self.subjects
  1206. self.data['userNames'] = self.usernames
  1207. # pylint: disable=too-many-instance-attributes,too-many-public-methods
  1208. class RoleBinding(Yedit):
  1209. ''' Class to model a rolebinding openshift object'''
  1210. group_names_path = "groupNames"
  1211. role_ref_path = "roleRef"
  1212. subjects_path = "subjects"
  1213. user_names_path = "userNames"
  1214. kind = 'RoleBinding'
  1215. def __init__(self, content):
  1216. '''RoleBinding constructor'''
  1217. super(RoleBinding, self).__init__(content=content)
  1218. self._subjects = None
  1219. self._role_ref = None
  1220. self._group_names = None
  1221. self._user_names = None
  1222. @property
  1223. def subjects(self):
  1224. ''' subjects property '''
  1225. if self._subjects is None:
  1226. self._subjects = self.get_subjects()
  1227. return self._subjects
  1228. @subjects.setter
  1229. def subjects(self, data):
  1230. ''' subjects property setter'''
  1231. self._subjects = data
  1232. @property
  1233. def role_ref(self):
  1234. ''' role_ref property '''
  1235. if self._role_ref is None:
  1236. self._role_ref = self.get_role_ref()
  1237. return self._role_ref
  1238. @role_ref.setter
  1239. def role_ref(self, data):
  1240. ''' role_ref property setter'''
  1241. self._role_ref = data
  1242. @property
  1243. def group_names(self):
  1244. ''' group_names property '''
  1245. if self._group_names is None:
  1246. self._group_names = self.get_group_names()
  1247. return self._group_names
  1248. @group_names.setter
  1249. def group_names(self, data):
  1250. ''' group_names property setter'''
  1251. self._group_names = data
  1252. @property
  1253. def user_names(self):
  1254. ''' user_names property '''
  1255. if self._user_names is None:
  1256. self._user_names = self.get_user_names()
  1257. return self._user_names
  1258. @user_names.setter
  1259. def user_names(self, data):
  1260. ''' user_names property setter'''
  1261. self._user_names = data
  1262. def get_group_names(self):
  1263. ''' return groupNames '''
  1264. return self.get(RoleBinding.group_names_path) or []
  1265. def get_user_names(self):
  1266. ''' return usernames '''
  1267. return self.get(RoleBinding.user_names_path) or []
  1268. def get_role_ref(self):
  1269. ''' return role_ref '''
  1270. return self.get(RoleBinding.role_ref_path) or {}
  1271. def get_subjects(self):
  1272. ''' return subjects '''
  1273. return self.get(RoleBinding.subjects_path) or []
  1274. #### ADD #####
  1275. def add_subject(self, inc_subject):
  1276. ''' add a subject '''
  1277. if self.subjects:
  1278. # pylint: disable=no-member
  1279. self.subjects.append(inc_subject)
  1280. else:
  1281. self.put(RoleBinding.subjects_path, [inc_subject])
  1282. return True
  1283. def add_role_ref(self, inc_role_ref):
  1284. ''' add a role_ref '''
  1285. if not self.role_ref:
  1286. self.put(RoleBinding.role_ref_path, {"name": inc_role_ref})
  1287. return True
  1288. return False
  1289. def add_group_names(self, inc_group_names):
  1290. ''' add a group_names '''
  1291. if self.group_names:
  1292. # pylint: disable=no-member
  1293. self.group_names.append(inc_group_names)
  1294. else:
  1295. self.put(RoleBinding.group_names_path, [inc_group_names])
  1296. return True
  1297. def add_user_name(self, inc_user_name):
  1298. ''' add a username '''
  1299. if self.user_names:
  1300. # pylint: disable=no-member
  1301. self.user_names.append(inc_user_name)
  1302. else:
  1303. self.put(RoleBinding.user_names_path, [inc_user_name])
  1304. return True
  1305. #### /ADD #####
  1306. #### Remove #####
  1307. def remove_subject(self, inc_subject):
  1308. ''' remove a subject '''
  1309. try:
  1310. # pylint: disable=no-member
  1311. self.subjects.remove(inc_subject)
  1312. except ValueError as _:
  1313. return False
  1314. return True
  1315. def remove_role_ref(self, inc_role_ref):
  1316. ''' remove a role_ref '''
  1317. if self.role_ref and self.role_ref['name'] == inc_role_ref:
  1318. del self.role_ref['name']
  1319. return True
  1320. return False
  1321. def remove_group_name(self, inc_group_name):
  1322. ''' remove a groupname '''
  1323. try:
  1324. # pylint: disable=no-member
  1325. self.group_names.remove(inc_group_name)
  1326. except ValueError as _:
  1327. return False
  1328. return True
  1329. def remove_user_name(self, inc_user_name):
  1330. ''' remove a username '''
  1331. try:
  1332. # pylint: disable=no-member
  1333. self.user_names.remove(inc_user_name)
  1334. except ValueError as _:
  1335. return False
  1336. return True
  1337. #### /REMOVE #####
  1338. #### UPDATE #####
  1339. def update_subject(self, inc_subject):
  1340. ''' update a subject '''
  1341. try:
  1342. # pylint: disable=no-member
  1343. index = self.subjects.index(inc_subject)
  1344. except ValueError as _:
  1345. return self.add_subject(inc_subject)
  1346. self.subjects[index] = inc_subject
  1347. return True
  1348. def update_group_name(self, inc_group_name):
  1349. ''' update a groupname '''
  1350. try:
  1351. # pylint: disable=no-member
  1352. index = self.group_names.index(inc_group_name)
  1353. except ValueError as _:
  1354. return self.add_group_names(inc_group_name)
  1355. self.group_names[index] = inc_group_name
  1356. return True
  1357. def update_user_name(self, inc_user_name):
  1358. ''' update a username '''
  1359. try:
  1360. # pylint: disable=no-member
  1361. index = self.user_names.index(inc_user_name)
  1362. except ValueError as _:
  1363. return self.add_user_name(inc_user_name)
  1364. self.user_names[index] = inc_user_name
  1365. return True
  1366. def update_role_ref(self, inc_role_ref):
  1367. ''' update a role_ref '''
  1368. self.role_ref['name'] = inc_role_ref
  1369. return True
  1370. #### /UPDATE #####
  1371. #### FIND ####
  1372. def find_subject(self, inc_subject):
  1373. ''' find a subject '''
  1374. index = None
  1375. try:
  1376. # pylint: disable=no-member
  1377. index = self.subjects.index(inc_subject)
  1378. except ValueError as _:
  1379. return index
  1380. return index
  1381. def find_group_name(self, inc_group_name):
  1382. ''' find a group_name '''
  1383. index = None
  1384. try:
  1385. # pylint: disable=no-member
  1386. index = self.group_names.index(inc_group_name)
  1387. except ValueError as _:
  1388. return index
  1389. return index
  1390. def find_user_name(self, inc_user_name):
  1391. ''' find a user_name '''
  1392. index = None
  1393. try:
  1394. # pylint: disable=no-member
  1395. index = self.user_names.index(inc_user_name)
  1396. except ValueError as _:
  1397. return index
  1398. return index
  1399. def find_role_ref(self, inc_role_ref):
  1400. ''' find a user_name '''
  1401. if self.role_ref and self.role_ref['name'] == inc_role_ref['name']:
  1402. return self.role_ref
  1403. return None
  1404. # -*- -*- -*- End included fragment: lib/rolebinding.py -*- -*- -*-
  1405. # -*- -*- -*- Begin included fragment: lib/scc.py -*- -*- -*-
  1406. # pylint: disable=too-many-instance-attributes
  1407. class SecurityContextConstraintsConfig(object):
  1408. ''' Handle scc options '''
  1409. # pylint: disable=too-many-arguments
  1410. def __init__(self,
  1411. sname,
  1412. kubeconfig,
  1413. options=None,
  1414. fs_group='MustRunAs',
  1415. default_add_capabilities=None,
  1416. groups=None,
  1417. priority=None,
  1418. required_drop_capabilities=None,
  1419. run_as_user='MustRunAsRange',
  1420. se_linux_context='MustRunAs',
  1421. supplemental_groups='RunAsAny',
  1422. users=None,
  1423. annotations=None):
  1424. ''' constructor for handling scc options '''
  1425. self.kubeconfig = kubeconfig
  1426. self.name = sname
  1427. self.options = options
  1428. self.fs_group = fs_group
  1429. self.default_add_capabilities = default_add_capabilities
  1430. self.groups = groups
  1431. self.priority = priority
  1432. self.required_drop_capabilities = required_drop_capabilities
  1433. self.run_as_user = run_as_user
  1434. self.se_linux_context = se_linux_context
  1435. self.supplemental_groups = supplemental_groups
  1436. self.users = users
  1437. self.annotations = annotations
  1438. self.data = {}
  1439. self.create_dict()
  1440. def create_dict(self):
  1441. ''' assign the correct properties for a scc dict '''
  1442. # allow options
  1443. if self.options:
  1444. for key, value in self.options.items():
  1445. self.data[key] = value
  1446. else:
  1447. self.data['allowHostDirVolumePlugin'] = False
  1448. self.data['allowHostIPC'] = False
  1449. self.data['allowHostNetwork'] = False
  1450. self.data['allowHostPID'] = False
  1451. self.data['allowHostPorts'] = False
  1452. self.data['allowPrivilegedContainer'] = False
  1453. self.data['allowedCapabilities'] = None
  1454. # version
  1455. self.data['apiVersion'] = 'v1'
  1456. # kind
  1457. self.data['kind'] = 'SecurityContextConstraints'
  1458. # defaultAddCapabilities
  1459. self.data['defaultAddCapabilities'] = self.default_add_capabilities
  1460. # fsGroup
  1461. self.data['fsGroup']['type'] = self.fs_group
  1462. # groups
  1463. self.data['groups'] = []
  1464. if self.groups:
  1465. self.data['groups'] = self.groups
  1466. # metadata
  1467. self.data['metadata'] = {}
  1468. self.data['metadata']['name'] = self.name
  1469. if self.annotations:
  1470. for key, value in self.annotations.items():
  1471. self.data['metadata'][key] = value
  1472. # priority
  1473. self.data['priority'] = self.priority
  1474. # requiredDropCapabilities
  1475. self.data['requiredDropCapabilities'] = self.required_drop_capabilities
  1476. # runAsUser
  1477. self.data['runAsUser'] = {'type': self.run_as_user}
  1478. # seLinuxContext
  1479. self.data['seLinuxContext'] = {'type': self.se_linux_context}
  1480. # supplementalGroups
  1481. self.data['supplementalGroups'] = {'type': self.supplemental_groups}
  1482. # users
  1483. self.data['users'] = []
  1484. if self.users:
  1485. self.data['users'] = self.users
  1486. # pylint: disable=too-many-instance-attributes,too-many-public-methods,no-member
  1487. class SecurityContextConstraints(Yedit):
  1488. ''' Class to wrap the oc command line tools '''
  1489. default_add_capabilities_path = "defaultAddCapabilities"
  1490. fs_group_path = "fsGroup"
  1491. groups_path = "groups"
  1492. priority_path = "priority"
  1493. required_drop_capabilities_path = "requiredDropCapabilities"
  1494. run_as_user_path = "runAsUser"
  1495. se_linux_context_path = "seLinuxContext"
  1496. supplemental_groups_path = "supplementalGroups"
  1497. users_path = "users"
  1498. kind = 'SecurityContextConstraints'
  1499. def __init__(self, content):
  1500. '''SecurityContextConstraints constructor'''
  1501. super(SecurityContextConstraints, self).__init__(content=content)
  1502. self._users = None
  1503. self._groups = None
  1504. @property
  1505. def users(self):
  1506. ''' users property getter '''
  1507. if self._users is None:
  1508. self._users = self.get_users()
  1509. return self._users
  1510. @property
  1511. def groups(self):
  1512. ''' groups property getter '''
  1513. if self._groups is None:
  1514. self._groups = self.get_groups()
  1515. return self._groups
  1516. @users.setter
  1517. def users(self, data):
  1518. ''' users property setter'''
  1519. self._users = data
  1520. @groups.setter
  1521. def groups(self, data):
  1522. ''' groups property setter'''
  1523. self._groups = data
  1524. def get_users(self):
  1525. '''get scc users'''
  1526. return self.get(SecurityContextConstraints.users_path) or []
  1527. def get_groups(self):
  1528. '''get scc groups'''
  1529. return self.get(SecurityContextConstraints.groups_path) or []
  1530. def add_user(self, inc_user):
  1531. ''' add a user '''
  1532. if self.users:
  1533. self.users.append(inc_user)
  1534. else:
  1535. self.put(SecurityContextConstraints.users_path, [inc_user])
  1536. return True
  1537. def add_group(self, inc_group):
  1538. ''' add a group '''
  1539. if self.groups:
  1540. self.groups.append(inc_group)
  1541. else:
  1542. self.put(SecurityContextConstraints.groups_path, [inc_group])
  1543. return True
  1544. def remove_user(self, inc_user):
  1545. ''' remove a user '''
  1546. try:
  1547. self.users.remove(inc_user)
  1548. except ValueError as _:
  1549. return False
  1550. return True
  1551. def remove_group(self, inc_group):
  1552. ''' remove a group '''
  1553. try:
  1554. self.groups.remove(inc_group)
  1555. except ValueError as _:
  1556. return False
  1557. return True
  1558. def update_user(self, inc_user):
  1559. ''' update a user '''
  1560. try:
  1561. index = self.users.index(inc_user)
  1562. except ValueError as _:
  1563. return self.add_user(inc_user)
  1564. self.users[index] = inc_user
  1565. return True
  1566. def update_group(self, inc_group):
  1567. ''' update a group '''
  1568. try:
  1569. index = self.groups.index(inc_group)
  1570. except ValueError as _:
  1571. return self.add_group(inc_group)
  1572. self.groups[index] = inc_group
  1573. return True
  1574. def find_user(self, inc_user):
  1575. ''' find a user '''
  1576. index = None
  1577. try:
  1578. index = self.users.index(inc_user)
  1579. except ValueError as _:
  1580. return index
  1581. return index
  1582. def find_group(self, inc_group):
  1583. ''' find a group '''
  1584. index = None
  1585. try:
  1586. index = self.groups.index(inc_group)
  1587. except ValueError as _:
  1588. return index
  1589. return index
  1590. # -*- -*- -*- End included fragment: lib/scc.py -*- -*- -*-
  1591. # -*- -*- -*- Begin included fragment: class/oc_adm_policy_group.py -*- -*- -*-
  1592. class PolicyGroupException(Exception):
  1593. ''' PolicyGroup exception'''
  1594. pass
  1595. class PolicyGroupConfig(OpenShiftCLIConfig):
  1596. ''' PolicyGroupConfig is a DTO for group related policy. '''
  1597. def __init__(self, namespace, kubeconfig, policy_options):
  1598. super(PolicyGroupConfig, self).__init__(policy_options['name']['value'],
  1599. namespace, kubeconfig, policy_options)
  1600. self.kind = self.get_kind()
  1601. self.namespace = namespace
  1602. def get_kind(self):
  1603. ''' return the kind we are working with '''
  1604. if self.config_options['resource_kind']['value'] == 'role':
  1605. return 'rolebinding'
  1606. elif self.config_options['resource_kind']['value'] == 'cluster-role':
  1607. return 'clusterrolebinding'
  1608. elif self.config_options['resource_kind']['value'] == 'scc':
  1609. return 'scc'
  1610. return None
  1611. # pylint: disable=too-many-return-statements
  1612. class PolicyGroup(OpenShiftCLI):
  1613. ''' Class to handle attaching policies to users '''
  1614. def __init__(self,
  1615. config,
  1616. verbose=False):
  1617. ''' Constructor for PolicyGroup '''
  1618. super(PolicyGroup, self).__init__(config.namespace, config.kubeconfig, verbose)
  1619. self.config = config
  1620. self.verbose = verbose
  1621. self._rolebinding = None
  1622. self._scc = None
  1623. self._cluster_role_bindings = None
  1624. self._role_bindings = None
  1625. @property
  1626. def rolebindings(self):
  1627. if self._role_bindings is None:
  1628. results = self._get('rolebindings', None)
  1629. if results['returncode'] != 0:
  1630. raise OpenShiftCLIError('Could not retrieve rolebindings')
  1631. self._role_bindings = results['results'][0]['items']
  1632. return self._role_bindings
  1633. @property
  1634. def clusterrolebindings(self):
  1635. if self._cluster_role_bindings is None:
  1636. results = self._get('clusterrolebindings', None)
  1637. if results['returncode'] != 0:
  1638. raise OpenShiftCLIError('Could not retrieve clusterrolebindings')
  1639. self._cluster_role_bindings = results['results'][0]['items']
  1640. return self._cluster_role_bindings
  1641. @property
  1642. def role_binding(self):
  1643. ''' role_binding getter '''
  1644. return self._rolebinding
  1645. @role_binding.setter
  1646. def role_binding(self, binding):
  1647. ''' role_binding setter '''
  1648. self._rolebinding = binding
  1649. @property
  1650. def security_context_constraint(self):
  1651. ''' security_context_constraint getter '''
  1652. return self._scc
  1653. @security_context_constraint.setter
  1654. def security_context_constraint(self, scc):
  1655. ''' security_context_constraint setter '''
  1656. self._scc = scc
  1657. def get(self):
  1658. '''fetch the desired kind'''
  1659. resource_name = self.config.config_options['name']['value']
  1660. if resource_name == 'cluster-reader':
  1661. resource_name += 's'
  1662. # oc adm policy add-... creates policy bindings with the name
  1663. # "[resource_name]-binding", however some bindings in the system
  1664. # simply use "[resource_name]". So try both.
  1665. results = self._get(self.config.kind, resource_name)
  1666. if results['returncode'] == 0:
  1667. return results
  1668. # Now try -binding naming convention
  1669. return self._get(self.config.kind, resource_name + "-binding")
  1670. def exists_role_binding(self):
  1671. ''' return whether role_binding exists '''
  1672. bindings = None
  1673. if self.config.config_options['resource_kind']['value'] == 'cluster-role':
  1674. bindings = self.clusterrolebindings
  1675. else:
  1676. bindings = self.rolebindings
  1677. if bindings is None:
  1678. return False
  1679. for binding in bindings:
  1680. if binding['roleRef']['name'] == self.config.config_options['name']['value'] and \
  1681. binding['groupNames'] is not None and \
  1682. self.config.config_options['group']['value'] in binding['groupNames']:
  1683. self.role_binding = binding
  1684. return True
  1685. return False
  1686. def exists_scc(self):
  1687. ''' return whether scc exists '''
  1688. results = self.get()
  1689. if results['returncode'] == 0:
  1690. self.security_context_constraint = SecurityContextConstraints(results['results'][0])
  1691. if self.security_context_constraint.find_group(self.config.config_options['group']['value']) != None:
  1692. return True
  1693. return False
  1694. return results
  1695. def exists(self):
  1696. '''does the object exist?'''
  1697. if self.config.config_options['resource_kind']['value'] == 'cluster-role':
  1698. return self.exists_role_binding()
  1699. elif self.config.config_options['resource_kind']['value'] == 'role':
  1700. return self.exists_role_binding()
  1701. elif self.config.config_options['resource_kind']['value'] == 'scc':
  1702. return self.exists_scc()
  1703. return False
  1704. def perform(self):
  1705. '''perform action on resource'''
  1706. cmd = ['policy',
  1707. self.config.config_options['action']['value'],
  1708. self.config.config_options['name']['value'],
  1709. self.config.config_options['group']['value']]
  1710. return self.openshift_cmd(cmd, oadm=True)
  1711. @staticmethod
  1712. def run_ansible(params, check_mode):
  1713. '''run the idempotent ansible code'''
  1714. state = params['state']
  1715. action = None
  1716. if state == 'present':
  1717. action = 'add-' + params['resource_kind'] + '-to-group'
  1718. else:
  1719. action = 'remove-' + params['resource_kind'] + '-from-group'
  1720. nconfig = PolicyGroupConfig(params['namespace'],
  1721. params['kubeconfig'],
  1722. {'action': {'value': action, 'include': False},
  1723. 'group': {'value': params['group'], 'include': False},
  1724. 'resource_kind': {'value': params['resource_kind'], 'include': False},
  1725. 'name': {'value': params['resource_name'], 'include': False},
  1726. })
  1727. policygroup = PolicyGroup(nconfig, params['debug'])
  1728. # Run the oc adm policy group related command
  1729. ########
  1730. # Delete
  1731. ########
  1732. if state == 'absent':
  1733. if not policygroup.exists():
  1734. return {'changed': False, 'state': 'absent'}
  1735. if check_mode:
  1736. return {'changed': False, 'msg': 'CHECK_MODE: would have performed a delete.'}
  1737. api_rval = policygroup.perform()
  1738. if api_rval['returncode'] != 0:
  1739. return {'msg': api_rval}
  1740. return {'changed': True, 'results' : api_rval, state:'absent'}
  1741. if state == 'present':
  1742. ########
  1743. # Create
  1744. ########
  1745. results = policygroup.exists()
  1746. if isinstance(results, dict) and 'returncode' in results and results['returncode'] != 0:
  1747. return {'msg': results}
  1748. if not results:
  1749. if check_mode:
  1750. return {'changed': False, 'msg': 'CHECK_MODE: would have performed a create.'}
  1751. api_rval = policygroup.perform()
  1752. if api_rval['returncode'] != 0:
  1753. return {'msg': api_rval}
  1754. return {'changed': True, 'results': api_rval, state: 'present'}
  1755. return {'changed': False, state: 'present'}
  1756. return {'failed': True, 'changed': False, 'results': 'Unknown state passed. %s' % state, state: 'unknown'}
  1757. # -*- -*- -*- End included fragment: class/oc_adm_policy_group.py -*- -*- -*-
  1758. # -*- -*- -*- Begin included fragment: ansible/oc_adm_policy_group.py -*- -*- -*-
  1759. def main():
  1760. '''
  1761. ansible oc adm module for group policy
  1762. '''
  1763. module = AnsibleModule(
  1764. argument_spec=dict(
  1765. state=dict(default='present', type='str',
  1766. choices=['present', 'absent']),
  1767. debug=dict(default=False, type='bool'),
  1768. resource_name=dict(required=True, type='str'),
  1769. namespace=dict(default='default', type='str'),
  1770. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1771. group=dict(required=True, type='str'),
  1772. resource_kind=dict(required=True, choices=['role', 'cluster-role', 'scc'], type='str'),
  1773. ),
  1774. supports_check_mode=True,
  1775. )
  1776. results = PolicyGroup.run_ansible(module.params, module.check_mode)
  1777. if 'failed' in results:
  1778. module.fail_json(**results)
  1779. module.exit_json(**results)
  1780. if __name__ == "__main__":
  1781. main()
  1782. # -*- -*- -*- End included fragment: ansible/oc_adm_policy_group.py -*- -*- -*-