oc_process.py 49 KB

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