oc_adm_policy_group.py 70 KB

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