oc_serviceaccount.py 50 KB

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