oc_serviceaccount.py 57 KB

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