oc_serviceaccount_secret.py 52 KB

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