oc_serviceaccount.py 50 KB

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