oc_serviceaccount_secret.py 54 KB

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