oc_obj.py 49 KB

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