oc_serviceaccount_secret.py 51 KB

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