yedit.py 27 KB

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