oc_adm_policy_group.py 72 KB

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