oc_serviceaccount.py 60 KB

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