oc_edit.py 50 KB

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