yedit.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. #!/usr/bin/env python
  2. # pylint: disable=missing-docstring
  3. # ___ ___ _ _ ___ ___ _ _____ ___ ___
  4. # / __| __| \| | __| _ \ /_\_ _| __| \
  5. # | (_ | _|| .` | _|| / / _ \| | | _|| |) |
  6. # \___|___|_|\_|___|_|_\/_/_\_\_|_|___|___/_ _____
  7. # | \ / _ \ | \| |/ _ \_ _| | __| \_ _|_ _|
  8. # | |) | (_) | | .` | (_) || | | _|| |) | | | |
  9. # |___/ \___/ |_|\_|\___/ |_| |___|___/___| |_|
  10. #
  11. # Copyright 2016 Red Hat, Inc. and/or its affiliates
  12. # and other contributors as indicated by the @author tags.
  13. #
  14. # Licensed under the Apache License, Version 2.0 (the "License");
  15. # you may not use this file except in compliance with the License.
  16. # You may obtain a copy of the License at
  17. #
  18. # http://www.apache.org/licenses/LICENSE-2.0
  19. #
  20. # Unless required by applicable law or agreed to in writing, software
  21. # distributed under the License is distributed on an "AS IS" BASIS,
  22. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23. # See the License for the specific language governing permissions and
  24. # limitations under the License.
  25. #
  26. # -*- -*- -*- Begin included fragment: lib/import.py -*- -*- -*-
  27. # pylint: disable=wrong-import-order,wrong-import-position,unused-import
  28. from __future__ import print_function # noqa: F401
  29. import json # noqa: F401
  30. import os # noqa: F401
  31. import re # noqa: F401
  32. # pylint: disable=import-error
  33. import ruamel.yaml as yaml # noqa: F401
  34. import shutil # noqa: F401
  35. from ansible.module_utils.basic import AnsibleModule
  36. # -*- -*- -*- End included fragment: lib/import.py -*- -*- -*-
  37. # -*- -*- -*- Begin included fragment: doc/yedit -*- -*- -*-
  38. DOCUMENTATION = '''
  39. ---
  40. module: yedit
  41. short_description: Create, modify, and idempotently manage yaml files.
  42. description:
  43. - Modify yaml files programmatically.
  44. options:
  45. state:
  46. description:
  47. - State represents whether to create, modify, delete, or list yaml
  48. required: true
  49. default: present
  50. choices: ["present", "absent", "list"]
  51. aliases: []
  52. debug:
  53. description:
  54. - Turn on debug information.
  55. required: false
  56. default: false
  57. aliases: []
  58. src:
  59. description:
  60. - The file that is the target of the modifications.
  61. required: false
  62. default: None
  63. aliases: []
  64. content:
  65. description:
  66. - Content represents the yaml content you desire to work with. This
  67. - could be the file contents to write or the inmemory data to modify.
  68. required: false
  69. default: None
  70. aliases: []
  71. content_type:
  72. description:
  73. - The python type of the content parameter.
  74. required: false
  75. default: 'dict'
  76. aliases: []
  77. key:
  78. description:
  79. - The path to the value you wish to modify. Emtpy string means the top of
  80. - the document.
  81. required: false
  82. default: ''
  83. aliases: []
  84. value:
  85. description:
  86. - The incoming value of parameter 'key'.
  87. required: false
  88. default:
  89. aliases: []
  90. value_type:
  91. description:
  92. - The python type of the incoming value.
  93. required: false
  94. default: ''
  95. aliases: []
  96. update:
  97. description:
  98. - Whether the update should be performed on a dict/hash or list/array
  99. - object.
  100. required: false
  101. default: false
  102. aliases: []
  103. append:
  104. description:
  105. - Whether to append to an array/list. When the key does not exist or is
  106. - null, a new array is created. When the key is of a non-list type,
  107. - nothing is done.
  108. required: false
  109. default: false
  110. aliases: []
  111. index:
  112. description:
  113. - Used in conjunction with the update parameter. This will update a
  114. - specific index in an array/list.
  115. required: false
  116. default: false
  117. aliases: []
  118. curr_value:
  119. description:
  120. - Used in conjunction with the update parameter. This is the current
  121. - value of 'key' in the yaml file.
  122. required: false
  123. default: false
  124. aliases: []
  125. curr_value_format:
  126. description:
  127. - Format of the incoming current value.
  128. choices: ["yaml", "json", "str"]
  129. required: false
  130. default: false
  131. aliases: []
  132. backup:
  133. description:
  134. - Whether to make a backup copy of the current file when performing an
  135. - edit.
  136. required: false
  137. default: true
  138. aliases: []
  139. separator:
  140. description:
  141. - The separator being used when parsing strings.
  142. required: false
  143. default: '.'
  144. aliases: []
  145. author:
  146. - "Kenny Woodson <kwoodson@redhat.com>"
  147. extends_documentation_fragment: []
  148. '''
  149. EXAMPLES = '''
  150. # Simple insert of key, value
  151. - name: insert simple key, value
  152. yedit:
  153. src: somefile.yml
  154. key: test
  155. value: somevalue
  156. state: present
  157. # Results:
  158. # test: somevalue
  159. # Multilevel insert of key, value
  160. - name: insert simple key, value
  161. yedit:
  162. src: somefile.yml
  163. key: a#b#c
  164. value: d
  165. state: present
  166. # Results:
  167. # a:
  168. # b:
  169. # c: d
  170. '''
  171. # -*- -*- -*- End included fragment: doc/yedit -*- -*- -*-
  172. # -*- -*- -*- Begin included fragment: class/yedit.py -*- -*- -*-
  173. # noqa: E301,E302
  174. class YeditException(Exception):
  175. ''' Exception class for Yedit '''
  176. pass
  177. # pylint: disable=too-many-public-methods
  178. class Yedit(object):
  179. ''' Class to modify yaml files '''
  180. re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
  181. re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z%s/_-]+)"
  182. com_sep = set(['.', '#', '|', ':'])
  183. # pylint: disable=too-many-arguments
  184. def __init__(self,
  185. filename=None,
  186. content=None,
  187. content_type='yaml',
  188. separator='.',
  189. backup=False):
  190. self.content = content
  191. self._separator = separator
  192. self.filename = filename
  193. self.__yaml_dict = content
  194. self.content_type = content_type
  195. self.backup = backup
  196. self.load(content_type=self.content_type)
  197. if self.__yaml_dict is None:
  198. self.__yaml_dict = {}
  199. @property
  200. def separator(self):
  201. ''' getter method for yaml_dict '''
  202. return self._separator
  203. @separator.setter
  204. def separator(self):
  205. ''' getter method for yaml_dict '''
  206. return self._separator
  207. @property
  208. def yaml_dict(self):
  209. ''' getter method for yaml_dict '''
  210. return self.__yaml_dict
  211. @yaml_dict.setter
  212. def yaml_dict(self, value):
  213. ''' setter method for yaml_dict '''
  214. self.__yaml_dict = value
  215. @staticmethod
  216. def parse_key(key, sep='.'):
  217. '''parse the key allowing the appropriate separator'''
  218. common_separators = list(Yedit.com_sep - set([sep]))
  219. return re.findall(Yedit.re_key % ''.join(common_separators), key)
  220. @staticmethod
  221. def valid_key(key, sep='.'):
  222. '''validate the incoming key'''
  223. common_separators = list(Yedit.com_sep - set([sep]))
  224. if not re.match(Yedit.re_valid_key % ''.join(common_separators), key):
  225. return False
  226. return True
  227. @staticmethod
  228. def remove_entry(data, key, sep='.'):
  229. ''' remove data at location key '''
  230. if key == '' and isinstance(data, dict):
  231. data.clear()
  232. return True
  233. elif key == '' and isinstance(data, list):
  234. del data[:]
  235. return True
  236. if not (key and Yedit.valid_key(key, sep)) and \
  237. isinstance(data, (list, dict)):
  238. return None
  239. key_indexes = Yedit.parse_key(key, sep)
  240. for arr_ind, dict_key in key_indexes[:-1]:
  241. if dict_key and isinstance(data, dict):
  242. data = data.get(dict_key, None)
  243. elif (arr_ind and isinstance(data, list) and
  244. int(arr_ind) <= len(data) - 1):
  245. data = data[int(arr_ind)]
  246. else:
  247. return None
  248. # process last index for remove
  249. # expected list entry
  250. if key_indexes[-1][0]:
  251. if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  252. del data[int(key_indexes[-1][0])]
  253. return True
  254. # expected dict entry
  255. elif key_indexes[-1][1]:
  256. if isinstance(data, dict):
  257. del data[key_indexes[-1][1]]
  258. return True
  259. @staticmethod
  260. def add_entry(data, key, item=None, sep='.'):
  261. ''' Get an item from a dictionary with key notation a.b.c
  262. d = {'a': {'b': 'c'}}}
  263. key = a#b
  264. return c
  265. '''
  266. if key == '':
  267. pass
  268. elif (not (key and Yedit.valid_key(key, sep)) and
  269. isinstance(data, (list, dict))):
  270. return None
  271. key_indexes = Yedit.parse_key(key, sep)
  272. for arr_ind, dict_key in key_indexes[:-1]:
  273. if dict_key:
  274. if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
  275. data = data[dict_key]
  276. continue
  277. elif data and not isinstance(data, dict):
  278. return None
  279. data[dict_key] = {}
  280. data = data[dict_key]
  281. elif (arr_ind and isinstance(data, list) and
  282. int(arr_ind) <= len(data) - 1):
  283. data = data[int(arr_ind)]
  284. else:
  285. return None
  286. if key == '':
  287. data = item
  288. # process last index for add
  289. # expected list entry
  290. elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  291. data[int(key_indexes[-1][0])] = item
  292. # expected dict entry
  293. elif key_indexes[-1][1] and isinstance(data, dict):
  294. data[key_indexes[-1][1]] = item
  295. return data
  296. @staticmethod
  297. def get_entry(data, key, sep='.'):
  298. ''' Get an item from a dictionary with key notation a.b.c
  299. d = {'a': {'b': 'c'}}}
  300. key = a.b
  301. return c
  302. '''
  303. if key == '':
  304. pass
  305. elif (not (key and Yedit.valid_key(key, sep)) and
  306. isinstance(data, (list, dict))):
  307. return None
  308. key_indexes = Yedit.parse_key(key, sep)
  309. for arr_ind, dict_key in key_indexes:
  310. if dict_key and isinstance(data, dict):
  311. data = data.get(dict_key, None)
  312. elif (arr_ind and isinstance(data, list) and
  313. int(arr_ind) <= len(data) - 1):
  314. data = data[int(arr_ind)]
  315. else:
  316. return None
  317. return data
  318. @staticmethod
  319. def _write(filename, contents):
  320. ''' Actually write the file contents to disk. This helps with mocking. '''
  321. tmp_filename = filename + '.yedit'
  322. with open(tmp_filename, 'w') as yfd:
  323. yfd.write(contents)
  324. os.rename(tmp_filename, filename)
  325. def write(self):
  326. ''' write to file '''
  327. if not self.filename:
  328. raise YeditException('Please specify a filename.')
  329. if self.backup and self.file_exists():
  330. shutil.copy(self.filename, self.filename + '.orig')
  331. # pylint: disable=no-member
  332. if hasattr(self.yaml_dict, 'fa'):
  333. self.yaml_dict.fa.set_block_style()
  334. Yedit._write(self.filename, yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
  335. return (True, self.yaml_dict)
  336. def read(self):
  337. ''' read from file '''
  338. # check if it exists
  339. if self.filename is None or not self.file_exists():
  340. return None
  341. contents = None
  342. with open(self.filename) as yfd:
  343. contents = yfd.read()
  344. return contents
  345. def file_exists(self):
  346. ''' return whether file exists '''
  347. if os.path.exists(self.filename):
  348. return True
  349. return False
  350. def load(self, content_type='yaml'):
  351. ''' return yaml file '''
  352. contents = self.read()
  353. if not contents and not self.content:
  354. return None
  355. if self.content:
  356. if isinstance(self.content, dict):
  357. self.yaml_dict = self.content
  358. return self.yaml_dict
  359. elif isinstance(self.content, str):
  360. contents = self.content
  361. # check if it is yaml
  362. try:
  363. if content_type == 'yaml' and contents:
  364. self.yaml_dict = yaml.load(contents, yaml.RoundTripLoader)
  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. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  501. default_flow_style=False),
  502. yaml.RoundTripLoader)
  503. # pylint: disable=no-member
  504. if hasattr(self.yaml_dict, 'fa'):
  505. tmp_copy.fa.set_block_style()
  506. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  507. if not result:
  508. return (False, self.yaml_dict)
  509. self.yaml_dict = tmp_copy
  510. return (True, self.yaml_dict)
  511. def create(self, path, value):
  512. ''' create a yaml file '''
  513. if not self.file_exists():
  514. # deepcopy didn't work
  515. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict, default_flow_style=False), # noqa: E501
  516. yaml.RoundTripLoader)
  517. # pylint: disable=no-member
  518. if hasattr(self.yaml_dict, 'fa'):
  519. tmp_copy.fa.set_block_style()
  520. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  521. if result:
  522. self.yaml_dict = tmp_copy
  523. return (True, self.yaml_dict)
  524. return (False, self.yaml_dict)
  525. @staticmethod
  526. def get_curr_value(invalue, val_type):
  527. '''return the current value'''
  528. if invalue is None:
  529. return None
  530. curr_value = invalue
  531. if val_type == 'yaml':
  532. curr_value = yaml.load(invalue)
  533. elif val_type == 'json':
  534. curr_value = json.loads(invalue)
  535. return curr_value
  536. @staticmethod
  537. def parse_value(inc_value, vtype=''):
  538. '''determine value type passed'''
  539. true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE',
  540. 'on', 'On', 'ON', ]
  541. false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE',
  542. 'off', 'Off', 'OFF']
  543. # It came in as a string but you didn't specify value_type as string
  544. # we will convert to bool if it matches any of the above cases
  545. if isinstance(inc_value, str) and 'bool' in vtype:
  546. if inc_value not in true_bools and inc_value not in false_bools:
  547. raise YeditException('Not a boolean type. str=[%s] vtype=[%s]'
  548. % (inc_value, vtype))
  549. elif isinstance(inc_value, bool) and 'str' in vtype:
  550. inc_value = str(inc_value)
  551. # If vtype is not str then go ahead and attempt to yaml load it.
  552. if isinstance(inc_value, str) and 'str' not in vtype:
  553. try:
  554. inc_value = yaml.load(inc_value)
  555. except Exception:
  556. raise YeditException('Could not determine type of incoming ' +
  557. 'value. value=[%s] vtype=[%s]'
  558. % (type(inc_value), vtype))
  559. return inc_value
  560. # pylint: disable=too-many-return-statements,too-many-branches
  561. @staticmethod
  562. def run_ansible(module):
  563. '''perform the idempotent crud operations'''
  564. yamlfile = Yedit(filename=module.params['src'],
  565. backup=module.params['backup'],
  566. separator=module.params['separator'])
  567. if module.params['src']:
  568. rval = yamlfile.load()
  569. if yamlfile.yaml_dict is None and \
  570. module.params['state'] != 'present':
  571. return {'failed': True,
  572. 'msg': 'Error opening file [%s]. Verify that the ' +
  573. 'file exists, that it is has correct' +
  574. ' permissions, and is valid yaml.'}
  575. if module.params['state'] == 'list':
  576. if module.params['content']:
  577. content = Yedit.parse_value(module.params['content'],
  578. module.params['content_type'])
  579. yamlfile.yaml_dict = content
  580. if module.params['key']:
  581. rval = yamlfile.get(module.params['key']) or {}
  582. return {'changed': False, 'result': rval, 'state': "list"}
  583. elif module.params['state'] == 'absent':
  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['update']:
  589. rval = yamlfile.pop(module.params['key'],
  590. module.params['value'])
  591. else:
  592. rval = yamlfile.delete(module.params['key'])
  593. if rval[0] and module.params['src']:
  594. yamlfile.write()
  595. return {'changed': rval[0], 'result': rval[1], 'state': "absent"}
  596. elif module.params['state'] == 'present':
  597. # check if content is different than what is in the file
  598. if module.params['content']:
  599. content = Yedit.parse_value(module.params['content'],
  600. module.params['content_type'])
  601. # We had no edits to make and the contents are the same
  602. if yamlfile.yaml_dict == content and \
  603. module.params['value'] is None:
  604. return {'changed': False,
  605. 'result': yamlfile.yaml_dict,
  606. 'state': "present"}
  607. yamlfile.yaml_dict = content
  608. # we were passed a value; parse it
  609. if module.params['value']:
  610. value = Yedit.parse_value(module.params['value'],
  611. module.params['value_type'])
  612. key = module.params['key']
  613. if module.params['update']:
  614. # pylint: disable=line-too-long
  615. curr_value = Yedit.get_curr_value(Yedit.parse_value(module.params['curr_value']), # noqa: E501
  616. module.params['curr_value_format']) # noqa: E501
  617. rval = yamlfile.update(key, value, module.params['index'], curr_value) # noqa: E501
  618. elif module.params['append']:
  619. rval = yamlfile.append(key, value)
  620. else:
  621. rval = yamlfile.put(key, value)
  622. if rval[0] and module.params['src']:
  623. yamlfile.write()
  624. return {'changed': rval[0],
  625. 'result': rval[1], 'state': "present"}
  626. # no edits to make
  627. if module.params['src']:
  628. # pylint: disable=redefined-variable-type
  629. rval = yamlfile.write()
  630. return {'changed': rval[0],
  631. 'result': rval[1],
  632. 'state': "present"}
  633. return {'failed': True, 'msg': 'Unkown state passed'}
  634. # -*- -*- -*- End included fragment: class/yedit.py -*- -*- -*-
  635. # -*- -*- -*- Begin included fragment: ansible/yedit.py -*- -*- -*-
  636. # pylint: disable=too-many-branches
  637. def main():
  638. ''' ansible oc module for secrets '''
  639. module = AnsibleModule(
  640. argument_spec=dict(
  641. state=dict(default='present', type='str',
  642. choices=['present', 'absent', 'list']),
  643. debug=dict(default=False, type='bool'),
  644. src=dict(default=None, type='str'),
  645. content=dict(default=None),
  646. content_type=dict(default='dict', choices=['dict']),
  647. key=dict(default='', type='str'),
  648. value=dict(),
  649. value_type=dict(default='', type='str'),
  650. update=dict(default=False, type='bool'),
  651. append=dict(default=False, type='bool'),
  652. index=dict(default=None, type='int'),
  653. curr_value=dict(default=None, type='str'),
  654. curr_value_format=dict(default='yaml',
  655. choices=['yaml', 'json', 'str'],
  656. type='str'),
  657. backup=dict(default=True, type='bool'),
  658. separator=dict(default='.', type='str'),
  659. ),
  660. mutually_exclusive=[["curr_value", "index"], ['update', "append"]],
  661. required_one_of=[["content", "src"]],
  662. )
  663. rval = Yedit.run_ansible(module)
  664. if 'failed' in rval and rval['failed']:
  665. module.fail_json(**rval)
  666. module.exit_json(**rval)
  667. if __name__ == '__main__':
  668. main()
  669. # -*- -*- -*- End included fragment: ansible/yedit.py -*- -*- -*-