Debian Codegraph @

ansible_collections/community/general/plugins/lookup/chef_databag.py

raw
1 # Copyright (c) 2016, Josh Bradley <jbradley(at)digitalocean.com>
2 # Copyright (c) 2017 Ansible Project
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5 from __future__ import annotations
6
7 DOCUMENTATION = r"""
8 author: Unknown (!UNKNOWN)
9 name: chef_databag
10 short_description: Fetches data from a Chef Databag
11 description:
12 - 'This is a lookup plugin to provide access to chef data bags using the pychef package. It interfaces with the chef server
13 API using the same methods to find a knife or chef-client config file to load parameters from, starting from either the
14 given base path or the current working directory. The lookup order mirrors the one from Chef, all folders in the base
15 path are walked back looking for the following configuration file in order: C(.chef/knife.rb), C(~/.chef/knife.rb), C(/etc/chef/client.rb).'
16 requirements:
17 - "pychef (L(Python library, https://pychef.readthedocs.io), C(pip install pychef))"
18 options:
19 name:
20 description:
21 - Name of the databag.
22 type: string
23 required: true
24 item:
25 description:
26 - Item to fetch.
27 type: string
28 required: true
29 """
30
31 EXAMPLES = r"""
32 - ansible.builtin.debug:
33 msg: "{{ lookup('community.general.chef_databag', 'name=data_bag_name item=data_bag_item') }}"
34 """
35
36 RETURN = r"""
37 _raw:
38 description:
39 - The value from the databag.
40 type: list
41 elements: dict
42 """
43
44 from ansible.errors import AnsibleError
45 from ansible.parsing.splitter import parse_kv
46 from ansible.plugins.lookup import LookupBase
47
48 try:
49 import chef
50
51 HAS_CHEF = True
52 except ImportError:
53 HAS_CHEF = False
54
55
56 class LookupModule(LookupBase):
57 """
58 Chef data bag lookup module
59 """
60
61 def __init__(self, loader=None, templar=None, **kwargs):
62 super().__init__(loader, templar, **kwargs)
63
64 # setup vars for data bag name and data bag item
65 self.name = None
66 self.item = None
67
68 def parse_kv_args(self, args):
69 """
70 parse key-value style arguments
71 """
72
73 for arg in ["name", "item"]:
74 try:
75 arg_raw = args.pop(arg, None)
76 if arg_raw is None:
77 continue
78 parsed = str(arg_raw)
79 setattr(self, arg, parsed)
80 except ValueError as e:
81 raise AnsibleError(f"can't parse arg {arg}={arg_raw} as string") from e
82 if args:
83 raise AnsibleError(f"unrecognized arguments to with_sequence: {list(args.keys())!r}")
84
85 def run(self, terms, variables=None, **kwargs):
86 # Ensure pychef has been loaded
87 if not HAS_CHEF:
88 raise AnsibleError("PyChef needed for lookup plugin, try `pip install pychef`")
89
90 # TODO: use new-style option parsing
91
92 for term in terms:
93 self.parse_kv_args(parse_kv(term))
94
95 api_object = chef.autoconfigure()
96
97 if not isinstance(api_object, chef.api.ChefAPI):
98 raise AnsibleError("Unable to connect to Chef Server API.")
99
100 data_bag_object = chef.DataBag(self.name)
101
102 data_bag_item = data_bag_object[self.item]
103
104 return [dict(data_bag_item)]