oc_serviceaccount.py 54 KB

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