oc_serviceaccount.py 53 KB

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