oc_user.py 58 KB

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