Debian Codegraph @

ansible_collections/community/general/plugins/modules/ldap_inc.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2024, Philippe Duveau <[email protected]>
4 # Copyright (c) 2019, Maciej Delmanowski <[email protected]> (ldap_attrs.py)
5 # Copyright (c) 2017, Alexander Korinek <[email protected]> (ldap_attrs.py)
6 # Copyright (c) 2016, Peter Sagerson <[email protected]> (ldap_attrs.py)
7 # Copyright (c) 2016, Jiri Tyr <[email protected]> (ldap_attrs.py)
8 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
9 # SPDX-License-Identifier: GPL-3.0-or-later
10
11 # The code of this module is derived from that of ldap_attrs.py
12
13 from __future__ import annotations
14
15 DOCUMENTATION = r"""
16 module: ldap_inc
17 short_description: Use the Modify-Increment LDAP V3 feature to increment an attribute value
18 version_added: 10.2.0
19 description:
20 - Atomically increments the value of an attribute and return its new value.
21 notes:
22 - When implemented by the directory server, the module uses the ModifyIncrement extension defined in L(RFC4525, https://www.rfc-editor.org/rfc/rfc4525.html)
23 and the control PostRead. This extension and the control are implemented in OpenLdap but not all directory servers implement
24 them. In this case, the module automatically uses a more classic method based on two phases, first the current value is
25 read then the modify operation remove the old value and add the new one in a single request. If the value has changed
26 by a concurrent call then the remove action fails. Then the sequence is retried 3 times before raising an error to the
27 playbook. In an heavy modification environment, the module does not guarante to be systematically successful.
28 - This only deals with integer attribute of an existing entry. To modify attributes of an entry, see M(community.general.ldap_attrs)
29 or to add or remove whole entries, see M(community.general.ldap_entry).
30 author:
31 - Philippe Duveau (@pduveau)
32 requirements:
33 - python-ldap
34 attributes:
35 check_mode:
36 support: full
37 diff_mode:
38 support: none
39 options:
40 dn:
41 required: true
42 type: str
43 description:
44 - The DN entry containing the attribute to increment.
45 attribute:
46 required: true
47 type: str
48 description:
49 - The attribute to increment.
50 increment:
51 type: int
52 default: 1
53 description:
54 - The value of the increment to apply.
55 method:
56 type: str
57 default: auto
58 choices: [auto, rfc4525, legacy]
59 description:
60 - If V(auto), the module determines automatically the method to use.
61 - If V(rfc4525) or V(legacy) force to use the corresponding method.
62 extends_documentation_fragment:
63 - community.general._ldap.documentation
64 - community.general._attributes
65 """
66
67
68 EXAMPLES = r"""
69 - name: Increments uidNumber 1 Number for example.com
70 community.general.ldap_inc:
71 dn: "cn=uidNext,ou=unix-management,dc=example,dc=com"
72 attribute: "uidNumber"
73 increment: "1"
74 register: ldap_uidNumber_sequence
75
76 - name: Modifies the user to define its identification number (uidNumber) when incrementation is successful
77 community.general.ldap_attrs:
78 dn: "cn=john,ou=posix-users,dc=example,dc=com"
79 state: present
80 attributes:
81 - uidNumber: "{{ ldap_uidNumber_sequence.value }}"
82 when: ldap_uidNumber_sequence.incremented
83 """
84
85
86 RETURN = r"""
87 incremented:
88 description:
89 - It is set to V(true) if the attribute value has changed.
90 returned: success
91 type: bool
92 sample: true
93
94 attribute:
95 description:
96 - The name of the attribute that was incremented.
97 returned: success
98 type: str
99 sample: uidNumber
100
101 value:
102 description:
103 - The new value after incrementing.
104 returned: success
105 type: str
106 sample: "2"
107
108 rfc4525:
109 description:
110 - Is V(true) if the method used to increment is based on RFC4525, V(false) if legacy.
111 returned: success
112 type: bool
113 sample: true
114 """
115
116 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
117 from ansible.module_utils.common.text.converters import to_bytes
118
119 from ansible_collections.community.general.plugins.module_utils import _deps as deps
120 from ansible_collections.community.general.plugins.module_utils._ldap import (
121 LdapGeneric,
122 gen_specs,
123 ldap_required_together,
124 )
125
126 with deps.declare("ldap", reason=missing_required_lib("python-ldap")):
127 import ldap
128 import ldap.controls.readentry
129
130
131 class LdapInc(LdapGeneric):
132 def __init__(self, module):
133 LdapGeneric.__init__(self, module)
134 # Shortcuts
135 self.attr = self.module.params["attribute"]
136 self.increment = self.module.params["increment"]
137 self.method = self.module.params["method"]
138
139 def inc_rfc4525(self):
140 return [(ldap.MOD_INCREMENT, self.attr, [to_bytes(str(self.increment))])]
141
142 def inc_legacy(self, curr_val, new_val):
143 return [(ldap.MOD_DELETE, self.attr, [to_bytes(curr_val)]), (ldap.MOD_ADD, self.attr, [to_bytes(new_val)])]
144
145 def serverControls(self):
146 return [ldap.controls.readentry.PostReadControl(attrList=[self.attr])]
147
148 LDAP_MOD_INCREMENT = to_bytes("1.3.6.1.1.14")
149
150
151 def main():
152 module = AnsibleModule(
153 argument_spec=gen_specs(
154 attribute=dict(type="str", required=True),
155 increment=dict(type="int", default=1),
156 method=dict(type="str", default="auto", choices=["auto", "rfc4525", "legacy"]),
157 ),
158 supports_check_mode=True,
159 required_together=ldap_required_together(),
160 )
161
162 deps.validate(module)
163
164 # Instantiate the LdapAttr object
165 mod = LdapInc(module)
166
167 changed = False
168 ret = ""
169 rfc4525 = False
170
171 try:
172 if mod.increment != 0 and not module.check_mode:
173 changed = True
174
175 if mod.method != "auto":
176 rfc4525 = mod.method == "rfc425"
177 else:
178 rootDSE = mod.connection.search_ext_s(base="", scope=ldap.SCOPE_BASE, attrlist=["*", "+"])
179 if len(rootDSE) == 1:
180 if to_bytes(ldap.CONTROL_POST_READ) in rootDSE[0][1]["supportedControl"] and (
181 mod.LDAP_MOD_INCREMENT in rootDSE[0][1]["supportedFeatures"]
182 or mod.LDAP_MOD_INCREMENT in rootDSE[0][1]["supportedExtension"]
183 ):
184 rfc4525 = True
185
186 if rfc4525:
187 dummy, dummy, dummy, resp_ctrls = mod.connection.modify_ext_s(
188 dn=mod.dn, modlist=mod.inc_rfc4525(), serverctrls=mod.serverControls(), clientctrls=None
189 )
190 if len(resp_ctrls) == 1:
191 ret = resp_ctrls[0].entry[mod.attr][0]
192
193 else:
194 tries = 0
195 max_tries = 3
196 while tries < max_tries:
197 tries = tries + 1
198 result = mod.connection.search_ext_s(
199 base=mod.dn, scope=ldap.SCOPE_BASE, filterstr=f"({mod.attr}=*)", attrlist=[mod.attr]
200 )
201 if len(result) != 1:
202 module.fail_json(msg="The entry does not exist or does not contain the specified attribute.")
203 return
204 try:
205 ret = str(int(result[0][1][mod.attr][0]) + mod.increment)
206 # if the current value first arg in inc_legacy has changed then the modify will fail
207 mod.connection.modify_s(dn=mod.dn, modlist=mod.inc_legacy(result[0][1][mod.attr][0], ret))
208 break
209 except ldap.NO_SUCH_ATTRIBUTE:
210 if tries == max_tries:
211 module.fail_json(msg=f"The increment could not be applied after {max_tries} tries.")
212 return
213
214 else:
215 result = mod.connection.search_ext_s(
216 base=mod.dn, scope=ldap.SCOPE_BASE, filterstr=f"({mod.attr}=*)", attrlist=[mod.attr]
217 )
218 if len(result) == 1:
219 ret = str(int(result[0][1][mod.attr][0]) + mod.increment)
220 changed = mod.increment != 0
221 else:
222 module.fail_json(msg="The entry does not exist or does not contain the specified attribute.")
223
224 except Exception as e:
225 module.fail_json(msg="Attribute action failed.", details=f"{e}")
226
227 module.exit_json(changed=changed, incremented=changed, attribute=mod.attr, value=ret, rfc4525=rfc4525)
228
229
230 if __name__ == "__main__":
231 main()