oc_user.py 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706
  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/user -*- -*- -*-
  49. DOCUMENTATION = '''
  50. ---
  51. module: oc_user
  52. short_description: Create, modify, and idempotently manage openshift users.
  53. description:
  54. - Modify openshift users programmatically.
  55. options:
  56. state:
  57. description:
  58. - State controls the action that will be taken with resource
  59. - 'present' will create or update a user to the desired state
  60. - 'absent' will ensure user is removed
  61. - 'list' will read and return a list of users
  62. default: present
  63. choices: ["present", "absent", "list"]
  64. aliases: []
  65. kubeconfig:
  66. description:
  67. - The path for the kubeconfig file to use for authentication
  68. required: false
  69. default: /etc/origin/master/admin.kubeconfig
  70. aliases: []
  71. debug:
  72. description:
  73. - Turn on debug output.
  74. required: false
  75. default: False
  76. aliases: []
  77. username:
  78. description:
  79. - Short username to query/modify.
  80. required: false
  81. default: None
  82. aliases: []
  83. full_name:
  84. description:
  85. - String with the full name/description of the user.
  86. required: false
  87. default: None
  88. aliases: []
  89. groups:
  90. description:
  91. - List of groups the user should be a member of. This does not add/update the legacy 'groups' field in the OpenShift user object, but makes user entries into the appropriate OpenShift group object for the given user.
  92. required: false
  93. default: []
  94. aliases: []
  95. author:
  96. - "Joel Diaz <jdiaz@redhat.com>"
  97. extends_documentation_fragment: []
  98. '''
  99. EXAMPLES = '''
  100. - name: Ensure user exists
  101. oc_user:
  102. state: present
  103. username: johndoe
  104. full_name "John Doe"
  105. groups:
  106. - dedicated-admins
  107. register: user_johndoe
  108. user_johndoe variable will have contents like:
  109. ok: [ded-int-aws-master-61034] => {
  110. "user_johndoe": {
  111. "changed": true,
  112. "results": {
  113. "cmd": "oc -n default get users johndoe -o json",
  114. "results": [
  115. {
  116. "apiVersion": "v1",
  117. "fullName": "John DOe",
  118. "groups": null,
  119. "identities": null,
  120. "kind": "User",
  121. "metadata": {
  122. "creationTimestamp": "2017-02-28T15:09:21Z",
  123. "name": "johndoe",
  124. "resourceVersion": "848781",
  125. "selfLink": "/oapi/v1/users/johndoe",
  126. "uid": "e23d3300-fdc7-11e6-9e3e-12822d6b7656"
  127. }
  128. }
  129. ],
  130. "returncode": 0
  131. },
  132. "state": "present"
  133. }
  134. }
  135. 'groups' is empty because this field is the OpenShift user object's 'group' field.
  136. - name: Ensure user does not exist
  137. oc_user:
  138. state: absent
  139. username: johndoe
  140. - name: List user's info
  141. oc_user:
  142. state: list
  143. username: johndoe
  144. register: user_johndoe
  145. user_johndoe will have contents similar to:
  146. ok: [ded-int-aws-master-61034] => {
  147. "user_johndoe": {
  148. "changed": false,
  149. "results": [
  150. {
  151. "apiVersion": "v1",
  152. "fullName": "John Doe",
  153. "groups": null,
  154. "identities": null,
  155. "kind": "User",
  156. "metadata": {
  157. "creationTimestamp": "2017-02-28T15:04:44Z",
  158. "name": "johndoe",
  159. "resourceVersion": "848280",
  160. "selfLink": "/oapi/v1/users/johndoe",
  161. "uid": "3d479ad2-fdc7-11e6-9e3e-12822d6b7656"
  162. }
  163. }
  164. ],
  165. "state": "list"
  166. }
  167. }
  168. '''
  169. # -*- -*- -*- End included fragment: doc/user -*- -*- -*-
  170. # -*- -*- -*- Begin included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  171. # pylint: disable=undefined-variable,missing-docstring
  172. # noqa: E301,E302
  173. class YeditException(Exception):
  174. ''' Exception class for Yedit '''
  175. pass
  176. # pylint: disable=too-many-public-methods
  177. class Yedit(object):
  178. ''' Class to modify yaml files '''
  179. re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
  180. re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z%s/_-]+)"
  181. com_sep = set(['.', '#', '|', ':'])
  182. # pylint: disable=too-many-arguments
  183. def __init__(self,
  184. filename=None,
  185. content=None,
  186. content_type='yaml',
  187. separator='.',
  188. backup=False):
  189. self.content = content
  190. self._separator = separator
  191. self.filename = filename
  192. self.__yaml_dict = content
  193. self.content_type = content_type
  194. self.backup = backup
  195. self.load(content_type=self.content_type)
  196. if self.__yaml_dict is None:
  197. self.__yaml_dict = {}
  198. @property
  199. def separator(self):
  200. ''' getter method for yaml_dict '''
  201. return self._separator
  202. @separator.setter
  203. def separator(self):
  204. ''' getter method for yaml_dict '''
  205. return self._separator
  206. @property
  207. def yaml_dict(self):
  208. ''' getter method for yaml_dict '''
  209. return self.__yaml_dict
  210. @yaml_dict.setter
  211. def yaml_dict(self, value):
  212. ''' setter method for yaml_dict '''
  213. self.__yaml_dict = value
  214. @staticmethod
  215. def parse_key(key, sep='.'):
  216. '''parse the key allowing the appropriate separator'''
  217. common_separators = list(Yedit.com_sep - set([sep]))
  218. return re.findall(Yedit.re_key % ''.join(common_separators), key)
  219. @staticmethod
  220. def valid_key(key, sep='.'):
  221. '''validate the incoming key'''
  222. common_separators = list(Yedit.com_sep - set([sep]))
  223. if not re.match(Yedit.re_valid_key % ''.join(common_separators), key):
  224. return False
  225. return True
  226. @staticmethod
  227. def remove_entry(data, key, sep='.'):
  228. ''' remove data at location key '''
  229. if key == '' and isinstance(data, dict):
  230. data.clear()
  231. return True
  232. elif key == '' and isinstance(data, list):
  233. del data[:]
  234. return True
  235. if not (key and Yedit.valid_key(key, sep)) and \
  236. isinstance(data, (list, dict)):
  237. return None
  238. key_indexes = Yedit.parse_key(key, sep)
  239. for arr_ind, dict_key in key_indexes[:-1]:
  240. if dict_key and isinstance(data, dict):
  241. data = data.get(dict_key, None)
  242. elif (arr_ind and isinstance(data, list) and
  243. int(arr_ind) <= len(data) - 1):
  244. data = data[int(arr_ind)]
  245. else:
  246. return None
  247. # process last index for remove
  248. # expected list entry
  249. if key_indexes[-1][0]:
  250. if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  251. del data[int(key_indexes[-1][0])]
  252. return True
  253. # expected dict entry
  254. elif key_indexes[-1][1]:
  255. if isinstance(data, dict):
  256. del data[key_indexes[-1][1]]
  257. return True
  258. @staticmethod
  259. def add_entry(data, key, item=None, sep='.'):
  260. ''' Get an item from a dictionary with key notation a.b.c
  261. d = {'a': {'b': 'c'}}}
  262. key = a#b
  263. return c
  264. '''
  265. if key == '':
  266. pass
  267. elif (not (key and Yedit.valid_key(key, sep)) and
  268. isinstance(data, (list, dict))):
  269. return None
  270. key_indexes = Yedit.parse_key(key, sep)
  271. for arr_ind, dict_key in key_indexes[:-1]:
  272. if dict_key:
  273. if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
  274. data = data[dict_key]
  275. continue
  276. elif data and not isinstance(data, dict):
  277. return None
  278. data[dict_key] = {}
  279. data = data[dict_key]
  280. elif (arr_ind and isinstance(data, list) and
  281. int(arr_ind) <= len(data) - 1):
  282. data = data[int(arr_ind)]
  283. else:
  284. return None
  285. if key == '':
  286. data = item
  287. # process last index for add
  288. # expected list entry
  289. elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  290. data[int(key_indexes[-1][0])] = item
  291. # expected dict entry
  292. elif key_indexes[-1][1] and isinstance(data, dict):
  293. data[key_indexes[-1][1]] = item
  294. return data
  295. @staticmethod
  296. def get_entry(data, key, sep='.'):
  297. ''' Get an item from a dictionary with key notation a.b.c
  298. d = {'a': {'b': 'c'}}}
  299. key = a.b
  300. return c
  301. '''
  302. if key == '':
  303. pass
  304. elif (not (key and Yedit.valid_key(key, sep)) and
  305. isinstance(data, (list, dict))):
  306. return None
  307. key_indexes = Yedit.parse_key(key, sep)
  308. for arr_ind, dict_key in key_indexes:
  309. if dict_key and isinstance(data, dict):
  310. data = data.get(dict_key, None)
  311. elif (arr_ind and isinstance(data, list) and
  312. int(arr_ind) <= len(data) - 1):
  313. data = data[int(arr_ind)]
  314. else:
  315. return None
  316. return data
  317. @staticmethod
  318. def _write(filename, contents):
  319. ''' Actually write the file contents to disk. This helps with mocking. '''
  320. tmp_filename = filename + '.yedit'
  321. with open(tmp_filename, 'w') as yfd:
  322. yfd.write(contents)
  323. os.rename(tmp_filename, filename)
  324. def write(self):
  325. ''' write to file '''
  326. if not self.filename:
  327. raise YeditException('Please specify a filename.')
  328. if self.backup and self.file_exists():
  329. shutil.copy(self.filename, self.filename + '.orig')
  330. # Try to set format attributes if supported
  331. try:
  332. self.yaml_dict.fa.set_block_style()
  333. except AttributeError:
  334. pass
  335. # Try to use RoundTripDumper if supported.
  336. try:
  337. Yedit._write(self.filename, yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
  338. except AttributeError:
  339. Yedit._write(self.filename, yaml.safe_dump(self.yaml_dict, default_flow_style=False))
  340. return (True, self.yaml_dict)
  341. def read(self):
  342. ''' read from file '''
  343. # check if it exists
  344. if self.filename is None or not self.file_exists():
  345. return None
  346. contents = None
  347. with open(self.filename) as yfd:
  348. contents = yfd.read()
  349. return contents
  350. def file_exists(self):
  351. ''' return whether file exists '''
  352. if os.path.exists(self.filename):
  353. return True
  354. return False
  355. def load(self, content_type='yaml'):
  356. ''' return yaml file '''
  357. contents = self.read()
  358. if not contents and not self.content:
  359. return None
  360. if self.content:
  361. if isinstance(self.content, dict):
  362. self.yaml_dict = self.content
  363. return self.yaml_dict
  364. elif isinstance(self.content, str):
  365. contents = self.content
  366. # check if it is yaml
  367. try:
  368. if content_type == 'yaml' and contents:
  369. # Try to set format attributes if supported
  370. try:
  371. self.yaml_dict.fa.set_block_style()
  372. except AttributeError:
  373. pass
  374. # Try to use RoundTripLoader if supported.
  375. try:
  376. self.yaml_dict = yaml.safe_load(contents, yaml.RoundTripLoader)
  377. except AttributeError:
  378. self.yaml_dict = yaml.safe_load(contents)
  379. # Try to set format attributes if supported
  380. try:
  381. self.yaml_dict.fa.set_block_style()
  382. except AttributeError:
  383. pass
  384. elif content_type == 'json' and contents:
  385. self.yaml_dict = json.loads(contents)
  386. except yaml.YAMLError as err:
  387. # Error loading yaml or json
  388. raise YeditException('Problem with loading yaml file. %s' % err)
  389. return self.yaml_dict
  390. def get(self, key):
  391. ''' get a specified key'''
  392. try:
  393. entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
  394. except KeyError:
  395. entry = None
  396. return entry
  397. def pop(self, path, key_or_item):
  398. ''' remove a key, value pair from a dict or an item for a list'''
  399. try:
  400. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  401. except KeyError:
  402. entry = None
  403. if entry is None:
  404. return (False, self.yaml_dict)
  405. if isinstance(entry, dict):
  406. # AUDIT:maybe-no-member makes sense due to fuzzy types
  407. # pylint: disable=maybe-no-member
  408. if key_or_item in entry:
  409. entry.pop(key_or_item)
  410. return (True, self.yaml_dict)
  411. return (False, self.yaml_dict)
  412. elif isinstance(entry, list):
  413. # AUDIT:maybe-no-member makes sense due to fuzzy types
  414. # pylint: disable=maybe-no-member
  415. ind = None
  416. try:
  417. ind = entry.index(key_or_item)
  418. except ValueError:
  419. return (False, self.yaml_dict)
  420. entry.pop(ind)
  421. return (True, self.yaml_dict)
  422. return (False, self.yaml_dict)
  423. def delete(self, path):
  424. ''' remove path from a dict'''
  425. try:
  426. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  427. except KeyError:
  428. entry = None
  429. if entry is None:
  430. return (False, self.yaml_dict)
  431. result = Yedit.remove_entry(self.yaml_dict, path, self.separator)
  432. if not result:
  433. return (False, self.yaml_dict)
  434. return (True, self.yaml_dict)
  435. def exists(self, path, value):
  436. ''' check if value exists at path'''
  437. try:
  438. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  439. except KeyError:
  440. entry = None
  441. if isinstance(entry, list):
  442. if value in entry:
  443. return True
  444. return False
  445. elif isinstance(entry, dict):
  446. if isinstance(value, dict):
  447. rval = False
  448. for key, val in value.items():
  449. if entry[key] != val:
  450. rval = False
  451. break
  452. else:
  453. rval = True
  454. return rval
  455. return value in entry
  456. return entry == value
  457. def append(self, path, value):
  458. '''append value to a list'''
  459. try:
  460. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  461. except KeyError:
  462. entry = None
  463. if entry is None:
  464. self.put(path, [])
  465. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  466. if not isinstance(entry, list):
  467. return (False, self.yaml_dict)
  468. # AUDIT:maybe-no-member makes sense due to loading data from
  469. # a serialized format.
  470. # pylint: disable=maybe-no-member
  471. entry.append(value)
  472. return (True, self.yaml_dict)
  473. # pylint: disable=too-many-arguments
  474. def update(self, path, value, index=None, curr_value=None):
  475. ''' put path, value into a dict '''
  476. try:
  477. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  478. except KeyError:
  479. entry = None
  480. if isinstance(entry, dict):
  481. # AUDIT:maybe-no-member makes sense due to fuzzy types
  482. # pylint: disable=maybe-no-member
  483. if not isinstance(value, dict):
  484. raise YeditException('Cannot replace key, value entry in ' +
  485. 'dict with non-dict type. value=[%s] [%s]' % (value, type(value))) # noqa: E501
  486. entry.update(value)
  487. return (True, self.yaml_dict)
  488. elif isinstance(entry, list):
  489. # AUDIT:maybe-no-member makes sense due to fuzzy types
  490. # pylint: disable=maybe-no-member
  491. ind = None
  492. if curr_value:
  493. try:
  494. ind = entry.index(curr_value)
  495. except ValueError:
  496. return (False, self.yaml_dict)
  497. elif index is not None:
  498. ind = index
  499. if ind is not None and entry[ind] != value:
  500. entry[ind] = value
  501. return (True, self.yaml_dict)
  502. # see if it exists in the list
  503. try:
  504. ind = entry.index(value)
  505. except ValueError:
  506. # doesn't exist, append it
  507. entry.append(value)
  508. return (True, self.yaml_dict)
  509. # already exists, return
  510. if ind is not None:
  511. return (False, self.yaml_dict)
  512. return (False, self.yaml_dict)
  513. def put(self, path, value):
  514. ''' put path, value into a dict '''
  515. try:
  516. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  517. except KeyError:
  518. entry = None
  519. if entry == value:
  520. return (False, self.yaml_dict)
  521. # deepcopy didn't work
  522. # Try to use ruamel.yaml and fallback to pyyaml
  523. try:
  524. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  525. default_flow_style=False),
  526. yaml.RoundTripLoader)
  527. except AttributeError:
  528. tmp_copy = copy.deepcopy(self.yaml_dict)
  529. # set the format attributes if available
  530. try:
  531. tmp_copy.fa.set_block_style()
  532. except AttributeError:
  533. pass
  534. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  535. if not result:
  536. return (False, self.yaml_dict)
  537. self.yaml_dict = tmp_copy
  538. return (True, self.yaml_dict)
  539. def create(self, path, value):
  540. ''' create a yaml file '''
  541. if not self.file_exists():
  542. # deepcopy didn't work
  543. # Try to use ruamel.yaml and fallback to pyyaml
  544. try:
  545. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  546. default_flow_style=False),
  547. yaml.RoundTripLoader)
  548. except AttributeError:
  549. tmp_copy = copy.deepcopy(self.yaml_dict)
  550. # set the format attributes if available
  551. try:
  552. tmp_copy.fa.set_block_style()
  553. except AttributeError:
  554. pass
  555. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  556. if result:
  557. self.yaml_dict = tmp_copy
  558. return (True, self.yaml_dict)
  559. return (False, self.yaml_dict)
  560. @staticmethod
  561. def get_curr_value(invalue, val_type):
  562. '''return the current value'''
  563. if invalue is None:
  564. return None
  565. curr_value = invalue
  566. if val_type == 'yaml':
  567. curr_value = yaml.load(invalue)
  568. elif val_type == 'json':
  569. curr_value = json.loads(invalue)
  570. return curr_value
  571. @staticmethod
  572. def parse_value(inc_value, vtype=''):
  573. '''determine value type passed'''
  574. true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE',
  575. 'on', 'On', 'ON', ]
  576. false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE',
  577. 'off', 'Off', 'OFF']
  578. # It came in as a string but you didn't specify value_type as string
  579. # we will convert to bool if it matches any of the above cases
  580. if isinstance(inc_value, str) and 'bool' in vtype:
  581. if inc_value not in true_bools and inc_value not in false_bools:
  582. raise YeditException('Not a boolean type. str=[%s] vtype=[%s]'
  583. % (inc_value, vtype))
  584. elif isinstance(inc_value, bool) and 'str' in vtype:
  585. inc_value = str(inc_value)
  586. # If vtype is not str then go ahead and attempt to yaml load it.
  587. if isinstance(inc_value, str) and 'str' not in vtype:
  588. try:
  589. inc_value = yaml.load(inc_value)
  590. except Exception:
  591. raise YeditException('Could not determine type of incoming ' +
  592. 'value. value=[%s] vtype=[%s]'
  593. % (type(inc_value), vtype))
  594. return inc_value
  595. # pylint: disable=too-many-return-statements,too-many-branches
  596. @staticmethod
  597. def run_ansible(module):
  598. '''perform the idempotent crud operations'''
  599. yamlfile = Yedit(filename=module.params['src'],
  600. backup=module.params['backup'],
  601. separator=module.params['separator'])
  602. if module.params['src']:
  603. rval = yamlfile.load()
  604. if yamlfile.yaml_dict is None and \
  605. module.params['state'] != 'present':
  606. return {'failed': True,
  607. 'msg': 'Error opening file [%s]. Verify that the ' +
  608. 'file exists, that it is has correct' +
  609. ' permissions, and is valid yaml.'}
  610. if module.params['state'] == 'list':
  611. if module.params['content']:
  612. content = Yedit.parse_value(module.params['content'],
  613. module.params['content_type'])
  614. yamlfile.yaml_dict = content
  615. if module.params['key']:
  616. rval = yamlfile.get(module.params['key']) or {}
  617. return {'changed': False, 'result': rval, 'state': "list"}
  618. elif module.params['state'] == 'absent':
  619. if module.params['content']:
  620. content = Yedit.parse_value(module.params['content'],
  621. module.params['content_type'])
  622. yamlfile.yaml_dict = content
  623. if module.params['update']:
  624. rval = yamlfile.pop(module.params['key'],
  625. module.params['value'])
  626. else:
  627. rval = yamlfile.delete(module.params['key'])
  628. if rval[0] and module.params['src']:
  629. yamlfile.write()
  630. return {'changed': rval[0], 'result': rval[1], 'state': "absent"}
  631. elif module.params['state'] == 'present':
  632. # check if content is different than what is in the file
  633. if module.params['content']:
  634. content = Yedit.parse_value(module.params['content'],
  635. module.params['content_type'])
  636. # We had no edits to make and the contents are the same
  637. if yamlfile.yaml_dict == content and \
  638. module.params['value'] is None:
  639. return {'changed': False,
  640. 'result': yamlfile.yaml_dict,
  641. 'state': "present"}
  642. yamlfile.yaml_dict = content
  643. # we were passed a value; parse it
  644. if module.params['value']:
  645. value = Yedit.parse_value(module.params['value'],
  646. module.params['value_type'])
  647. key = module.params['key']
  648. if module.params['update']:
  649. # pylint: disable=line-too-long
  650. curr_value = Yedit.get_curr_value(Yedit.parse_value(module.params['curr_value']), # noqa: E501
  651. module.params['curr_value_format']) # noqa: E501
  652. rval = yamlfile.update(key, value, module.params['index'], curr_value) # noqa: E501
  653. elif module.params['append']:
  654. rval = yamlfile.append(key, value)
  655. else:
  656. rval = yamlfile.put(key, value)
  657. if rval[0] and module.params['src']:
  658. yamlfile.write()
  659. return {'changed': rval[0],
  660. 'result': rval[1], 'state': "present"}
  661. # no edits to make
  662. if module.params['src']:
  663. # pylint: disable=redefined-variable-type
  664. rval = yamlfile.write()
  665. return {'changed': rval[0],
  666. 'result': rval[1],
  667. 'state': "present"}
  668. return {'failed': True, 'msg': 'Unkown state passed'}
  669. # -*- -*- -*- End included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  670. # -*- -*- -*- Begin included fragment: lib/base.py -*- -*- -*-
  671. # pylint: disable=too-many-lines
  672. # noqa: E301,E302,E303,T001
  673. class OpenShiftCLIError(Exception):
  674. '''Exception class for openshiftcli'''
  675. pass
  676. ADDITIONAL_PATH_LOOKUPS = ['/usr/local/bin', os.path.expanduser('~/bin')]
  677. def locate_oc_binary():
  678. ''' Find and return oc binary file '''
  679. # https://github.com/openshift/openshift-ansible/issues/3410
  680. # oc can be in /usr/local/bin in some cases, but that may not
  681. # be in $PATH due to ansible/sudo
  682. paths = os.environ.get("PATH", os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS
  683. oc_binary = 'oc'
  684. # Use shutil.which if it is available, otherwise fallback to a naive path search
  685. try:
  686. which_result = shutil.which(oc_binary, path=os.pathsep.join(paths))
  687. if which_result is not None:
  688. oc_binary = which_result
  689. except AttributeError:
  690. for path in paths:
  691. if os.path.exists(os.path.join(path, oc_binary)):
  692. oc_binary = os.path.join(path, oc_binary)
  693. break
  694. return oc_binary
  695. # pylint: disable=too-few-public-methods
  696. class OpenShiftCLI(object):
  697. ''' Class to wrap the command line tools '''
  698. def __init__(self,
  699. namespace,
  700. kubeconfig='/etc/origin/master/admin.kubeconfig',
  701. verbose=False,
  702. all_namespaces=False):
  703. ''' Constructor for OpenshiftCLI '''
  704. self.namespace = namespace
  705. self.verbose = verbose
  706. self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
  707. self.all_namespaces = all_namespaces
  708. self.oc_binary = locate_oc_binary()
  709. # Pylint allows only 5 arguments to be passed.
  710. # pylint: disable=too-many-arguments
  711. def _replace_content(self, resource, rname, content, force=False, sep='.'):
  712. ''' replace the current object with the content '''
  713. res = self._get(resource, rname)
  714. if not res['results']:
  715. return res
  716. fname = Utils.create_tmpfile(rname + '-')
  717. yed = Yedit(fname, res['results'][0], separator=sep)
  718. changes = []
  719. for key, value in content.items():
  720. changes.append(yed.put(key, value))
  721. if any([change[0] for change in changes]):
  722. yed.write()
  723. atexit.register(Utils.cleanup, [fname])
  724. return self._replace(fname, force)
  725. return {'returncode': 0, 'updated': False}
  726. def _replace(self, fname, force=False):
  727. '''replace the current object with oc replace'''
  728. cmd = ['replace', '-f', fname]
  729. if force:
  730. cmd.append('--force')
  731. return self.openshift_cmd(cmd)
  732. def _create_from_content(self, rname, content):
  733. '''create a temporary file and then call oc create on it'''
  734. fname = Utils.create_tmpfile(rname + '-')
  735. yed = Yedit(fname, content=content)
  736. yed.write()
  737. atexit.register(Utils.cleanup, [fname])
  738. return self._create(fname)
  739. def _create(self, fname):
  740. '''call oc create on a filename'''
  741. return self.openshift_cmd(['create', '-f', fname])
  742. def _delete(self, resource, rname, selector=None):
  743. '''call oc delete on a resource'''
  744. cmd = ['delete', resource, rname]
  745. if selector:
  746. cmd.append('--selector=%s' % selector)
  747. return self.openshift_cmd(cmd)
  748. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  749. '''process a template
  750. template_name: the name of the template to process
  751. create: whether to send to oc create after processing
  752. params: the parameters for the template
  753. template_data: the incoming template's data; instead of a file
  754. '''
  755. cmd = ['process']
  756. if template_data:
  757. cmd.extend(['-f', '-'])
  758. else:
  759. cmd.append(template_name)
  760. if params:
  761. param_str = ["%s=%s" % (key, value) for key, value in params.items()]
  762. cmd.append('-v')
  763. cmd.extend(param_str)
  764. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  765. if results['returncode'] != 0 or not create:
  766. return results
  767. fname = Utils.create_tmpfile(template_name + '-')
  768. yed = Yedit(fname, results['results'])
  769. yed.write()
  770. atexit.register(Utils.cleanup, [fname])
  771. return self.openshift_cmd(['create', '-f', fname])
  772. def _get(self, resource, rname=None, selector=None):
  773. '''return a resource by name '''
  774. cmd = ['get', resource]
  775. if selector:
  776. cmd.append('--selector=%s' % selector)
  777. elif rname:
  778. cmd.append(rname)
  779. cmd.extend(['-o', 'json'])
  780. rval = self.openshift_cmd(cmd, output=True)
  781. # Ensure results are retuned in an array
  782. if 'items' in rval:
  783. rval['results'] = rval['items']
  784. elif not isinstance(rval['results'], list):
  785. rval['results'] = [rval['results']]
  786. return rval
  787. def _schedulable(self, node=None, selector=None, schedulable=True):
  788. ''' perform oadm manage-node scheduable '''
  789. cmd = ['manage-node']
  790. if node:
  791. cmd.extend(node)
  792. else:
  793. cmd.append('--selector=%s' % selector)
  794. cmd.append('--schedulable=%s' % schedulable)
  795. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  796. def _list_pods(self, node=None, selector=None, pod_selector=None):
  797. ''' perform oadm list pods
  798. node: the node in which to list pods
  799. selector: the label selector filter if provided
  800. pod_selector: the pod selector filter if provided
  801. '''
  802. cmd = ['manage-node']
  803. if node:
  804. cmd.extend(node)
  805. else:
  806. cmd.append('--selector=%s' % selector)
  807. if pod_selector:
  808. cmd.append('--pod-selector=%s' % pod_selector)
  809. cmd.extend(['--list-pods', '-o', 'json'])
  810. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  811. # pylint: disable=too-many-arguments
  812. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  813. ''' perform oadm manage-node evacuate '''
  814. cmd = ['manage-node']
  815. if node:
  816. cmd.extend(node)
  817. else:
  818. cmd.append('--selector=%s' % selector)
  819. if dry_run:
  820. cmd.append('--dry-run')
  821. if pod_selector:
  822. cmd.append('--pod-selector=%s' % pod_selector)
  823. if grace_period:
  824. cmd.append('--grace-period=%s' % int(grace_period))
  825. if force:
  826. cmd.append('--force')
  827. cmd.append('--evacuate')
  828. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  829. def _version(self):
  830. ''' return the openshift version'''
  831. return self.openshift_cmd(['version'], output=True, output_type='raw')
  832. def _import_image(self, url=None, name=None, tag=None):
  833. ''' perform image import '''
  834. cmd = ['import-image']
  835. image = '{0}'.format(name)
  836. if tag:
  837. image += ':{0}'.format(tag)
  838. cmd.append(image)
  839. if url:
  840. cmd.append('--from={0}/{1}'.format(url, image))
  841. cmd.append('-n{0}'.format(self.namespace))
  842. cmd.append('--confirm')
  843. return self.openshift_cmd(cmd)
  844. def _run(self, cmds, input_data):
  845. ''' Actually executes the command. This makes mocking easier. '''
  846. curr_env = os.environ.copy()
  847. curr_env.update({'KUBECONFIG': self.kubeconfig})
  848. proc = subprocess.Popen(cmds,
  849. stdin=subprocess.PIPE,
  850. stdout=subprocess.PIPE,
  851. stderr=subprocess.PIPE,
  852. env=curr_env)
  853. stdout, stderr = proc.communicate(input_data)
  854. return proc.returncode, stdout.decode(), stderr.decode()
  855. # pylint: disable=too-many-arguments,too-many-branches
  856. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  857. '''Base command for oc '''
  858. cmds = [self.oc_binary]
  859. if oadm:
  860. cmds.append('adm')
  861. if self.all_namespaces:
  862. cmds.extend(['--all-namespaces'])
  863. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  864. cmds.extend(['-n', self.namespace])
  865. cmds.extend(cmd)
  866. rval = {}
  867. results = ''
  868. err = None
  869. if self.verbose:
  870. print(' '.join(cmds))
  871. try:
  872. returncode, stdout, stderr = self._run(cmds, input_data)
  873. except OSError as ex:
  874. returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
  875. rval = {"returncode": returncode,
  876. "results": results,
  877. "cmd": ' '.join(cmds)}
  878. if returncode == 0:
  879. if output:
  880. if output_type == 'json':
  881. try:
  882. rval['results'] = json.loads(stdout)
  883. except ValueError as err:
  884. if "No JSON object could be decoded" in err.args:
  885. err = err.args
  886. elif output_type == 'raw':
  887. rval['results'] = stdout
  888. if self.verbose:
  889. print("STDOUT: {0}".format(stdout))
  890. print("STDERR: {0}".format(stderr))
  891. if err:
  892. rval.update({"err": err,
  893. "stderr": stderr,
  894. "stdout": stdout,
  895. "cmd": cmds})
  896. else:
  897. rval.update({"stderr": stderr,
  898. "stdout": stdout,
  899. "results": {}})
  900. return rval
  901. class Utils(object):
  902. ''' utilities for openshiftcli modules '''
  903. @staticmethod
  904. def _write(filename, contents):
  905. ''' Actually write the file contents to disk. This helps with mocking. '''
  906. with open(filename, 'w') as sfd:
  907. sfd.write(contents)
  908. @staticmethod
  909. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  910. ''' create a file in tmp with name and contents'''
  911. tmp = Utils.create_tmpfile(prefix=rname)
  912. if ftype == 'yaml':
  913. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  914. # pylint: disable=no-member
  915. if hasattr(yaml, 'RoundTripDumper'):
  916. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  917. else:
  918. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  919. elif ftype == 'json':
  920. Utils._write(tmp, json.dumps(data))
  921. else:
  922. Utils._write(tmp, data)
  923. # Register cleanup when module is done
  924. atexit.register(Utils.cleanup, [tmp])
  925. return tmp
  926. @staticmethod
  927. def create_tmpfile_copy(inc_file):
  928. '''create a temporary copy of a file'''
  929. tmpfile = Utils.create_tmpfile('lib_openshift-')
  930. Utils._write(tmpfile, open(inc_file).read())
  931. # Cleanup the tmpfile
  932. atexit.register(Utils.cleanup, [tmpfile])
  933. return tmpfile
  934. @staticmethod
  935. def create_tmpfile(prefix='tmp'):
  936. ''' Generates and returns a temporary file name '''
  937. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  938. return tmp.name
  939. @staticmethod
  940. def create_tmp_files_from_contents(content, content_type=None):
  941. '''Turn an array of dict: filename, content into a files array'''
  942. if not isinstance(content, list):
  943. content = [content]
  944. files = []
  945. for item in content:
  946. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  947. item['data'],
  948. ftype=content_type)
  949. files.append({'name': os.path.basename(item['path']),
  950. 'path': path})
  951. return files
  952. @staticmethod
  953. def cleanup(files):
  954. '''Clean up on exit '''
  955. for sfile in files:
  956. if os.path.exists(sfile):
  957. if os.path.isdir(sfile):
  958. shutil.rmtree(sfile)
  959. elif os.path.isfile(sfile):
  960. os.remove(sfile)
  961. @staticmethod
  962. def exists(results, _name):
  963. ''' Check to see if the results include the name '''
  964. if not results:
  965. return False
  966. if Utils.find_result(results, _name):
  967. return True
  968. return False
  969. @staticmethod
  970. def find_result(results, _name):
  971. ''' Find the specified result by name'''
  972. rval = None
  973. for result in results:
  974. if 'metadata' in result and result['metadata']['name'] == _name:
  975. rval = result
  976. break
  977. return rval
  978. @staticmethod
  979. def get_resource_file(sfile, sfile_type='yaml'):
  980. ''' return the service file '''
  981. contents = None
  982. with open(sfile) as sfd:
  983. contents = sfd.read()
  984. if sfile_type == 'yaml':
  985. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  986. # pylint: disable=no-member
  987. if hasattr(yaml, 'RoundTripLoader'):
  988. contents = yaml.load(contents, yaml.RoundTripLoader)
  989. else:
  990. contents = yaml.safe_load(contents)
  991. elif sfile_type == 'json':
  992. contents = json.loads(contents)
  993. return contents
  994. @staticmethod
  995. def filter_versions(stdout):
  996. ''' filter the oc version output '''
  997. version_dict = {}
  998. version_search = ['oc', 'openshift', 'kubernetes']
  999. for line in stdout.strip().split('\n'):
  1000. for term in version_search:
  1001. if not line:
  1002. continue
  1003. if line.startswith(term):
  1004. version_dict[term] = line.split()[-1]
  1005. # horrible hack to get openshift version in Openshift 3.2
  1006. # By default "oc version in 3.2 does not return an "openshift" version
  1007. if "openshift" not in version_dict:
  1008. version_dict["openshift"] = version_dict["oc"]
  1009. return version_dict
  1010. @staticmethod
  1011. def add_custom_versions(versions):
  1012. ''' create custom versions strings '''
  1013. versions_dict = {}
  1014. for tech, version in versions.items():
  1015. # clean up "-" from version
  1016. if "-" in version:
  1017. version = version.split("-")[0]
  1018. if version.startswith('v'):
  1019. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  1020. # "v3.3.0.33" is what we have, we want "3.3"
  1021. versions_dict[tech + '_short'] = version[1:4]
  1022. return versions_dict
  1023. @staticmethod
  1024. def openshift_installed():
  1025. ''' check if openshift is installed '''
  1026. import yum
  1027. yum_base = yum.YumBase()
  1028. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  1029. return True
  1030. return False
  1031. # Disabling too-many-branches. This is a yaml dictionary comparison function
  1032. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  1033. @staticmethod
  1034. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  1035. ''' Given a user defined definition, compare it with the results given back by our query. '''
  1036. # Currently these values are autogenerated and we do not need to check them
  1037. skip = ['metadata', 'status']
  1038. if skip_keys:
  1039. skip.extend(skip_keys)
  1040. for key, value in result_def.items():
  1041. if key in skip:
  1042. continue
  1043. # Both are lists
  1044. if isinstance(value, list):
  1045. if key not in user_def:
  1046. if debug:
  1047. print('User data does not have key [%s]' % key)
  1048. print('User data: %s' % user_def)
  1049. return False
  1050. if not isinstance(user_def[key], list):
  1051. if debug:
  1052. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  1053. return False
  1054. if len(user_def[key]) != len(value):
  1055. if debug:
  1056. print("List lengths are not equal.")
  1057. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  1058. print("user_def: %s" % user_def[key])
  1059. print("value: %s" % value)
  1060. return False
  1061. for values in zip(user_def[key], value):
  1062. if isinstance(values[0], dict) and isinstance(values[1], dict):
  1063. if debug:
  1064. print('sending list - list')
  1065. print(type(values[0]))
  1066. print(type(values[1]))
  1067. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  1068. if not result:
  1069. print('list compare returned false')
  1070. return False
  1071. elif value != user_def[key]:
  1072. if debug:
  1073. print('value should be identical')
  1074. print(value)
  1075. print(user_def[key])
  1076. return False
  1077. # recurse on a dictionary
  1078. elif isinstance(value, dict):
  1079. if key not in user_def:
  1080. if debug:
  1081. print("user_def does not have key [%s]" % key)
  1082. return False
  1083. if not isinstance(user_def[key], dict):
  1084. if debug:
  1085. print("dict returned false: not instance of dict")
  1086. return False
  1087. # before passing ensure keys match
  1088. api_values = set(value.keys()) - set(skip)
  1089. user_values = set(user_def[key].keys()) - set(skip)
  1090. if api_values != user_values:
  1091. if debug:
  1092. print("keys are not equal in dict")
  1093. print(api_values)
  1094. print(user_values)
  1095. return False
  1096. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1097. if not result:
  1098. if debug:
  1099. print("dict returned false")
  1100. print(result)
  1101. return False
  1102. # Verify each key, value pair is the same
  1103. else:
  1104. if key not in user_def or value != user_def[key]:
  1105. if debug:
  1106. print("value not equal; user_def does not have key")
  1107. print(key)
  1108. print(value)
  1109. if key in user_def:
  1110. print(user_def[key])
  1111. return False
  1112. if debug:
  1113. print('returning true')
  1114. return True
  1115. class OpenShiftCLIConfig(object):
  1116. '''Generic Config'''
  1117. def __init__(self, rname, namespace, kubeconfig, options):
  1118. self.kubeconfig = kubeconfig
  1119. self.name = rname
  1120. self.namespace = namespace
  1121. self._options = options
  1122. @property
  1123. def config_options(self):
  1124. ''' return config options '''
  1125. return self._options
  1126. def to_option_list(self):
  1127. '''return all options as a string'''
  1128. return self.stringify()
  1129. def stringify(self):
  1130. ''' return the options hash as cli params in a string '''
  1131. rval = []
  1132. for key, data in self.config_options.items():
  1133. if data['include'] \
  1134. and (data['value'] or isinstance(data['value'], int)):
  1135. rval.append('--%s=%s' % (key.replace('_', '-'), data['value']))
  1136. return rval
  1137. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1138. # -*- -*- -*- Begin included fragment: lib/user.py -*- -*- -*-
  1139. class UserConfig(object):
  1140. ''' Handle user options '''
  1141. def __init__(self,
  1142. kubeconfig,
  1143. username,
  1144. full_name):
  1145. ''' constructor for handling user options '''
  1146. self.kubeconfig = kubeconfig
  1147. self.username = username
  1148. self.full_name = full_name
  1149. self.data = {}
  1150. self.create_dict()
  1151. def create_dict(self):
  1152. ''' return a user as a dict '''
  1153. self.data['apiVersion'] = 'v1'
  1154. self.data['fullName'] = self.full_name
  1155. self.data['groups'] = None
  1156. self.data['identities'] = None
  1157. self.data['kind'] = 'User'
  1158. self.data['metadata'] = {}
  1159. self.data['metadata']['name'] = self.username
  1160. # pylint: disable=too-many-instance-attributes
  1161. class User(Yedit):
  1162. ''' Class to wrap the oc command line tools '''
  1163. kind = 'user'
  1164. def __init__(self, content):
  1165. '''User constructor'''
  1166. super(User, self).__init__(content=content)
  1167. # -*- -*- -*- End included fragment: lib/user.py -*- -*- -*-
  1168. # -*- -*- -*- Begin included fragment: class/oc_user.py -*- -*- -*-
  1169. # pylint: disable=too-many-instance-attributes
  1170. class OCUser(OpenShiftCLI):
  1171. ''' Class to wrap the oc command line tools '''
  1172. kind = 'users'
  1173. def __init__(self,
  1174. config,
  1175. groups=None,
  1176. verbose=False):
  1177. ''' Constructor for OCUser '''
  1178. # namespace has no meaning for user operations, hardcode to 'default'
  1179. super(OCUser, self).__init__('default', config.kubeconfig)
  1180. self.config = config
  1181. self.groups = groups
  1182. self._user = None
  1183. @property
  1184. def user(self):
  1185. ''' property function user'''
  1186. if not self._user:
  1187. self.get()
  1188. return self._user
  1189. @user.setter
  1190. def user(self, data):
  1191. ''' setter function for user '''
  1192. self._user = data
  1193. def exists(self):
  1194. ''' return whether a user exists '''
  1195. if self.user:
  1196. return True
  1197. return False
  1198. def get(self):
  1199. ''' return user information '''
  1200. result = self._get(self.kind, self.config.username)
  1201. if result['returncode'] == 0:
  1202. self.user = User(content=result['results'][0])
  1203. elif 'users \"%s\" not found' % self.config.username in result['stderr']:
  1204. result['returncode'] = 0
  1205. result['results'] = [{}]
  1206. return result
  1207. def delete(self):
  1208. ''' delete the object '''
  1209. return self._delete(self.kind, self.config.username)
  1210. def create_group_entries(self):
  1211. ''' make entries for user to the provided group list '''
  1212. if self.groups != None:
  1213. for group in self.groups:
  1214. cmd = ['groups', 'add-users', group, self.config.username]
  1215. rval = self.openshift_cmd(cmd, oadm=True)
  1216. if rval['returncode'] != 0:
  1217. return rval
  1218. return rval
  1219. return {'returncode': 0}
  1220. def create(self):
  1221. ''' create the object '''
  1222. rval = self.create_group_entries()
  1223. if rval['returncode'] != 0:
  1224. return rval
  1225. return self._create_from_content(self.config.username, self.config.data)
  1226. def group_update(self):
  1227. ''' update group membership '''
  1228. rval = {'returncode': 0}
  1229. cmd = ['get', 'groups', '-o', 'json']
  1230. all_groups = self.openshift_cmd(cmd, output=True)
  1231. # pylint misindentifying all_groups['results']['items'] type
  1232. # pylint: disable=invalid-sequence-index
  1233. for group in all_groups['results']['items']:
  1234. # If we're supposed to be in this group
  1235. if group['metadata']['name'] in self.groups \
  1236. and (group['users'] is None or self.config.username not in group['users']):
  1237. cmd = ['groups', 'add-users', group['metadata']['name'],
  1238. self.config.username]
  1239. rval = self.openshift_cmd(cmd, oadm=True)
  1240. if rval['returncode'] != 0:
  1241. return rval
  1242. # else if we're in the group, but aren't supposed to be
  1243. elif group['users'] != None and self.config.username in group['users'] \
  1244. and group['metadata']['name'] not in self.groups:
  1245. cmd = ['groups', 'remove-users', group['metadata']['name'],
  1246. self.config.username]
  1247. rval = self.openshift_cmd(cmd, oadm=True)
  1248. if rval['returncode'] != 0:
  1249. return rval
  1250. return rval
  1251. def update(self):
  1252. ''' update the object '''
  1253. rval = self.group_update()
  1254. if rval['returncode'] != 0:
  1255. return rval
  1256. # need to update the user's info
  1257. return self._replace_content(self.kind, self.config.username, self.config.data, force=True)
  1258. def needs_group_update(self):
  1259. ''' check if there are group membership changes '''
  1260. cmd = ['get', 'groups', '-o', 'json']
  1261. all_groups = self.openshift_cmd(cmd, output=True)
  1262. # pylint misindentifying all_groups['results']['items'] type
  1263. # pylint: disable=invalid-sequence-index
  1264. for group in all_groups['results']['items']:
  1265. # If we're supposed to be in this group
  1266. if group['metadata']['name'] in self.groups \
  1267. and (group['users'] is None or self.config.username not in group['users']):
  1268. return True
  1269. # else if we're in the group, but aren't supposed to be
  1270. elif group['users'] != None and self.config.username in group['users'] \
  1271. and group['metadata']['name'] not in self.groups:
  1272. return True
  1273. return False
  1274. def needs_update(self):
  1275. ''' verify an update is needed '''
  1276. skip = []
  1277. if self.needs_group_update():
  1278. return True
  1279. return not Utils.check_def_equal(self.config.data, self.user.yaml_dict, skip_keys=skip, debug=True)
  1280. # pylint: disable=too-many-return-statements
  1281. @staticmethod
  1282. def run_ansible(params, check_mode=False):
  1283. ''' run the idempotent ansible code
  1284. params comes from the ansible portion of this module
  1285. check_mode: does the module support check mode. (module.check_mode)
  1286. '''
  1287. uconfig = UserConfig(params['kubeconfig'],
  1288. params['username'],
  1289. params['full_name'],
  1290. )
  1291. oc_user = OCUser(uconfig, params['groups'],
  1292. verbose=params['debug'])
  1293. state = params['state']
  1294. api_rval = oc_user.get()
  1295. #####
  1296. # Get
  1297. #####
  1298. if state == 'list':
  1299. return {'changed': False, 'results': api_rval['results'], 'state': "list"}
  1300. ########
  1301. # Delete
  1302. ########
  1303. if state == 'absent':
  1304. if oc_user.exists():
  1305. if check_mode:
  1306. return {'changed': False, 'msg': 'Would have performed a delete.'}
  1307. api_rval = oc_user.delete()
  1308. return {'changed': True, 'results': api_rval, 'state': "absent"}
  1309. return {'changed': False, 'state': "absent"}
  1310. if state == 'present':
  1311. ########
  1312. # Create
  1313. ########
  1314. if not oc_user.exists():
  1315. if check_mode:
  1316. return {'changed': False, 'msg': 'Would have performed a create.'}
  1317. # Create it here
  1318. api_rval = oc_user.create()
  1319. if api_rval['returncode'] != 0:
  1320. return {'failed': True, 'msg': api_rval}
  1321. # return the created object
  1322. api_rval = oc_user.get()
  1323. if api_rval['returncode'] != 0:
  1324. return {'failed': True, 'msg': api_rval}
  1325. return {'changed': True, 'results': api_rval, 'state': "present"}
  1326. ########
  1327. # Update
  1328. ########
  1329. if oc_user.needs_update():
  1330. api_rval = oc_user.update()
  1331. if api_rval['returncode'] != 0:
  1332. return {'failed': True, 'msg': api_rval}
  1333. orig_cmd = api_rval['cmd']
  1334. # return the created object
  1335. api_rval = oc_user.get()
  1336. # overwrite the get/list cmd
  1337. api_rval['cmd'] = orig_cmd
  1338. if api_rval['returncode'] != 0:
  1339. return {'failed': True, 'msg': api_rval}
  1340. return {'changed': True, 'results': api_rval, 'state': "present"}
  1341. return {'changed': False, 'results': api_rval, 'state': "present"}
  1342. return {'failed': True,
  1343. 'changed': False,
  1344. 'results': 'Unknown state passed. %s' % state,
  1345. 'state': "unknown"}
  1346. # -*- -*- -*- End included fragment: class/oc_user.py -*- -*- -*-
  1347. # -*- -*- -*- Begin included fragment: ansible/oc_user.py -*- -*- -*-
  1348. def main():
  1349. '''
  1350. ansible oc module for user
  1351. '''
  1352. module = AnsibleModule(
  1353. argument_spec=dict(
  1354. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1355. state=dict(default='present', type='str',
  1356. choices=['present', 'absent', 'list']),
  1357. debug=dict(default=False, type='bool'),
  1358. username=dict(default=None, type='str'),
  1359. full_name=dict(default=None, type='str'),
  1360. # setting groups for user data will not populate the
  1361. # 'groups' field in the user data.
  1362. # it will call out to the group data and make the user
  1363. # entry there
  1364. groups=dict(default=[], type='list'),
  1365. ),
  1366. supports_check_mode=True,
  1367. )
  1368. results = OCUser.run_ansible(module.params, module.check_mode)
  1369. if 'failed' in results:
  1370. module.fail_json(**results)
  1371. module.exit_json(**results)
  1372. if __name__ == '__main__':
  1373. main()
  1374. # -*- -*- -*- End included fragment: ansible/oc_user.py -*- -*- -*-