oc_process.py 50 KB

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