oc_obj.py 50 KB

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