Debian Codegraph @

lib/ansible/modules/getent.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: (c) 2014, Brian Coca <[email protected]>
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
9 DOCUMENTATION = r"""
10 ---
11 module: getent
12 short_description: A wrapper to the unix getent utility
13 description:
14 - Runs getent against one of its various databases and returns information into
15 the host's facts, in a C(getent_<database>) prefixed variable.
16 version_added: "1.8"
17 options:
18 database:
19 description:
20 - The name of a getent database supported by the target system (passwd, group,
21 hosts, etc).
22 type: str
23 required: True
24 key:
25 description:
26 - Key from which to return values from the specified database, otherwise the
27 full contents are returned.
28 type: str
29 service:
30 description:
31 - Override all databases with the specified service
32 - The underlying system must support the service flag which is not always available.
33 type: str
34 version_added: "2.9"
35 split:
36 description:
37 - Character used to split the database values into lists/arrays such as V(:) or V(\\t),
38 otherwise it will try to pick one depending on the database.
39 - The value must be a non-empty string.
40 type: str
41 fail_key:
42 description:
43 - If a supplied key is missing this will make the task fail if V(true).
44 type: bool
45 default: 'yes'
46 extends_documentation_fragment:
47 - action_common_attributes
48 - action_common_attributes.facts
49 attributes:
50 check_mode:
51 support: full
52 diff_mode:
53 support: none
54 facts:
55 support: full
56 platform:
57 platforms: posix
58 notes:
59 - Not all databases support enumeration, check system documentation for details.
60 author:
61 - Brian Coca (@bcoca)
62 """
63
64 EXAMPLES = """
65 - name: Get root user info
66 ansible.builtin.getent:
67 database: passwd
68 key: root
69 - ansible.builtin.debug:
70 var: ansible_facts.getent_passwd
71
72 - name: Get all groups
73 ansible.builtin.getent:
74 database: group
75 split: ':'
76 - ansible.builtin.debug:
77 var: ansible_facts.getent_group
78
79 - name: Get all hosts, split by tab
80 ansible.builtin.getent:
81 database: hosts
82 - ansible.builtin.debug:
83 var: ansible_facts.getent_hosts
84
85 - name: Get http service info, no error if missing
86 ansible.builtin.getent:
87 database: services
88 key: http
89 fail_key: False
90 - ansible.builtin.debug:
91 var: ansible_facts.getent_services
92
93 - name: Get user password hash (requires sudo/root)
94 ansible.builtin.getent:
95 database: shadow
96 key: www-data
97 split: ':'
98 - ansible.builtin.debug:
99 var: ansible_facts.getent_shadow
100
101 """
102
103 RETURN = """
104 ansible_facts:
105 description: Facts to add to ansible_facts.
106 returned: always
107 type: dict
108 contains:
109 getent_<database>:
110 description:
111 - A list of results or a single result as a list of the fields the db provides
112 - The list elements depend on the database queried, see getent man page for the structure
113 - Starting at 2.11 it now returns multiple duplicate entries, previously it only returned the last one
114 returned: always
115 type: list
116 """
117
118 import platform
119 from ansible.module_utils.basic import AnsibleModule
120 from ansible.module_utils.common.text.converters import to_native
121
122
123 def main():
124 module = AnsibleModule(
125 argument_spec=dict(
126 database=dict(type='str', required=True),
127 key=dict(type='str', no_log=False),
128 service=dict(type='str'),
129 split=dict(type='str'),
130 fail_key=dict(type='bool', default=True),
131 ),
132 supports_check_mode=True,
133 )
134
135 colon = ['passwd', 'shadow', 'group', 'gshadow']
136
137 database = module.params['database']
138 key = module.params.get('key')
139 split = module.params.get('split')
140 service = module.params.get('service')
141 fail_key = module.params.get('fail_key')
142
143 getent_bin = module.get_bin_path('getent', True)
144
145 if key is not None:
146 cmd = [getent_bin, database, key]
147 else:
148 cmd = [getent_bin, database]
149
150 if service is not None:
151 if platform.libc_ver()[0] not in ('glibc',):
152 module.fail_json(msg=f"Specifying service `{service}` not supported on this platform.")
153 cmd.extend(['-s', service])
154
155 if not split and split is not None:
156 module.fail_json(msg="Invalid split value. The value must be a non-empty string")
157
158 if split is None and database in colon:
159 split = ':'
160
161 try:
162 rc, out, err = module.run_command(cmd)
163 except Exception as e:
164 module.fail_json(msg=to_native(e))
165
166 msg = "Unexpected failure!"
167 dbtree = 'getent_%s' % database
168 results = {dbtree: {}}
169
170 if rc == 0:
171 seen = {}
172 for line in out.splitlines():
173 record = line.split(split)
174
175 if record[0] in seen:
176 # more than one result for same key, ensure we store in a list
177 if seen[record[0]] == 1:
178 results[dbtree][record[0]] = [results[dbtree][record[0]]]
179
180 results[dbtree][record[0]].append(record[1:])
181 seen[record[0]] += 1
182 else:
183 # new key/value, just assign
184 results[dbtree][record[0]] = record[1:]
185 seen[record[0]] = 1
186
187 module.exit_json(ansible_facts=results)
188
189 elif rc == 1:
190 msg = "Missing arguments, or database unknown."
191 elif rc == 2:
192 msg = "One or more supplied key could not be found in the database."
193 if not fail_key:
194 results[dbtree][key] = None
195 module.exit_json(ansible_facts=results, msg=msg)
196 elif rc == 3:
197 msg = "Enumeration not supported on this database."
198
199 module.fail_json(msg=msg)
200
201
202 if __name__ == '__main__':
203 main()