oc_serviceaccount_secret.py 51 KB

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