yedit.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  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. # pylint: disable=wrong-import-order
  27. import json
  28. import os
  29. import re
  30. # pylint: disable=import-error
  31. import ruamel.yaml as yaml
  32. import shutil
  33. from ansible.module_utils.basic import AnsibleModule
  34. DOCUMENTATION = '''
  35. ---
  36. module: yedit
  37. short_description: Create, modify, and idempotently manage yaml files.
  38. description:
  39. - Modify yaml files programmatically.
  40. options:
  41. state:
  42. description:
  43. - State represents whether to create, modify, delete, or list yaml
  44. required: true
  45. default: present
  46. choices: ["present", "absent", "list"]
  47. aliases: []
  48. debug:
  49. description:
  50. - Turn on debug information.
  51. required: false
  52. default: false
  53. aliases: []
  54. src:
  55. description:
  56. - The file that is the target of the modifications.
  57. required: false
  58. default: None
  59. aliases: []
  60. content:
  61. description:
  62. - Content represents the yaml content you desire to work with. This
  63. - could be the file contents to write or the inmemory data to modify.
  64. required: false
  65. default: None
  66. aliases: []
  67. content_type:
  68. description:
  69. - The python type of the content parameter.
  70. required: false
  71. default: 'dict'
  72. aliases: []
  73. key:
  74. description:
  75. - The path to the value you wish to modify. Emtpy string means the top of
  76. - the document.
  77. required: false
  78. default: ''
  79. aliases: []
  80. value:
  81. description:
  82. - The incoming value of parameter 'key'.
  83. required: false
  84. default:
  85. aliases: []
  86. value_type:
  87. description:
  88. - The python type of the incoming value.
  89. required: false
  90. default: ''
  91. aliases: []
  92. update:
  93. description:
  94. - Whether the update should be performed on a dict/hash or list/array
  95. - object.
  96. required: false
  97. default: false
  98. aliases: []
  99. append:
  100. description:
  101. - Whether to append to an array/list. When the key does not exist or is
  102. - null, a new array is created. When the key is of a non-list type,
  103. - nothing is done.
  104. required: false
  105. default: false
  106. aliases: []
  107. index:
  108. description:
  109. - Used in conjunction with the update parameter. This will update a
  110. - specific index in an array/list.
  111. required: false
  112. default: false
  113. aliases: []
  114. curr_value:
  115. description:
  116. - Used in conjunction with the update parameter. This is the current
  117. - value of 'key' in the yaml file.
  118. required: false
  119. default: false
  120. aliases: []
  121. curr_value_format:
  122. description:
  123. - Format of the incoming current value.
  124. choices: ["yaml", "json", "str"]
  125. required: false
  126. default: false
  127. aliases: []
  128. backup:
  129. description:
  130. - Whether to make a backup copy of the current file when performing an
  131. - edit.
  132. required: false
  133. default: true
  134. aliases: []
  135. author:
  136. - "Kenny Woodson <kwoodson@redhat.com>"
  137. extends_documentation_fragment: []
  138. '''
  139. EXAMPLES = '''
  140. # Simple insert of key, value
  141. - name: insert simple key, value
  142. yedit:
  143. src: somefile.yml
  144. key: test
  145. value: somevalue
  146. state: present
  147. # Results:
  148. # test: somevalue
  149. # Multilevel insert of key, value
  150. - name: insert simple key, value
  151. yedit:
  152. src: somefile.yml
  153. key: a#b#c
  154. value: d
  155. state: present
  156. # Results:
  157. # a:
  158. # b:
  159. # c: d
  160. '''
  161. class YeditException(Exception):
  162. ''' Exception class for Yedit '''
  163. pass
  164. class Yedit(object):
  165. ''' Class to modify yaml files '''
  166. re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
  167. re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z%s/_-]+)"
  168. com_sep = set(['.', '#', '|', ':'])
  169. # pylint: disable=too-many-arguments
  170. def __init__(self,
  171. filename=None,
  172. content=None,
  173. content_type='yaml',
  174. separator='.',
  175. backup=False):
  176. self.content = content
  177. self._separator = separator
  178. self.filename = filename
  179. self.__yaml_dict = content
  180. self.content_type = content_type
  181. self.backup = backup
  182. self.load(content_type=self.content_type)
  183. if self.__yaml_dict is None:
  184. self.__yaml_dict = {}
  185. @property
  186. def separator(self):
  187. ''' getter method for yaml_dict '''
  188. return self._separator
  189. @separator.setter
  190. def separator(self):
  191. ''' getter method for yaml_dict '''
  192. return self._separator
  193. @property
  194. def yaml_dict(self):
  195. ''' getter method for yaml_dict '''
  196. return self.__yaml_dict
  197. @yaml_dict.setter
  198. def yaml_dict(self, value):
  199. ''' setter method for yaml_dict '''
  200. self.__yaml_dict = value
  201. @staticmethod
  202. def parse_key(key, sep='.'):
  203. '''parse the key allowing the appropriate separator'''
  204. common_separators = list(Yedit.com_sep - set([sep]))
  205. return re.findall(Yedit.re_key % ''.join(common_separators), key)
  206. @staticmethod
  207. def valid_key(key, sep='.'):
  208. '''validate the incoming key'''
  209. common_separators = list(Yedit.com_sep - set([sep]))
  210. if not re.match(Yedit.re_valid_key % ''.join(common_separators), key):
  211. return False
  212. return True
  213. @staticmethod
  214. def remove_entry(data, key, sep='.'):
  215. ''' remove data at location key '''
  216. if key == '' and isinstance(data, dict):
  217. data.clear()
  218. return True
  219. elif key == '' and isinstance(data, list):
  220. del data[:]
  221. return True
  222. if not (key and Yedit.valid_key(key, sep)) and \
  223. isinstance(data, (list, dict)):
  224. return None
  225. key_indexes = Yedit.parse_key(key, sep)
  226. for arr_ind, dict_key in key_indexes[:-1]:
  227. if dict_key and isinstance(data, dict):
  228. data = data.get(dict_key, None)
  229. elif (arr_ind and isinstance(data, list) and
  230. int(arr_ind) <= len(data) - 1):
  231. data = data[int(arr_ind)]
  232. else:
  233. return None
  234. # process last index for remove
  235. # expected list entry
  236. if key_indexes[-1][0]:
  237. if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  238. del data[int(key_indexes[-1][0])]
  239. return True
  240. # expected dict entry
  241. elif key_indexes[-1][1]:
  242. if isinstance(data, dict):
  243. del data[key_indexes[-1][1]]
  244. return True
  245. @staticmethod
  246. def add_entry(data, key, item=None, sep='.'):
  247. ''' Get an item from a dictionary with key notation a.b.c
  248. d = {'a': {'b': 'c'}}}
  249. key = a#b
  250. return c
  251. '''
  252. if key == '':
  253. pass
  254. elif (not (key and Yedit.valid_key(key, sep)) and
  255. isinstance(data, (list, dict))):
  256. return None
  257. key_indexes = Yedit.parse_key(key, sep)
  258. for arr_ind, dict_key in key_indexes[:-1]:
  259. if dict_key:
  260. if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
  261. data = data[dict_key]
  262. continue
  263. elif data and not isinstance(data, dict):
  264. return None
  265. data[dict_key] = {}
  266. data = data[dict_key]
  267. elif (arr_ind and isinstance(data, list) and
  268. int(arr_ind) <= len(data) - 1):
  269. data = data[int(arr_ind)]
  270. else:
  271. return None
  272. if key == '':
  273. data = item
  274. # process last index for add
  275. # expected list entry
  276. elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  277. data[int(key_indexes[-1][0])] = item
  278. # expected dict entry
  279. elif key_indexes[-1][1] and isinstance(data, dict):
  280. data[key_indexes[-1][1]] = item
  281. return data
  282. @staticmethod
  283. def get_entry(data, key, sep='.'):
  284. ''' Get an item from a dictionary with key notation a.b.c
  285. d = {'a': {'b': 'c'}}}
  286. key = a.b
  287. return c
  288. '''
  289. if key == '':
  290. pass
  291. elif (not (key and Yedit.valid_key(key, sep)) and
  292. isinstance(data, (list, dict))):
  293. return None
  294. key_indexes = Yedit.parse_key(key, sep)
  295. for arr_ind, dict_key in key_indexes:
  296. if dict_key and isinstance(data, dict):
  297. data = data.get(dict_key, None)
  298. elif (arr_ind and isinstance(data, list) and
  299. int(arr_ind) <= len(data) - 1):
  300. data = data[int(arr_ind)]
  301. else:
  302. return None
  303. return data
  304. def write(self):
  305. ''' write to file '''
  306. if not self.filename:
  307. raise YeditException('Please specify a filename.')
  308. if self.backup and self.file_exists():
  309. shutil.copy(self.filename, self.filename + '.orig')
  310. tmp_filename = self.filename + '.yedit'
  311. with open(tmp_filename, 'w') as yfd:
  312. # pylint: disable=no-member
  313. if hasattr(self.yaml_dict, 'fa'):
  314. self.yaml_dict.fa.set_block_style()
  315. yfd.write(yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
  316. os.rename(tmp_filename, self.filename)
  317. return (True, self.yaml_dict)
  318. def read(self):
  319. ''' read from file '''
  320. # check if it exists
  321. if self.filename is None or not self.file_exists():
  322. return None
  323. contents = None
  324. with open(self.filename) as yfd:
  325. contents = yfd.read()
  326. return contents
  327. def file_exists(self):
  328. ''' return whether file exists '''
  329. if os.path.exists(self.filename):
  330. return True
  331. return False
  332. def load(self, content_type='yaml'):
  333. ''' return yaml file '''
  334. contents = self.read()
  335. if not contents and not self.content:
  336. return None
  337. if self.content:
  338. if isinstance(self.content, dict):
  339. self.yaml_dict = self.content
  340. return self.yaml_dict
  341. elif isinstance(self.content, str):
  342. contents = self.content
  343. # check if it is yaml
  344. try:
  345. if content_type == 'yaml' and contents:
  346. self.yaml_dict = yaml.load(contents, yaml.RoundTripLoader)
  347. # pylint: disable=no-member
  348. if hasattr(self.yaml_dict, 'fa'):
  349. self.yaml_dict.fa.set_block_style()
  350. elif content_type == 'json' and contents:
  351. self.yaml_dict = json.loads(contents)
  352. except yaml.YAMLError as err:
  353. # Error loading yaml or json
  354. raise YeditException('Problem with loading yaml file. %s' % err)
  355. return self.yaml_dict
  356. def get(self, key):
  357. ''' get a specified key'''
  358. try:
  359. entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
  360. except KeyError:
  361. entry = None
  362. return entry
  363. def pop(self, path, key_or_item):
  364. ''' remove a key, value pair from a dict or an item for a list'''
  365. try:
  366. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  367. except KeyError:
  368. entry = None
  369. if entry is None:
  370. return (False, self.yaml_dict)
  371. if isinstance(entry, dict):
  372. # pylint: disable=no-member,maybe-no-member
  373. if key_or_item in entry:
  374. entry.pop(key_or_item)
  375. return (True, self.yaml_dict)
  376. return (False, self.yaml_dict)
  377. elif isinstance(entry, list):
  378. # pylint: disable=no-member,maybe-no-member
  379. ind = None
  380. try:
  381. ind = entry.index(key_or_item)
  382. except ValueError:
  383. return (False, self.yaml_dict)
  384. entry.pop(ind)
  385. return (True, self.yaml_dict)
  386. return (False, self.yaml_dict)
  387. def delete(self, path):
  388. ''' remove path from a dict'''
  389. try:
  390. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  391. except KeyError:
  392. entry = None
  393. if entry is None:
  394. return (False, self.yaml_dict)
  395. result = Yedit.remove_entry(self.yaml_dict, path, self.separator)
  396. if not result:
  397. return (False, self.yaml_dict)
  398. return (True, self.yaml_dict)
  399. def exists(self, path, value):
  400. ''' check if value exists at path'''
  401. try:
  402. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  403. except KeyError:
  404. entry = None
  405. if isinstance(entry, list):
  406. if value in entry:
  407. return True
  408. return False
  409. elif isinstance(entry, dict):
  410. if isinstance(value, dict):
  411. rval = False
  412. for key, val in value.items():
  413. if entry[key] != val:
  414. rval = False
  415. break
  416. else:
  417. rval = True
  418. return rval
  419. return value in entry
  420. return entry == value
  421. def append(self, path, value):
  422. '''append value to a list'''
  423. try:
  424. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  425. except KeyError:
  426. entry = None
  427. if entry is None:
  428. self.put(path, [])
  429. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  430. if not isinstance(entry, list):
  431. return (False, self.yaml_dict)
  432. # pylint: disable=no-member,maybe-no-member
  433. entry.append(value)
  434. return (True, self.yaml_dict)
  435. # pylint: disable=too-many-arguments
  436. def update(self, path, value, index=None, curr_value=None):
  437. ''' put path, value into a dict '''
  438. try:
  439. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  440. except KeyError:
  441. entry = None
  442. if isinstance(entry, dict):
  443. # pylint: disable=no-member,maybe-no-member
  444. if not isinstance(value, dict):
  445. raise YeditException('Cannot replace key, value entry in ' +
  446. 'dict with non-dict type. value=[%s] [%s]' % (value, type(value))) # noqa: E501
  447. entry.update(value)
  448. return (True, self.yaml_dict)
  449. elif isinstance(entry, list):
  450. # pylint: disable=no-member,maybe-no-member
  451. ind = None
  452. if curr_value:
  453. try:
  454. ind = entry.index(curr_value)
  455. except ValueError:
  456. return (False, self.yaml_dict)
  457. elif index is not None:
  458. ind = index
  459. if ind is not None and entry[ind] != value:
  460. entry[ind] = value
  461. return (True, self.yaml_dict)
  462. # see if it exists in the list
  463. try:
  464. ind = entry.index(value)
  465. except ValueError:
  466. # doesn't exist, append it
  467. entry.append(value)
  468. return (True, self.yaml_dict)
  469. # already exists, return
  470. if ind is not None:
  471. return (False, self.yaml_dict)
  472. return (False, self.yaml_dict)
  473. def put(self, path, value):
  474. ''' put path, value into a dict '''
  475. try:
  476. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  477. except KeyError:
  478. entry = None
  479. if entry == value:
  480. return (False, self.yaml_dict)
  481. # deepcopy didn't work
  482. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  483. default_flow_style=False),
  484. yaml.RoundTripLoader)
  485. # pylint: disable=no-member
  486. if hasattr(self.yaml_dict, 'fa'):
  487. tmp_copy.fa.set_block_style()
  488. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  489. if not result:
  490. return (False, self.yaml_dict)
  491. self.yaml_dict = tmp_copy
  492. return (True, self.yaml_dict)
  493. def create(self, path, value):
  494. ''' create a yaml file '''
  495. if not self.file_exists():
  496. # deepcopy didn't work
  497. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict, default_flow_style=False), # noqa: E501
  498. yaml.RoundTripLoader)
  499. # pylint: disable=no-member
  500. if hasattr(self.yaml_dict, 'fa'):
  501. tmp_copy.fa.set_block_style()
  502. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  503. if result:
  504. self.yaml_dict = tmp_copy
  505. return (True, self.yaml_dict)
  506. return (False, self.yaml_dict)
  507. # pylint: disable=too-many-return-statements,too-many-branches
  508. @staticmethod
  509. def run_ansible(module):
  510. '''perform the idempotent crud operations'''
  511. yamlfile = Yedit(filename=module.params['src'],
  512. backup=module.params['backup'],
  513. separator=module.params['separator'])
  514. if module.params['src']:
  515. rval = yamlfile.load()
  516. if yamlfile.yaml_dict is None and \
  517. module.params['state'] != 'present':
  518. return {'failed': True,
  519. 'msg': 'Error opening file [%s]. Verify that the ' +
  520. 'file exists, that it is has correct' +
  521. ' permissions, and is valid yaml.'}
  522. if module.params['state'] == 'list':
  523. if module.params['content']:
  524. content = parse_value(module.params['content'],
  525. module.params['content_type'])
  526. yamlfile.yaml_dict = content
  527. if module.params['key']:
  528. rval = yamlfile.get(module.params['key']) or {}
  529. return {'changed': False, 'result': rval, 'state': "list"}
  530. elif module.params['state'] == 'absent':
  531. if module.params['content']:
  532. content = parse_value(module.params['content'],
  533. module.params['content_type'])
  534. yamlfile.yaml_dict = content
  535. if module.params['update']:
  536. rval = yamlfile.pop(module.params['key'],
  537. module.params['value'])
  538. else:
  539. rval = yamlfile.delete(module.params['key'])
  540. if rval[0] and module.params['src']:
  541. yamlfile.write()
  542. return {'changed': rval[0], 'result': rval[1], 'state': "absent"}
  543. elif module.params['state'] == 'present':
  544. # check if content is different than what is in the file
  545. if module.params['content']:
  546. content = parse_value(module.params['content'],
  547. module.params['content_type'])
  548. # We had no edits to make and the contents are the same
  549. if yamlfile.yaml_dict == content and \
  550. module.params['value'] is None:
  551. return {'changed': False,
  552. 'result': yamlfile.yaml_dict,
  553. 'state': "present"}
  554. yamlfile.yaml_dict = content
  555. # we were passed a value; parse it
  556. if module.params['value']:
  557. value = parse_value(module.params['value'],
  558. module.params['value_type'])
  559. key = module.params['key']
  560. if module.params['update']:
  561. # pylint: disable=line-too-long
  562. curr_value = get_curr_value(parse_value(module.params['curr_value']), module.params['curr_value_format']) # noqa: #501
  563. rval = yamlfile.update(key, value, module.params['index'], curr_value) # noqa: E501
  564. elif module.params['append']:
  565. rval = yamlfile.append(key, value)
  566. else:
  567. rval = yamlfile.put(key, value)
  568. if rval[0] and module.params['src']:
  569. yamlfile.write()
  570. return {'changed': rval[0],
  571. 'result': rval[1], 'state': "present"}
  572. # no edits to make
  573. if module.params['src']:
  574. # pylint: disable=redefined-variable-type
  575. rval = yamlfile.write()
  576. return {'changed': rval[0],
  577. 'result': rval[1],
  578. 'state': "present"}
  579. return {'failed': True, 'msg': 'Unkown state passed'}
  580. def get_curr_value(invalue, val_type):
  581. '''return the current value'''
  582. if invalue is None:
  583. return None
  584. curr_value = invalue
  585. if val_type == 'yaml':
  586. curr_value = yaml.load(invalue)
  587. elif val_type == 'json':
  588. curr_value = json.loads(invalue)
  589. return curr_value
  590. def parse_value(inc_value, vtype=''):
  591. '''determine value type passed'''
  592. true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE',
  593. 'on', 'On', 'ON', ]
  594. false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE',
  595. 'off', 'Off', 'OFF']
  596. # It came in as a string but you didn't specify value_type as string
  597. # we will convert to bool if it matches any of the above cases
  598. if isinstance(inc_value, str) and 'bool' in vtype:
  599. if inc_value not in true_bools and inc_value not in false_bools:
  600. raise YeditException('Not a boolean type. str=[%s] vtype=[%s]'
  601. % (inc_value, vtype))
  602. elif isinstance(inc_value, bool) and 'str' in vtype:
  603. inc_value = str(inc_value)
  604. # If vtype is not str then go ahead and attempt to yaml load it.
  605. if isinstance(inc_value, str) and 'str' not in vtype:
  606. try:
  607. inc_value = yaml.load(inc_value)
  608. except Exception:
  609. raise YeditException('Could not determine type of incoming ' +
  610. 'value. value=[%s] vtype=[%s]'
  611. % (type(inc_value), vtype))
  612. return inc_value
  613. # pylint: disable=too-many-branches
  614. def main():
  615. ''' ansible oc module for secrets '''
  616. module = AnsibleModule(
  617. argument_spec=dict(
  618. state=dict(default='present', type='str',
  619. choices=['present', 'absent', 'list']),
  620. debug=dict(default=False, type='bool'),
  621. src=dict(default=None, type='str'),
  622. content=dict(default=None),
  623. content_type=dict(default='dict', choices=['dict']),
  624. key=dict(default='', type='str'),
  625. value=dict(),
  626. value_type=dict(default='', type='str'),
  627. update=dict(default=False, type='bool'),
  628. append=dict(default=False, type='bool'),
  629. index=dict(default=None, type='int'),
  630. curr_value=dict(default=None, type='str'),
  631. curr_value_format=dict(default='yaml',
  632. choices=['yaml', 'json', 'str'],
  633. type='str'),
  634. backup=dict(default=True, type='bool'),
  635. separator=dict(default='.', type='str'),
  636. ),
  637. mutually_exclusive=[["curr_value", "index"], ['update', "append"]],
  638. required_one_of=[["content", "src"]],
  639. )
  640. rval = Yedit.run_ansible(module)
  641. if 'failed' in rval and rval['failed']:
  642. module.fail_json(msg=rval['msg'])
  643. module.exit_json(**rval)
  644. if __name__ == '__main__':
  645. main()