oc_serviceaccount.py 51 KB

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