oc_edit.py 48 KB

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