Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2017, Ansible Project
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: xattr
11 short_description: Manage user defined extended attributes
12 description:
13 - Manages filesystem user defined extended attributes.
14 - Requires that extended attributes are enabled on the target filesystem and that the C(setfattr)/C(getfattr) utilities
15 are present.
16 extends_documentation_fragment:
17 - community.general._attributes
18 attributes:
19 check_mode:
20 support: full
21 diff_mode:
22 support: none
23 options:
24 path:
25 description:
26 - The full path of the file/object to get the facts of.
27 type: path
28 required: true
29 aliases: [name]
30 namespace:
31 description:
32 - Namespace of the named name/key.
33 type: str
34 default: user
35 key:
36 description:
37 - The name of a specific Extended attribute key to set/retrieve.
38 type: str
39 value:
40 description:
41 - The value to set the named name/key to, it automatically sets the O(state) to V(present).
42 type: str
43 state:
44 description:
45 - Defines which state you want to do.
46 - V(read) retrieves the current value for a O(key).
47 - V(present) sets O(path) to O(value), default if value is set.
48 - V(all) dumps all data.
49 - V(keys) retrieves all keys.
50 - V(absent) deletes the key.
51 type: str
52 choices: [absent, all, keys, present, read]
53 default: read
54 follow:
55 description:
56 - If V(true), dereferences symlinks and sets/gets attributes on symlink target, otherwise acts on symlink itself.
57 type: bool
58 default: true
59 author:
60 - Brian Coca (@bcoca)
61 """
62
63 EXAMPLES = r"""
64 - name: Obtain the extended attributes of /etc/foo.conf
65 community.general.xattr:
66 path: /etc/foo.conf
67
68 - name: Set the key 'user.foo' to value 'bar'
69 community.general.xattr:
70 path: /etc/foo.conf
71 key: foo
72 value: bar
73
74 - name: Set the key 'trusted.glusterfs.volume-id' to value '0x817b94343f164f199e5b573b4ea1f914'
75 community.general.xattr:
76 path: /mnt/bricks/brick1
77 namespace: trusted
78 key: glusterfs.volume-id
79 value: "0x817b94343f164f199e5b573b4ea1f914"
80
81 - name: Remove the key 'user.foo'
82 community.general.xattr:
83 path: /etc/foo.conf
84 key: foo
85 state: absent
86
87 - name: Remove the key 'trusted.glusterfs.volume-id'
88 community.general.xattr:
89 path: /mnt/bricks/brick1
90 namespace: trusted
91 key: glusterfs.volume-id
92 state: absent
93 """
94
95 import os
96
97 # import module snippets
98 from ansible.module_utils.basic import AnsibleModule
99
100
101 def get_xattr_keys(module, path, follow):
102 cmd = [module.get_bin_path("getfattr", True), "--absolute-names"]
103
104 if not follow:
105 cmd.append("-h")
106 cmd.append(path)
107
108 return _run_xattr(module, cmd)
109
110
111 def get_xattr(module, path, key, follow):
112 cmd = [module.get_bin_path("getfattr", True), "--absolute-names"]
113
114 if not follow:
115 cmd.append("-h")
116 if key is None:
117 cmd.append("-d")
118 else:
119 cmd.append("-n")
120 cmd.append(key)
121 cmd.append(path)
122
123 return _run_xattr(module, cmd, False)
124
125
126 def set_xattr(module, path, key, value, follow):
127 cmd = [module.get_bin_path("setfattr", True)]
128 if not follow:
129 cmd.append("-h")
130 cmd.append("-n")
131 cmd.append(key)
132 cmd.append("-v")
133 cmd.append(value)
134 cmd.append(path)
135
136 return _run_xattr(module, cmd)
137
138
139 def rm_xattr(module, path, key, follow):
140 cmd = [module.get_bin_path("setfattr", True)]
141 if not follow:
142 cmd.append("-h")
143 cmd.append("-x")
144 cmd.append(key)
145 cmd.append(path)
146
147 return _run_xattr(module, cmd, False)
148
149
150 def _run_xattr(module, cmd, check_rc=True):
151 try:
152 (rc, out, err) = module.run_command(cmd, check_rc=check_rc)
153 except Exception as e:
154 module.fail_json(msg=f"{e}!")
155
156 # result = {'raw': out}
157 result = {}
158 for line in out.splitlines():
159 if line.startswith("#") or line == "":
160 pass
161 elif "=" in line:
162 (key, val) = line.split("=", 1)
163 result[key] = val.strip('"')
164 else:
165 result[line] = ""
166 return result
167
168
169 def main():
170 module = AnsibleModule(
171 argument_spec=dict(
172 path=dict(type="path", required=True, aliases=["name"]),
173 namespace=dict(type="str", default="user"),
174 key=dict(type="str", no_log=False),
175 value=dict(type="str"),
176 state=dict(type="str", default="read", choices=["absent", "all", "keys", "present", "read"]),
177 follow=dict(type="bool", default=True),
178 ),
179 supports_check_mode=True,
180 )
181 module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"}
182 path = module.params.get("path")
183 namespace = module.params.get("namespace")
184 key = module.params.get("key")
185 value = module.params.get("value")
186 state = module.params.get("state")
187 follow = module.params.get("follow")
188
189 if not os.path.exists(path):
190 module.fail_json(msg="path not found or not accessible!")
191
192 changed = False
193 msg = ""
194 res = {}
195
196 if key is None and state in ["absent", "present"]:
197 module.fail_json(msg=f"{state} needs a key parameter")
198
199 # Prepend the key with the namespace if defined
200 if (
201 key is not None
202 and namespace is not None
203 and len(namespace) > 0
204 and not (namespace == "user" and key.startswith("user."))
205 ):
206 key = f"{namespace}.{key}"
207
208 if state == "present" or value is not None:
209 current = get_xattr(module, path, key, follow)
210 if current is None or key not in current or value != current[key]:
211 if not module.check_mode:
212 res = set_xattr(module, path, key, value, follow)
213 changed = True
214 res = current
215 msg = f"{key} set to {value}"
216 elif state == "absent":
217 current = get_xattr(module, path, key, follow)
218 if current is not None and key in current:
219 if not module.check_mode:
220 res = rm_xattr(module, path, key, follow)
221 changed = True
222 res = current
223 msg = f"{key} removed"
224 elif state == "keys":
225 res = get_xattr_keys(module, path, follow)
226 msg = "returning all keys"
227 elif state == "all":
228 res = get_xattr(module, path, None, follow)
229 msg = "dumping all"
230 else:
231 res = get_xattr(module, path, key, follow)
232 msg = f"returning {key}"
233
234 module.exit_json(changed=changed, msg=msg, xattr=res)
235
236
237 if __name__ == "__main__":
238 main()