oc_adm_policy_user.py 66 KB

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