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