yedit.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  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. # noqa: E301,E302
  162. class YeditException(Exception):
  163. ''' Exception class for Yedit '''
  164. pass
  165. # pylint: disable=too-many-public-methods
  166. class Yedit(object):
  167. ''' Class to modify yaml files '''
  168. re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
  169. re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z%s/_-]+)"
  170. com_sep = set(['.', '#', '|', ':'])
  171. # pylint: disable=too-many-arguments
  172. def __init__(self,
  173. filename=None,
  174. content=None,
  175. content_type='yaml',
  176. separator='.',
  177. backup=False):
  178. self.content = content
  179. self._separator = separator
  180. self.filename = filename
  181. self.__yaml_dict = content
  182. self.content_type = content_type
  183. self.backup = backup
  184. self.load(content_type=self.content_type)
  185. if self.__yaml_dict is None:
  186. self.__yaml_dict = {}
  187. @property
  188. def separator(self):
  189. ''' getter method for yaml_dict '''
  190. return self._separator
  191. @separator.setter
  192. def separator(self):
  193. ''' getter method for yaml_dict '''
  194. return self._separator
  195. @property
  196. def yaml_dict(self):
  197. ''' getter method for yaml_dict '''
  198. return self.__yaml_dict
  199. @yaml_dict.setter
  200. def yaml_dict(self, value):
  201. ''' setter method for yaml_dict '''
  202. self.__yaml_dict = value
  203. @staticmethod
  204. def parse_key(key, sep='.'):
  205. '''parse the key allowing the appropriate separator'''
  206. common_separators = list(Yedit.com_sep - set([sep]))
  207. return re.findall(Yedit.re_key % ''.join(common_separators), key)
  208. @staticmethod
  209. def valid_key(key, sep='.'):
  210. '''validate the incoming key'''
  211. common_separators = list(Yedit.com_sep - set([sep]))
  212. if not re.match(Yedit.re_valid_key % ''.join(common_separators), key):
  213. return False
  214. return True
  215. @staticmethod
  216. def remove_entry(data, key, sep='.'):
  217. ''' remove data at location key '''
  218. if key == '' and isinstance(data, dict):
  219. data.clear()
  220. return True
  221. elif key == '' and isinstance(data, list):
  222. del data[:]
  223. return True
  224. if not (key and Yedit.valid_key(key, sep)) and \
  225. isinstance(data, (list, dict)):
  226. return None
  227. key_indexes = Yedit.parse_key(key, sep)
  228. for arr_ind, dict_key in key_indexes[:-1]:
  229. if dict_key and isinstance(data, dict):
  230. data = data.get(dict_key, None)
  231. elif (arr_ind and isinstance(data, list) and
  232. int(arr_ind) <= len(data) - 1):
  233. data = data[int(arr_ind)]
  234. else:
  235. return None
  236. # process last index for remove
  237. # expected list entry
  238. if key_indexes[-1][0]:
  239. if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  240. del data[int(key_indexes[-1][0])]
  241. return True
  242. # expected dict entry
  243. elif key_indexes[-1][1]:
  244. if isinstance(data, dict):
  245. del data[key_indexes[-1][1]]
  246. return True
  247. @staticmethod
  248. def add_entry(data, key, item=None, sep='.'):
  249. ''' Get an item from a dictionary with key notation a.b.c
  250. d = {'a': {'b': 'c'}}}
  251. key = a#b
  252. return c
  253. '''
  254. if key == '':
  255. pass
  256. elif (not (key and Yedit.valid_key(key, sep)) and
  257. isinstance(data, (list, dict))):
  258. return None
  259. key_indexes = Yedit.parse_key(key, sep)
  260. for arr_ind, dict_key in key_indexes[:-1]:
  261. if dict_key:
  262. if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
  263. data = data[dict_key]
  264. continue
  265. elif data and not isinstance(data, dict):
  266. return None
  267. data[dict_key] = {}
  268. data = data[dict_key]
  269. elif (arr_ind and isinstance(data, list) and
  270. int(arr_ind) <= len(data) - 1):
  271. data = data[int(arr_ind)]
  272. else:
  273. return None
  274. if key == '':
  275. data = item
  276. # process last index for add
  277. # expected list entry
  278. elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  279. data[int(key_indexes[-1][0])] = item
  280. # expected dict entry
  281. elif key_indexes[-1][1] and isinstance(data, dict):
  282. data[key_indexes[-1][1]] = item
  283. return data
  284. @staticmethod
  285. def get_entry(data, key, sep='.'):
  286. ''' Get an item from a dictionary with key notation a.b.c
  287. d = {'a': {'b': 'c'}}}
  288. key = a.b
  289. return c
  290. '''
  291. if key == '':
  292. pass
  293. elif (not (key and Yedit.valid_key(key, sep)) and
  294. isinstance(data, (list, dict))):
  295. return None
  296. key_indexes = Yedit.parse_key(key, sep)
  297. for arr_ind, dict_key in key_indexes:
  298. if dict_key and isinstance(data, dict):
  299. data = data.get(dict_key, None)
  300. elif (arr_ind and isinstance(data, list) and
  301. int(arr_ind) <= len(data) - 1):
  302. data = data[int(arr_ind)]
  303. else:
  304. return None
  305. return data
  306. def write(self):
  307. ''' write to file '''
  308. if not self.filename:
  309. raise YeditException('Please specify a filename.')
  310. if self.backup and self.file_exists():
  311. shutil.copy(self.filename, self.filename + '.orig')
  312. tmp_filename = self.filename + '.yedit'
  313. with open(tmp_filename, 'w') as yfd:
  314. # pylint: disable=no-member
  315. if hasattr(self.yaml_dict, 'fa'):
  316. self.yaml_dict.fa.set_block_style()
  317. yfd.write(yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
  318. os.rename(tmp_filename, self.filename)
  319. return (True, self.yaml_dict)
  320. def read(self):
  321. ''' read from file '''
  322. # check if it exists
  323. if self.filename is None or not self.file_exists():
  324. return None
  325. contents = None
  326. with open(self.filename) as yfd:
  327. contents = yfd.read()
  328. return contents
  329. def file_exists(self):
  330. ''' return whether file exists '''
  331. if os.path.exists(self.filename):
  332. return True
  333. return False
  334. def load(self, content_type='yaml'):
  335. ''' return yaml file '''
  336. contents = self.read()
  337. if not contents and not self.content:
  338. return None
  339. if self.content:
  340. if isinstance(self.content, dict):
  341. self.yaml_dict = self.content
  342. return self.yaml_dict
  343. elif isinstance(self.content, str):
  344. contents = self.content
  345. # check if it is yaml
  346. try:
  347. if content_type == 'yaml' and contents:
  348. self.yaml_dict = yaml.load(contents, yaml.RoundTripLoader)
  349. # pylint: disable=no-member
  350. if hasattr(self.yaml_dict, 'fa'):
  351. self.yaml_dict.fa.set_block_style()
  352. elif content_type == 'json' and contents:
  353. self.yaml_dict = json.loads(contents)
  354. except yaml.YAMLError as err:
  355. # Error loading yaml or json
  356. raise YeditException('Problem with loading yaml file. %s' % err)
  357. return self.yaml_dict
  358. def get(self, key):
  359. ''' get a specified key'''
  360. try:
  361. entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
  362. except KeyError:
  363. entry = None
  364. return entry
  365. def pop(self, path, key_or_item):
  366. ''' remove a key, value pair from a dict or an item for a list'''
  367. try:
  368. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  369. except KeyError:
  370. entry = None
  371. if entry is None:
  372. return (False, self.yaml_dict)
  373. if isinstance(entry, dict):
  374. # pylint: disable=no-member,maybe-no-member
  375. if key_or_item in entry:
  376. entry.pop(key_or_item)
  377. return (True, self.yaml_dict)
  378. return (False, self.yaml_dict)
  379. elif isinstance(entry, list):
  380. # pylint: disable=no-member,maybe-no-member
  381. ind = None
  382. try:
  383. ind = entry.index(key_or_item)
  384. except ValueError:
  385. return (False, self.yaml_dict)
  386. entry.pop(ind)
  387. return (True, self.yaml_dict)
  388. return (False, self.yaml_dict)
  389. def delete(self, path):
  390. ''' remove path from a dict'''
  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. result = Yedit.remove_entry(self.yaml_dict, path, self.separator)
  398. if not result:
  399. return (False, self.yaml_dict)
  400. return (True, self.yaml_dict)
  401. def exists(self, path, value):
  402. ''' check if value exists at path'''
  403. try:
  404. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  405. except KeyError:
  406. entry = None
  407. if isinstance(entry, list):
  408. if value in entry:
  409. return True
  410. return False
  411. elif isinstance(entry, dict):
  412. if isinstance(value, dict):
  413. rval = False
  414. for key, val in value.items():
  415. if entry[key] != val:
  416. rval = False
  417. break
  418. else:
  419. rval = True
  420. return rval
  421. return value in entry
  422. return entry == value
  423. def append(self, path, value):
  424. '''append value to a list'''
  425. try:
  426. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  427. except KeyError:
  428. entry = None
  429. if entry is None:
  430. self.put(path, [])
  431. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  432. if not isinstance(entry, list):
  433. return (False, self.yaml_dict)
  434. # pylint: disable=no-member,maybe-no-member
  435. entry.append(value)
  436. return (True, self.yaml_dict)
  437. # pylint: disable=too-many-arguments
  438. def update(self, path, value, index=None, curr_value=None):
  439. ''' put path, value into a dict '''
  440. try:
  441. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  442. except KeyError:
  443. entry = None
  444. if isinstance(entry, dict):
  445. # pylint: disable=no-member,maybe-no-member
  446. if not isinstance(value, dict):
  447. raise YeditException('Cannot replace key, value entry in ' +
  448. 'dict with non-dict type. value=[%s] [%s]' % (value, type(value))) # noqa: E501
  449. entry.update(value)
  450. return (True, self.yaml_dict)
  451. elif isinstance(entry, list):
  452. # pylint: disable=no-member,maybe-no-member
  453. ind = None
  454. if curr_value:
  455. try:
  456. ind = entry.index(curr_value)
  457. except ValueError:
  458. return (False, self.yaml_dict)
  459. elif index is not None:
  460. ind = index
  461. if ind is not None and entry[ind] != value:
  462. entry[ind] = value
  463. return (True, self.yaml_dict)
  464. # see if it exists in the list
  465. try:
  466. ind = entry.index(value)
  467. except ValueError:
  468. # doesn't exist, append it
  469. entry.append(value)
  470. return (True, self.yaml_dict)
  471. # already exists, return
  472. if ind is not None:
  473. return (False, self.yaml_dict)
  474. return (False, self.yaml_dict)
  475. def put(self, path, value):
  476. ''' put path, value into a dict '''
  477. try:
  478. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  479. except KeyError:
  480. entry = None
  481. if entry == value:
  482. return (False, self.yaml_dict)
  483. # deepcopy didn't work
  484. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  485. default_flow_style=False),
  486. yaml.RoundTripLoader)
  487. # pylint: disable=no-member
  488. if hasattr(self.yaml_dict, 'fa'):
  489. tmp_copy.fa.set_block_style()
  490. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  491. if not result:
  492. return (False, self.yaml_dict)
  493. self.yaml_dict = tmp_copy
  494. return (True, self.yaml_dict)
  495. def create(self, path, value):
  496. ''' create a yaml file '''
  497. if not self.file_exists():
  498. # deepcopy didn't work
  499. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict, default_flow_style=False), # noqa: E501
  500. yaml.RoundTripLoader)
  501. # pylint: disable=no-member
  502. if hasattr(self.yaml_dict, 'fa'):
  503. tmp_copy.fa.set_block_style()
  504. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  505. if result:
  506. self.yaml_dict = tmp_copy
  507. return (True, self.yaml_dict)
  508. return (False, self.yaml_dict)
  509. @staticmethod
  510. def get_curr_value(invalue, val_type):
  511. '''return the current value'''
  512. if invalue is None:
  513. return None
  514. curr_value = invalue
  515. if val_type == 'yaml':
  516. curr_value = yaml.load(invalue)
  517. elif val_type == 'json':
  518. curr_value = json.loads(invalue)
  519. return curr_value
  520. @staticmethod
  521. def parse_value(inc_value, vtype=''):
  522. '''determine value type passed'''
  523. true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE',
  524. 'on', 'On', 'ON', ]
  525. false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE',
  526. 'off', 'Off', 'OFF']
  527. # It came in as a string but you didn't specify value_type as string
  528. # we will convert to bool if it matches any of the above cases
  529. if isinstance(inc_value, str) and 'bool' in vtype:
  530. if inc_value not in true_bools and inc_value not in false_bools:
  531. raise YeditException('Not a boolean type. str=[%s] vtype=[%s]'
  532. % (inc_value, vtype))
  533. elif isinstance(inc_value, bool) and 'str' in vtype:
  534. inc_value = str(inc_value)
  535. # If vtype is not str then go ahead and attempt to yaml load it.
  536. if isinstance(inc_value, str) and 'str' not in vtype:
  537. try:
  538. inc_value = yaml.load(inc_value)
  539. except Exception:
  540. raise YeditException('Could not determine type of incoming ' +
  541. 'value. value=[%s] vtype=[%s]'
  542. % (type(inc_value), vtype))
  543. return inc_value
  544. # pylint: disable=too-many-return-statements,too-many-branches
  545. @staticmethod
  546. def run_ansible(module):
  547. '''perform the idempotent crud operations'''
  548. yamlfile = Yedit(filename=module.params['src'],
  549. backup=module.params['backup'],
  550. separator=module.params['separator'])
  551. if module.params['src']:
  552. rval = yamlfile.load()
  553. if yamlfile.yaml_dict is None and \
  554. module.params['state'] != 'present':
  555. return {'failed': True,
  556. 'msg': 'Error opening file [%s]. Verify that the ' +
  557. 'file exists, that it is has correct' +
  558. ' permissions, and is valid yaml.'}
  559. if module.params['state'] == 'list':
  560. if module.params['content']:
  561. content = Yedit.parse_value(module.params['content'],
  562. module.params['content_type'])
  563. yamlfile.yaml_dict = content
  564. if module.params['key']:
  565. rval = yamlfile.get(module.params['key']) or {}
  566. return {'changed': False, 'result': rval, 'state': "list"}
  567. elif module.params['state'] == 'absent':
  568. if module.params['content']:
  569. content = Yedit.parse_value(module.params['content'],
  570. module.params['content_type'])
  571. yamlfile.yaml_dict = content
  572. if module.params['update']:
  573. rval = yamlfile.pop(module.params['key'],
  574. module.params['value'])
  575. else:
  576. rval = yamlfile.delete(module.params['key'])
  577. if rval[0] and module.params['src']:
  578. yamlfile.write()
  579. return {'changed': rval[0], 'result': rval[1], 'state': "absent"}
  580. elif module.params['state'] == 'present':
  581. # check if content is different than what is in the file
  582. if module.params['content']:
  583. content = Yedit.parse_value(module.params['content'],
  584. module.params['content_type'])
  585. # We had no edits to make and the contents are the same
  586. if yamlfile.yaml_dict == content and \
  587. module.params['value'] is None:
  588. return {'changed': False,
  589. 'result': yamlfile.yaml_dict,
  590. 'state': "present"}
  591. yamlfile.yaml_dict = content
  592. # we were passed a value; parse it
  593. if module.params['value']:
  594. value = Yedit.parse_value(module.params['value'],
  595. module.params['value_type'])
  596. key = module.params['key']
  597. if module.params['update']:
  598. # pylint: disable=line-too-long
  599. curr_value = Yedit.get_curr_value(Yedit.parse_value(module.params['curr_value']), # noqa: E501
  600. module.params['curr_value_format']) # noqa: E501
  601. rval = yamlfile.update(key, value, module.params['index'], curr_value) # noqa: E501
  602. elif module.params['append']:
  603. rval = yamlfile.append(key, value)
  604. else:
  605. rval = yamlfile.put(key, value)
  606. if rval[0] and module.params['src']:
  607. yamlfile.write()
  608. return {'changed': rval[0],
  609. 'result': rval[1], 'state': "present"}
  610. # no edits to make
  611. if module.params['src']:
  612. # pylint: disable=redefined-variable-type
  613. rval = yamlfile.write()
  614. return {'changed': rval[0],
  615. 'result': rval[1],
  616. 'state': "present"}
  617. return {'failed': True, 'msg': 'Unkown state passed'}
  618. # pylint: disable=too-many-branches
  619. def main():
  620. ''' ansible oc module for secrets '''
  621. module = AnsibleModule(
  622. argument_spec=dict(
  623. state=dict(default='present', type='str',
  624. choices=['present', 'absent', 'list']),
  625. debug=dict(default=False, type='bool'),
  626. src=dict(default=None, type='str'),
  627. content=dict(default=None),
  628. content_type=dict(default='dict', choices=['dict']),
  629. key=dict(default='', type='str'),
  630. value=dict(),
  631. value_type=dict(default='', type='str'),
  632. update=dict(default=False, type='bool'),
  633. append=dict(default=False, type='bool'),
  634. index=dict(default=None, type='int'),
  635. curr_value=dict(default=None, type='str'),
  636. curr_value_format=dict(default='yaml',
  637. choices=['yaml', 'json', 'str'],
  638. type='str'),
  639. backup=dict(default=True, type='bool'),
  640. separator=dict(default='.', type='str'),
  641. ),
  642. mutually_exclusive=[["curr_value", "index"], ['update', "append"]],
  643. required_one_of=[["content", "src"]],
  644. )
  645. rval = Yedit.run_ansible(module)
  646. if 'failed' in rval and rval['failed']:
  647. module.fail_json(**rval)
  648. module.exit_json(**rval)
  649. if __name__ == '__main__':
  650. main()