oc_edit.py 48 KB

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