oc_group.py 51 KB

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