Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2019 David Lundgren <[email protected]>
4 #
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import annotations
9
10 DOCUMENTATION = r"""
11 author:
12 - David Lundgren (@dlundgren)
13 module: sysrc
14 short_description: Manage FreeBSD using sysrc
15 version_added: '2.0.0'
16 description:
17 - Manages C(/etc/rc.conf) for FreeBSD.
18 extends_documentation_fragment:
19 - community.general._attributes
20 attributes:
21 check_mode:
22 support: full
23 diff_mode:
24 support: none
25 options:
26 name:
27 description:
28 - Name of variable in C(/etc/rc.conf) to manage.
29 type: str
30 required: true
31 value:
32 description:
33 - The value to set when O(state=present).
34 - The value to add when O(state=value_present).
35 - The value to remove when O(state=value_absent).
36 type: str
37 state:
38 description:
39 - Use V(present) to add the variable.
40 - Use V(absent) to remove the variable.
41 - Use V(value_present) to add the value to the existing variable.
42 - Use V(value_absent) to remove the value from the existing variable.
43 type: str
44 default: "present"
45 choices: [absent, present, value_present, value_absent]
46 path:
47 description:
48 - Path to file to use instead of V(/etc/rc.conf).
49 type: str
50 default: "/etc/rc.conf"
51 delim:
52 description:
53 - Delimiter to be used instead of V(" ") (space).
54 - Only used when O(state=value_present) or O(state=value_absent).
55 default: " "
56 type: str
57 jail:
58 description:
59 - Name or ID of the jail to operate on.
60 type: str
61 notes:
62 - The O(name) cannot contain periods as sysrc does not support OID style names.
63 """
64
65 EXAMPLES = r"""
66 # enable mysql in the /etc/rc.conf
67 - name: Configure mysql pid file
68 community.general.sysrc:
69 name: mysql_pidfile
70 value: "/var/run/mysqld/mysqld.pid"
71
72 # enable accf_http kld in the boot loader
73 - name: Enable accf_http kld
74 community.general.sysrc:
75 name: accf_http_load
76 state: present
77 value: "YES"
78 path: /boot/loader.conf
79
80 # add gif0 to cloned_interfaces
81 - name: Add gif0 interface
82 community.general.sysrc:
83 name: cloned_interfaces
84 state: value_present
85 value: "gif0"
86
87 # enable nginx on a jail
88 - name: Enable nginx in test jail
89 community.general.sysrc:
90 name: nginx_enable
91 value: "YES"
92 jail: testjail
93 """
94
95
96 import os
97 import re
98
99 from ansible_collections.community.general.plugins.module_utils._module_helper import StateModuleHelper
100
101
102 class Sysrc(StateModuleHelper):
103 module = dict(
104 argument_spec=dict(
105 name=dict(type="str", required=True),
106 value=dict(type="str"),
107 state=dict(type="str", default="present", choices=["absent", "present", "value_present", "value_absent"]),
108 path=dict(type="str", default="/etc/rc.conf"),
109 delim=dict(type="str", default=" "),
110 jail=dict(type="str"),
111 ),
112 supports_check_mode=True,
113 )
114 output_params = ("value",)
115 use_old_vardict = False
116
117 def __init_module__(self):
118 # OID style names are not supported
119 if not re.match(r"^\w+$", self.vars.name, re.ASCII):
120 self.module.fail_json(msg="Name may only contain alpha-numeric and underscore characters")
121
122 self.module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"}
123 self.sysrc = self.module.get_bin_path("sysrc", True)
124
125 def _contains(self):
126 value = self._get()
127 if value is None:
128 return False, None
129
130 value = value.split(self.vars.delim)
131
132 return self.vars.value in value, value
133
134 def _get(self):
135 if not os.path.exists(self.vars.path):
136 return None
137
138 (rc, out, err) = self._sysrc("-v", "-n", self.vars.name)
139 if "unknown variable" in err or "unknown variable" in out:
140 # Prior to FreeBSD 11.1 sysrc would write "unknown variable" to stdout and not stderr
141 # https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=229806
142 return None
143
144 if out.startswith(self.vars.path):
145 return out.split(":", 1)[1].strip()
146
147 return None
148
149 def _modify(self, op, changed):
150 (rc, out, err) = self._sysrc(f"{self.vars.name}{op}={self.vars.delim}{self.vars.value}")
151 if out.startswith(f"{self.vars.name}:"):
152 return changed(out.split(" -> ")[1].strip().split(self.vars.delim))
153
154 return False
155
156 def _sysrc(self, *args):
157 cmd = [self.sysrc, "-f", self.vars.path]
158 if self.vars.jail:
159 cmd += ["-j", self.vars.jail]
160 cmd.extend(args)
161
162 (rc, out, err) = self.module.run_command(cmd)
163 if "Permission denied" in err:
164 self.module.fail_json(msg=f"Permission denied for {self.vars.path}")
165
166 return rc, out, err
167
168 def state_absent(self):
169 if self._get() is None:
170 return
171
172 if not self.check_mode:
173 self._sysrc("-x", self.vars.name)
174
175 self.changed = True
176
177 def state_present(self):
178 value = self._get()
179 if value == self.vars.value:
180 return
181
182 if self.vars.value is None:
183 self.vars.set("value", value)
184 return
185
186 if not self.check_mode:
187 self._sysrc(f"{self.vars.name}={self.vars.value}")
188
189 self.changed = True
190
191 def state_value_absent(self):
192 (contains, _unused) = self._contains()
193 if not contains:
194 return
195
196 self.changed = self.check_mode or self._modify("-", lambda values: self.vars.value not in values)
197
198 def state_value_present(self):
199 (contains, value) = self._contains()
200 if contains:
201 return
202
203 if self.vars.value is None:
204 self.vars.set("value", value)
205 return
206
207 self.changed = self.check_mode or self._modify("+", lambda values: self.vars.value in values)
208
209
210 def main():
211 Sysrc.execute()
212
213
214 if __name__ == "__main__":
215 main()