Debian Codegraph @

lib/ansible/parsing/utils/yaml.py

raw
1 # (c) 2012-2014, Michael DeHaan <[email protected]>
2 # Copyright: (c) 2017, Ansible Project
3 # Copyright: (c) 2018, Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import annotations
7
8 import json
9 import typing as t
10
11 import yaml
12
13 from ansible.errors import AnsibleJSONParserError
14 from ansible._internal._errors import _error_utils
15 from ansible.parsing.vault import VaultSecret
16 from ansible.parsing.yaml.loader import AnsibleLoader
17 from ansible._internal._yaml._errors import AnsibleYAMLParserError
18 from ansible._internal._datatag._tags import Origin
19 from ansible._internal._json._profiles import _legacy
20
21
22 def from_yaml(
23 data: str,
24 file_name: str | None = None,
25 show_content: bool = True,
26 vault_secrets: list[tuple[str, VaultSecret]] | None = None, # deprecated: description='Deprecate vault_secrets, it has no effect.' core_version='2.23'
27 json_only: bool = False,
28 ) -> t.Any:
29 """Creates a Python data structure from the given data, which can be either a JSON or YAML string."""
30 # FUTURE: provide Ansible-specific top-level APIs to expose JSON and YAML serialization/deserialization to hide the error handling logic
31 # once those are in place, defer deprecate this entire function
32
33 origin = Origin.get_or_create_tag(data, file_name)
34
35 data = origin.tag(data)
36
37 with _error_utils.RedactAnnotatedSourceContext.when(not show_content):
38 try:
39 # we first try to load this data as JSON.
40 # Fixes issues with extra vars json strings not being parsed correctly by the yaml parser
41 return json.loads(data, cls=_legacy.Decoder)
42 except Exception as ex:
43 json_ex = ex
44
45 if json_only:
46 AnsibleJSONParserError.handle_exception(json_ex, origin=origin)
47
48 try:
49 return yaml.load(data, Loader=AnsibleLoader) # type: ignore[arg-type]
50 except Exception as yaml_ex:
51 # DTFIX-FUTURE: how can we indicate in Origin that the data is in-memory only, to support context information -- is that useful?
52 # we'd need to pass data to handle_exception so it could be used as the content instead of reading from disk
53 AnsibleYAMLParserError.handle_exception(yaml_ex, origin=origin)