oc_edit.py 48 KB

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