| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2016, Shinichi TAMURA (@tmshn) |
| 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: timezone |
| 11 |
short_description: Configure timezone setting |
| 12 |
description: |
| 13 |
- This module configures the timezone setting, both of the system clock and of the hardware clock. If you want to set up |
| 14 |
the NTP, use M(ansible.builtin.service) module. |
| 15 |
- It is recommended to restart C(crond) after changing the timezone, otherwise the jobs may run at the wrong time. |
| 16 |
- Several different tools are used depending on the OS/Distribution involved. For Linux it can use C(timedatectl) or edit |
| 17 |
C(/etc/sysconfig/clock) or C(/etc/timezone) and C(hwclock). On SmartOS, C(sm-set-timezone), for macOS, C(systemsetup), |
| 18 |
for BSD, C(/etc/localtime) is modified. On AIX, C(chtz) is used. |
| 19 |
- Make sure that the zoneinfo files are installed with the appropriate OS package, like C(tzdata) (usually always installed, |
| 20 |
when not using a minimal installation like Alpine Linux). |
| 21 |
- Windows and HPUX are not supported, please let us know if you find any other OS/distro in which this fails. |
| 22 |
extends_documentation_fragment: |
| 23 |
- community.general._attributes |
| 24 |
attributes: |
| 25 |
check_mode: |
| 26 |
support: full |
| 27 |
diff_mode: |
| 28 |
support: full |
| 29 |
options: |
| 30 |
name: |
| 31 |
description: |
| 32 |
- Name of the timezone for the system clock. |
| 33 |
- Default is to keep current setting. |
| 34 |
- B(At least one) of O(name) and O(hwclock) are required. |
| 35 |
type: str |
| 36 |
hwclock: |
| 37 |
description: |
| 38 |
- Whether the hardware clock is in UTC or in local timezone. |
| 39 |
- Default is to keep current setting. |
| 40 |
- Note that this option is recommended not to change and may fail to configure, especially on virtual environments such |
| 41 |
as AWS. |
| 42 |
- B(At least one) of O(name) and O(hwclock) are required. |
| 43 |
- I(Only used on Linux). |
| 44 |
type: str |
| 45 |
aliases: [rtc] |
| 46 |
choices: [local, UTC] |
| 47 |
notes: |
| 48 |
- On Ubuntu 24.04 and Debian 13 (Trixie), the C(util-linux-extra) package is required to provide the C(hwclock) command. |
| 49 |
- On SmartOS the C(sm-set-timezone) utility (part of the smtools package) is required to set the zone timezone. |
| 50 |
- On AIX only Olson/tz database timezones are usable (POSIX is not supported). An OS reboot is also required on AIX for |
| 51 |
the new timezone setting to take effect. Note that AIX 6.1+ is needed (OS level 61 or newer). |
| 52 |
author: |
| 53 |
- Shinichi TAMURA (@tmshn) |
| 54 |
- Jasper Lievisse Adriaanse (@jasperla) |
| 55 |
- Indrajit Raychaudhuri (@indrajitr) |
| 56 |
""" |
| 57 |
|
| 58 |
EXAMPLES = r""" |
| 59 |
- name: Set timezone to Asia/Tokyo |
| 60 |
become: true |
| 61 |
community.general.timezone: |
| 62 |
name: Asia/Tokyo |
| 63 |
|
| 64 |
- name: Set timezone and hardware clock to UTC |
| 65 |
community.general.timezone: |
| 66 |
name: UTC |
| 67 |
hwclock: UTC |
| 68 |
""" |
| 69 |
|
| 70 |
import errno |
| 71 |
import filecmp |
| 72 |
import os |
| 73 |
import platform |
| 74 |
import random |
| 75 |
import re |
| 76 |
import string |
| 77 |
|
| 78 |
from ansible.module_utils.basic import AnsibleModule, get_distribution |
| 79 |
|
| 80 |
|
| 81 |
class Timezone: |
| 82 |
"""This is a generic Timezone manipulation class that is subclassed based on platform. |
| 83 |
|
| 84 |
A subclass may wish to override the following action methods: |
| 85 |
- get(key, phase) ... get the value from the system at `phase` |
| 86 |
- set(key, value) ... set the value to the current system |
| 87 |
""" |
| 88 |
|
| 89 |
def __new__(cls, module): |
| 90 |
"""Return the platform-specific subclass. |
| 91 |
|
| 92 |
It does not use load_platform_subclass() because it needs to judge based |
| 93 |
on whether the `timedatectl` command exists and is available. |
| 94 |
|
| 95 |
Args: |
| 96 |
module: The AnsibleModule. |
| 97 |
""" |
| 98 |
if platform.system() == "Linux": |
| 99 |
timedatectl = module.get_bin_path("timedatectl") |
| 100 |
if timedatectl is not None: |
| 101 |
rc, stdout, stderr = module.run_command(timedatectl) |
| 102 |
if rc == 0: |
| 103 |
return super(Timezone, SystemdTimezone).__new__(SystemdTimezone) |
| 104 |
else: |
| 105 |
module.debug(f"timedatectl command was found but not usable: {stderr}. using other method.") |
| 106 |
return super(Timezone, NosystemdTimezone).__new__(NosystemdTimezone) |
| 107 |
else: |
| 108 |
return super(Timezone, NosystemdTimezone).__new__(NosystemdTimezone) |
| 109 |
elif re.match("^joyent_.*Z", platform.version()): |
| 110 |
# platform.system() returns SunOS, which is too broad. So look at the |
| 111 |
# platform version instead. However we have to ensure that we're not |
| 112 |
# running in the global zone where changing the timezone has no effect. |
| 113 |
zonename_cmd = module.get_bin_path("zonename") |
| 114 |
if zonename_cmd is not None: |
| 115 |
(rc, stdout, dummy) = module.run_command(zonename_cmd) |
| 116 |
if rc == 0 and stdout.strip() == "global": |
| 117 |
module.fail_json(msg="Adjusting timezone is not supported in Global Zone") |
| 118 |
|
| 119 |
return super(Timezone, SmartOSTimezone).__new__(SmartOSTimezone) |
| 120 |
elif platform.system() == "Darwin": |
| 121 |
return super(Timezone, DarwinTimezone).__new__(DarwinTimezone) |
| 122 |
elif re.match("^(Free|Net|Open)BSD", platform.platform()): |
| 123 |
return super(Timezone, BSDTimezone).__new__(BSDTimezone) |
| 124 |
elif platform.system() == "AIX": |
| 125 |
AIXoslevel = int(platform.version() + platform.release()) |
| 126 |
if AIXoslevel >= 61: |
| 127 |
return super(Timezone, AIXTimezone).__new__(AIXTimezone) |
| 128 |
else: |
| 129 |
module.fail_json(msg=f"AIX os level must be >= 61 for timezone module (Target: {AIXoslevel}).") |
| 130 |
else: |
| 131 |
# Not supported yet |
| 132 |
return super(Timezone, Timezone).__new__(Timezone) |
| 133 |
|
| 134 |
def __init__(self, module): |
| 135 |
"""Initialize of the class. |
| 136 |
|
| 137 |
Args: |
| 138 |
module: The AnsibleModule. |
| 139 |
""" |
| 140 |
super().__init__() |
| 141 |
self.msg = [] |
| 142 |
# `self.value` holds the values for each params on each phases. |
| 143 |
# Initially there's only info of "planned" phase, but the |
| 144 |
# `self.check()` function will fill out it. |
| 145 |
self.value = dict() |
| 146 |
for key in module.argument_spec: |
| 147 |
value = module.params[key] |
| 148 |
if value is not None: |
| 149 |
self.value[key] = dict(planned=value) |
| 150 |
self.module = module |
| 151 |
|
| 152 |
def abort(self, msg): |
| 153 |
"""Abort the process with error message. |
| 154 |
|
| 155 |
This is just the wrapper of module.fail_json(). |
| 156 |
|
| 157 |
Args: |
| 158 |
msg: The error message. |
| 159 |
""" |
| 160 |
error_msg = ["Error message:", msg] |
| 161 |
if len(self.msg) > 0: |
| 162 |
error_msg.append("Other message(s):") |
| 163 |
error_msg.extend(self.msg) |
| 164 |
self.module.fail_json(msg="\n".join(error_msg)) |
| 165 |
|
| 166 |
def execute(self, *commands, **kwargs): |
| 167 |
"""Execute the shell command. |
| 168 |
|
| 169 |
This is just the wrapper of module.run_command(). |
| 170 |
|
| 171 |
Args: |
| 172 |
*commands: The command to execute. |
| 173 |
**kwargs: Only 'log' key is checked. |
| 174 |
If kwargs['log'] is true, record the command to self.msg. |
| 175 |
|
| 176 |
Returns: |
| 177 |
stdout: Standard output of the command. |
| 178 |
""" |
| 179 |
(rc, stdout, stderr) = self.module.run_command(list(commands), check_rc=True) |
| 180 |
if kwargs.get("log", False): |
| 181 |
self.msg.append(f"executed `{' '.join(commands)}`") |
| 182 |
return stdout |
| 183 |
|
| 184 |
def diff(self, phase1="before", phase2="after"): |
| 185 |
"""Calculate the difference between given 2 phases. |
| 186 |
|
| 187 |
Args: |
| 188 |
phase1, phase2: The names of phase to compare. |
| 189 |
|
| 190 |
Returns: |
| 191 |
diff: The difference of value between phase1 and phase2. |
| 192 |
This is in the format which can be used with the |
| 193 |
`--diff` option of ansible-playbook. |
| 194 |
""" |
| 195 |
diff = {phase1: {}, phase2: {}} |
| 196 |
for key, value in self.value.items(): |
| 197 |
diff[phase1][key] = value[phase1] |
| 198 |
diff[phase2][key] = value[phase2] |
| 199 |
return diff |
| 200 |
|
| 201 |
def check(self, phase): |
| 202 |
"""Check the state in given phase and set it to `self.value`. |
| 203 |
|
| 204 |
Args: |
| 205 |
phase: The name of the phase to check. |
| 206 |
|
| 207 |
Returns: |
| 208 |
NO RETURN VALUE |
| 209 |
""" |
| 210 |
if phase == "planned": |
| 211 |
return |
| 212 |
for key, value in self.value.items(): |
| 213 |
value[phase] = self.get(key, phase) |
| 214 |
|
| 215 |
def change(self): |
| 216 |
"""Make the changes effect based on `self.value`.""" |
| 217 |
for key, value in self.value.items(): |
| 218 |
if value["before"] != value["planned"]: |
| 219 |
self.set(key, value["planned"]) |
| 220 |
|
| 221 |
# =========================================== |
| 222 |
# Platform specific methods (must be replaced by subclass). |
| 223 |
|
| 224 |
def get(self, key, phase): |
| 225 |
"""Get the value for the key at the given phase. |
| 226 |
|
| 227 |
Called from self.check(). |
| 228 |
|
| 229 |
Args: |
| 230 |
key: The key to get the value |
| 231 |
phase: The phase to get the value |
| 232 |
|
| 233 |
Return: |
| 234 |
value: The value for the key at the given phase. |
| 235 |
""" |
| 236 |
self.abort("get(key, phase) is not implemented on target platform") |
| 237 |
|
| 238 |
def set(self, key, value): |
| 239 |
"""Set the value for the key (of course, for the phase 'after'). |
| 240 |
|
| 241 |
Called from self.change(). |
| 242 |
|
| 243 |
Args: |
| 244 |
key: Key to set the value |
| 245 |
value: Value to set |
| 246 |
""" |
| 247 |
self.abort("set(key, value) is not implemented on target platform") |
| 248 |
|
| 249 |
def _verify_timezone(self): |
| 250 |
tz = self.value["name"]["planned"] |
| 251 |
tzfile = f"/usr/share/zoneinfo/{tz}" |
| 252 |
if not os.path.isfile(tzfile): |
| 253 |
self.abort(f'given timezone "{tz}" is not available') |
| 254 |
return tzfile |
| 255 |
|
| 256 |
|
| 257 |
class SystemdTimezone(Timezone): |
| 258 |
"""This is a Timezone manipulation class for systemd-powered Linux. |
| 259 |
|
| 260 |
It uses the `timedatectl` command to check/set all arguments. |
| 261 |
""" |
| 262 |
|
| 263 |
regexps = dict( |
| 264 |
hwclock=re.compile(r"^\s*RTC in local TZ\s*:\s*([^\s]+)", re.MULTILINE), |
| 265 |
name=re.compile(r"^\s*Time ?zone\s*:\s*([^\s]+)", re.MULTILINE), |
| 266 |
) |
| 267 |
|
| 268 |
subcmds = dict(hwclock="set-local-rtc", name="set-timezone") |
| 269 |
|
| 270 |
def __init__(self, module): |
| 271 |
super().__init__(module) |
| 272 |
self.timedatectl = module.get_bin_path("timedatectl", required=True) |
| 273 |
self.status = dict() |
| 274 |
# Validate given timezone |
| 275 |
if "name" in self.value: |
| 276 |
self._verify_timezone() |
| 277 |
|
| 278 |
def _get_status(self, phase): |
| 279 |
if phase not in self.status: |
| 280 |
self.status[phase] = self.execute(self.timedatectl, "status") |
| 281 |
return self.status[phase] |
| 282 |
|
| 283 |
def get(self, key, phase): |
| 284 |
status = self._get_status(phase) |
| 285 |
value = self.regexps[key].search(status).group(1) |
| 286 |
if key == "hwclock": |
| 287 |
# For key='hwclock'; convert yes/no -> local/UTC |
| 288 |
if self.module.boolean(value): |
| 289 |
value = "local" |
| 290 |
else: |
| 291 |
value = "UTC" |
| 292 |
return value |
| 293 |
|
| 294 |
def set(self, key, value): |
| 295 |
# For key='hwclock'; convert UTC/local -> yes/no |
| 296 |
if key == "hwclock": |
| 297 |
if value == "local": |
| 298 |
value = "yes" |
| 299 |
else: |
| 300 |
value = "no" |
| 301 |
self.execute(self.timedatectl, self.subcmds[key], value, log=True) |
| 302 |
|
| 303 |
|
| 304 |
class NosystemdTimezone(Timezone): |
| 305 |
"""This is a Timezone manipulation class for non systemd-powered Linux. |
| 306 |
|
| 307 |
For timezone setting, it edits the following file and reflect changes: |
| 308 |
- /etc/sysconfig/clock ... RHEL/CentOS |
| 309 |
- /etc/timezone ... Debian/Ubuntu |
| 310 |
For hwclock setting, it executes `hwclock --systohc` command with the |
| 311 |
'--utc' or '--localtime' option. |
| 312 |
""" |
| 313 |
|
| 314 |
conf_files = dict( |
| 315 |
name=None, # To be set in __init__ |
| 316 |
hwclock=None, # To be set in __init__ |
| 317 |
adjtime="/etc/adjtime", |
| 318 |
) |
| 319 |
|
| 320 |
# It is fine if all tree config files don't exist |
| 321 |
allow_no_file = dict(name=True, hwclock=True, adjtime=True) |
| 322 |
|
| 323 |
regexps = dict( |
| 324 |
name=None, # To be set in __init__ |
| 325 |
hwclock=re.compile(r"^UTC\s*=\s*([^\s]+)", re.MULTILINE), |
| 326 |
adjtime=re.compile(r"^(UTC|LOCAL)$", re.MULTILINE), |
| 327 |
) |
| 328 |
|
| 329 |
dist_regexps = dict( |
| 330 |
SuSE=re.compile(r'^TIMEZONE\s*=\s*"?([^"\s]+)"?', re.MULTILINE), |
| 331 |
redhat=re.compile(r'^ZONE\s*=\s*"?([^"\s]+)"?', re.MULTILINE), |
| 332 |
) |
| 333 |
|
| 334 |
dist_tzline_format = dict(SuSE='TIMEZONE="%s"\n', redhat='ZONE="%s"\n') |
| 335 |
|
| 336 |
def __init__(self, module): |
| 337 |
super().__init__(module) |
| 338 |
# Validate given timezone |
| 339 |
planned_tz = "" |
| 340 |
if "name" in self.value: |
| 341 |
tzfile = self._verify_timezone() |
| 342 |
planned_tz = self.value["name"]["planned"] |
| 343 |
# `--remove-destination` is needed if /etc/localtime is a symlink so |
| 344 |
# that it overwrites it instead of following it. |
| 345 |
self.update_timezone = [ |
| 346 |
[self.module.get_bin_path("cp", required=True), "--remove-destination", tzfile, "/etc/localtime"] |
| 347 |
] |
| 348 |
self.update_hwclock = self.module.get_bin_path("hwclock", required=True) |
| 349 |
distribution = get_distribution() |
| 350 |
self.conf_files["name"] = "/etc/timezone" |
| 351 |
self.regexps["name"] = re.compile(r"^([^\s]+)", re.MULTILINE) |
| 352 |
self.tzline_format = "%s\n" |
| 353 |
# Distribution-specific configurations |
| 354 |
if self.module.get_bin_path("dpkg-reconfigure") is not None: |
| 355 |
# Debian/Ubuntu |
| 356 |
if "name" in self.value: |
| 357 |
self.update_timezone = [ |
| 358 |
[self.module.get_bin_path("ln", required=True), "-sf", tzfile, "/etc/localtime"], |
| 359 |
[ |
| 360 |
self.module.get_bin_path("dpkg-reconfigure", required=True), |
| 361 |
"--frontend", |
| 362 |
"noninteractive", |
| 363 |
"tzdata", |
| 364 |
], |
| 365 |
] |
| 366 |
self.conf_files["hwclock"] = "/etc/default/rcS" |
| 367 |
elif distribution == "Alpine" or distribution == "Gentoo": |
| 368 |
self.conf_files["hwclock"] = "/etc/conf.d/hwclock" |
| 369 |
if distribution == "Alpine": |
| 370 |
self.update_timezone = [[self.module.get_bin_path("setup-timezone", required=True), "-z", planned_tz]] |
| 371 |
else: |
| 372 |
# RHEL/CentOS/SUSE |
| 373 |
if self.module.get_bin_path("tzdata-update") is not None: |
| 374 |
# tzdata-update cannot update the timezone if /etc/localtime is |
| 375 |
# a symlink so we have to use cp to update the time zone which |
| 376 |
# was set above. |
| 377 |
if not os.path.islink("/etc/localtime"): |
| 378 |
self.update_timezone = [[self.module.get_bin_path("tzdata-update", required=True)]] |
| 379 |
# else: |
| 380 |
# self.update_timezone = 'cp --remove-destination ...' <- configured above |
| 381 |
self.conf_files["name"] = "/etc/sysconfig/clock" |
| 382 |
self.conf_files["hwclock"] = "/etc/sysconfig/clock" |
| 383 |
try: |
| 384 |
with open(self.conf_files["name"]) as f: |
| 385 |
sysconfig_clock = f.read() |
| 386 |
except OSError as err: |
| 387 |
if self._allow_ioerror(err, "name"): |
| 388 |
# If the config file doesn't exist detect the distribution and set regexps. |
| 389 |
if distribution == "SuSE": |
| 390 |
# For SUSE |
| 391 |
self.regexps["name"] = self.dist_regexps["SuSE"] |
| 392 |
self.tzline_format = self.dist_tzline_format["SuSE"] |
| 393 |
else: |
| 394 |
# For RHEL/CentOS |
| 395 |
self.regexps["name"] = self.dist_regexps["redhat"] |
| 396 |
self.tzline_format = self.dist_tzline_format["redhat"] |
| 397 |
else: |
| 398 |
self.abort(f'could not read configuration file "{self.conf_files["name"]}"') |
| 399 |
else: |
| 400 |
# The key for timezone might be `ZONE` or `TIMEZONE` |
| 401 |
# (the former is used in RHEL/CentOS and the latter is used in SUSE linux). |
| 402 |
# So check the content of /etc/sysconfig/clock and decide which key to use. |
| 403 |
if re.search(r"^TIMEZONE\s*=", sysconfig_clock, re.MULTILINE): |
| 404 |
# For SUSE |
| 405 |
self.regexps["name"] = self.dist_regexps["SuSE"] |
| 406 |
self.tzline_format = self.dist_tzline_format["SuSE"] |
| 407 |
else: |
| 408 |
# For RHEL/CentOS |
| 409 |
self.regexps["name"] = self.dist_regexps["redhat"] |
| 410 |
self.tzline_format = self.dist_tzline_format["redhat"] |
| 411 |
|
| 412 |
def _allow_ioerror(self, err, key): |
| 413 |
# In some cases, even if the target file does not exist, |
| 414 |
# simply creating it may solve the problem. |
| 415 |
# In such cases, we should continue the configuration rather than aborting. |
| 416 |
if err.errno != errno.ENOENT: |
| 417 |
# If the error is not ENOENT ("No such file or directory"), |
| 418 |
# (e.g., permission error, etc), we should abort. |
| 419 |
return False |
| 420 |
return self.allow_no_file.get(key, False) |
| 421 |
|
| 422 |
def _edit_file(self, filename, regexp, value, key): |
| 423 |
"""Replace the first matched line with given `value`. |
| 424 |
|
| 425 |
If `regexp` matched more than once, other than the first line will be deleted. |
| 426 |
|
| 427 |
Args: |
| 428 |
filename: The name of the file to edit. |
| 429 |
regexp: The regular expression to search with. |
| 430 |
value: The line which will be inserted. |
| 431 |
key: For what key the file is being edited. |
| 432 |
""" |
| 433 |
# Read the file |
| 434 |
try: |
| 435 |
with open(filename) as file: |
| 436 |
lines = file.readlines() |
| 437 |
except OSError as err: |
| 438 |
if self._allow_ioerror(err, key): |
| 439 |
lines = [] |
| 440 |
else: |
| 441 |
self.abort(f'tried to configure {key} using a file "{filename}", but could not read it') |
| 442 |
# Find the all matched lines |
| 443 |
matched_indices = [] |
| 444 |
for i, line in enumerate(lines): |
| 445 |
if regexp.search(line): |
| 446 |
matched_indices.append(i) |
| 447 |
if len(matched_indices) > 0: |
| 448 |
insert_line = matched_indices[0] |
| 449 |
else: |
| 450 |
insert_line = 0 |
| 451 |
# Remove all matched lines |
| 452 |
for i in matched_indices[::-1]: |
| 453 |
del lines[i] |
| 454 |
# ...and insert the value |
| 455 |
lines.insert(insert_line, value) |
| 456 |
# Write the changes |
| 457 |
try: |
| 458 |
with open(filename, "w") as file: |
| 459 |
file.writelines(lines) |
| 460 |
except OSError: |
| 461 |
self.abort(f'tried to configure {key} using a file "{filename}", but could not write to it') |
| 462 |
self.msg.append(f"Added 1 line and deleted {len(matched_indices)} line(s) on {filename}") |
| 463 |
|
| 464 |
def _get_value_from_config(self, key, phase): |
| 465 |
filename = self.conf_files[key] |
| 466 |
try: |
| 467 |
with open(filename) as file: |
| 468 |
status = file.read() |
| 469 |
except OSError as err: |
| 470 |
if self._allow_ioerror(err, key): |
| 471 |
if key == "hwclock": |
| 472 |
return "n/a" |
| 473 |
elif key == "adjtime": |
| 474 |
return "UTC" |
| 475 |
elif key == "name": |
| 476 |
return "n/a" |
| 477 |
else: |
| 478 |
self.abort(f'tried to configure {key} using a file "{filename}", but could not read it') |
| 479 |
else: |
| 480 |
try: |
| 481 |
value = self.regexps[key].search(status).group(1) |
| 482 |
except AttributeError: |
| 483 |
if key == "hwclock": |
| 484 |
# If we cannot find UTC in the config that's fine. |
| 485 |
return "n/a" |
| 486 |
elif key == "adjtime": |
| 487 |
# If we cannot find UTC/LOCAL in /etc/cannot that means UTC |
| 488 |
# will be used by default. |
| 489 |
return "UTC" |
| 490 |
elif key == "name": |
| 491 |
if phase == "before": |
| 492 |
# In 'before' phase UTC/LOCAL doesn't need to be set in |
| 493 |
# the timezone config file, so we ignore this error. |
| 494 |
return "n/a" |
| 495 |
else: |
| 496 |
self.abort( |
| 497 |
f'tried to configure {key} using a file "{filename}", but could not find a valid value in it' |
| 498 |
) |
| 499 |
else: |
| 500 |
if key == "hwclock": |
| 501 |
# convert yes/no -> UTC/local |
| 502 |
if self.module.boolean(value): |
| 503 |
value = "UTC" |
| 504 |
else: |
| 505 |
value = "local" |
| 506 |
elif key == "adjtime": |
| 507 |
# convert LOCAL -> local |
| 508 |
if value != "UTC": |
| 509 |
value = value.lower() |
| 510 |
return value |
| 511 |
|
| 512 |
def get(self, key, phase): |
| 513 |
planned = self.value[key]["planned"] |
| 514 |
if key == "hwclock": |
| 515 |
value = self._get_value_from_config(key, phase) |
| 516 |
if value == planned: |
| 517 |
# If the value in the config file is the same as the 'planned' |
| 518 |
# value, we need to check /etc/adjtime. |
| 519 |
value = self._get_value_from_config("adjtime", phase) |
| 520 |
elif key == "name": |
| 521 |
value = self._get_value_from_config(key, phase) |
| 522 |
if value == planned: |
| 523 |
# If the planned values is the same as the one in the config file |
| 524 |
# we need to check if /etc/localtime is also set to the 'planned' zone. |
| 525 |
if os.path.islink("/etc/localtime"): |
| 526 |
# If /etc/localtime is a symlink and is not set to the TZ we 'planned' |
| 527 |
# to set, we need to return the TZ which the symlink points to. |
| 528 |
if os.path.exists("/etc/localtime"): |
| 529 |
# We use readlink() because on some distros zone files are symlinks |
| 530 |
# to other zone files, so it is hard to get which TZ is actually set |
| 531 |
# if we follow the symlink. |
| 532 |
path = os.readlink("/etc/localtime") |
| 533 |
# most linuxes has it in /usr/share/zoneinfo |
| 534 |
# alpine linux links under /etc/zoneinfo |
| 535 |
linktz = re.search(r"(?:/(?:usr/share|etc)/zoneinfo/)(.*)", path, re.MULTILINE) |
| 536 |
if linktz: |
| 537 |
valuelink = linktz.group(1) |
| 538 |
if valuelink != planned: |
| 539 |
value = valuelink |
| 540 |
else: |
| 541 |
# Set current TZ to 'n/a' if the symlink points to a path |
| 542 |
# which isn't a zone file. |
| 543 |
value = "n/a" |
| 544 |
else: |
| 545 |
# Set current TZ to 'n/a' if the symlink to the zone file is broken. |
| 546 |
value = "n/a" |
| 547 |
else: |
| 548 |
# If /etc/localtime is not a symlink best we can do is compare it with |
| 549 |
# the 'planned' zone info file and return 'n/a' if they are different. |
| 550 |
try: |
| 551 |
if not filecmp.cmp("/etc/localtime", f"/usr/share/zoneinfo/{planned}"): |
| 552 |
return "n/a" |
| 553 |
except Exception: |
| 554 |
return "n/a" |
| 555 |
else: |
| 556 |
self.abort(f'unknown parameter "{key}"') |
| 557 |
return value |
| 558 |
|
| 559 |
def set_timezone(self, value): |
| 560 |
self._edit_file( |
| 561 |
filename=self.conf_files["name"], regexp=self.regexps["name"], value=self.tzline_format % value, key="name" |
| 562 |
) |
| 563 |
for cmd in self.update_timezone: |
| 564 |
self.execute(*cmd) |
| 565 |
|
| 566 |
def set_hwclock(self, value): |
| 567 |
if value == "local": |
| 568 |
option = "--localtime" |
| 569 |
utc = "no" |
| 570 |
else: |
| 571 |
option = "--utc" |
| 572 |
utc = "yes" |
| 573 |
if self.conf_files["hwclock"] is not None: |
| 574 |
self._edit_file( |
| 575 |
filename=self.conf_files["hwclock"], regexp=self.regexps["hwclock"], value=f"UTC={utc}\n", key="hwclock" |
| 576 |
) |
| 577 |
self.execute(self.update_hwclock, "--systohc", option, log=True) |
| 578 |
|
| 579 |
def set(self, key, value): |
| 580 |
if key == "name": |
| 581 |
self.set_timezone(value) |
| 582 |
elif key == "hwclock": |
| 583 |
self.set_hwclock(value) |
| 584 |
else: |
| 585 |
self.abort(f'unknown parameter "{key}"') |
| 586 |
|
| 587 |
|
| 588 |
class SmartOSTimezone(Timezone): |
| 589 |
"""This is a Timezone manipulation class for SmartOS instances. |
| 590 |
|
| 591 |
It uses the C(sm-set-timezone) utility to set the timezone, and |
| 592 |
inspects C(/etc/default/init) to determine the current timezone. |
| 593 |
|
| 594 |
NB: A zone needs to be rebooted in order for the change to be |
| 595 |
activated. |
| 596 |
""" |
| 597 |
|
| 598 |
def __init__(self, module): |
| 599 |
super().__init__(module) |
| 600 |
self.settimezone = self.module.get_bin_path("sm-set-timezone", required=False) |
| 601 |
if not self.settimezone: |
| 602 |
module.fail_json(msg="sm-set-timezone not found. Make sure the smtools package is installed.") |
| 603 |
|
| 604 |
def get(self, key, phase): |
| 605 |
"""Lookup the current timezone name in `/etc/default/init`. If anything else |
| 606 |
is requested, or if the TZ field is not set we fail. |
| 607 |
""" |
| 608 |
if key == "name": |
| 609 |
try: |
| 610 |
with open("/etc/default/init") as f: |
| 611 |
for line in f: |
| 612 |
m = re.match("^TZ=(.*)$", line.strip()) |
| 613 |
if m: |
| 614 |
return m.groups()[0] |
| 615 |
except Exception: |
| 616 |
self.module.fail_json(msg="Failed to read /etc/default/init") |
| 617 |
else: |
| 618 |
self.module.fail_json(msg=f"{key} is not a supported option on target platform") |
| 619 |
|
| 620 |
def set(self, key, value): |
| 621 |
"""Set the requested timezone through sm-set-timezone, an invalid timezone name |
| 622 |
will be rejected and we have no further input validation to perform. |
| 623 |
""" |
| 624 |
if key == "name": |
| 625 |
cmd = ["sm-set-timezone", value] |
| 626 |
|
| 627 |
(rc, stdout, stderr) = self.module.run_command(cmd) |
| 628 |
|
| 629 |
if rc != 0: |
| 630 |
self.module.fail_json(msg=stderr) |
| 631 |
|
| 632 |
# sm-set-timezone knows no state and will always set the timezone. |
| 633 |
# XXX: https://github.com/joyent/smtools/pull/2 |
| 634 |
m = re.match(rf"^\* Changed (to)? timezone (to)? ({value}).*", stdout.splitlines()[1]) |
| 635 |
if not (m and m.groups()[-1] == value): |
| 636 |
self.module.fail_json(msg="Failed to set timezone") |
| 637 |
else: |
| 638 |
self.module.fail_json(msg=f"{key} is not a supported option on target platform") |
| 639 |
|
| 640 |
|
| 641 |
class DarwinTimezone(Timezone): |
| 642 |
"""This is the timezone implementation for Darwin which, unlike other *BSD |
| 643 |
implementations, uses the `systemsetup` command on Darwin to check/set |
| 644 |
the timezone. |
| 645 |
""" |
| 646 |
|
| 647 |
regexps = dict(name=re.compile(r"^\s*Time ?Zone\s*:\s*([^\s]+)", re.MULTILINE)) |
| 648 |
|
| 649 |
def __init__(self, module): |
| 650 |
super().__init__(module) |
| 651 |
self.systemsetup = module.get_bin_path("systemsetup", required=True) |
| 652 |
self.status = dict() |
| 653 |
# Validate given timezone |
| 654 |
if "name" in self.value: |
| 655 |
self._verify_timezone() |
| 656 |
|
| 657 |
def _get_current_timezone(self, phase): |
| 658 |
"""Lookup the current timezone via `systemsetup -gettimezone`.""" |
| 659 |
if phase not in self.status: |
| 660 |
self.status[phase] = self.execute(self.systemsetup, "-gettimezone") |
| 661 |
return self.status[phase] |
| 662 |
|
| 663 |
def _verify_timezone(self): |
| 664 |
tz = self.value["name"]["planned"] |
| 665 |
# Lookup the list of supported timezones via `systemsetup -listtimezones`. |
| 666 |
# Note: Skip the first line that contains the label 'Time Zones:' |
| 667 |
out = self.execute(self.systemsetup, "-listtimezones").splitlines()[1:] |
| 668 |
tz_list = [x.strip() for x in out] |
| 669 |
if tz not in tz_list: |
| 670 |
self.abort(f'given timezone "{tz}" is not available') |
| 671 |
return tz |
| 672 |
|
| 673 |
def get(self, key, phase): |
| 674 |
if key == "name": |
| 675 |
status = self._get_current_timezone(phase) |
| 676 |
value = self.regexps[key].search(status).group(1) |
| 677 |
return value |
| 678 |
else: |
| 679 |
self.module.fail_json(msg=f"{key} is not a supported option on target platform") |
| 680 |
|
| 681 |
def set(self, key, value): |
| 682 |
if key == "name": |
| 683 |
self.execute(self.systemsetup, "-settimezone", value, log=True) |
| 684 |
else: |
| 685 |
self.module.fail_json(msg=f"{key} is not a supported option on target platform") |
| 686 |
|
| 687 |
|
| 688 |
class BSDTimezone(Timezone): |
| 689 |
"""This is the timezone implementation for *BSD which works simply through |
| 690 |
updating the `/etc/localtime` symlink to point to a valid timezone name under |
| 691 |
`/usr/share/zoneinfo`. |
| 692 |
""" |
| 693 |
|
| 694 |
def __init__(self, module): |
| 695 |
super().__init__(module) |
| 696 |
|
| 697 |
def __get_timezone(self): |
| 698 |
zoneinfo_dir = "/usr/share/zoneinfo/" |
| 699 |
localtime_file = "/etc/localtime" |
| 700 |
|
| 701 |
# Strategy 1: |
| 702 |
# If /etc/localtime does not exist, assume the timezone is UTC. |
| 703 |
if not os.path.exists(localtime_file): |
| 704 |
self.module.warn("Could not read /etc/localtime. Assuming UTC.") |
| 705 |
return "UTC" |
| 706 |
|
| 707 |
# Strategy 2: |
| 708 |
# Follow symlink of /etc/localtime |
| 709 |
zoneinfo_file = localtime_file |
| 710 |
while not zoneinfo_file.startswith(zoneinfo_dir): |
| 711 |
try: |
| 712 |
zoneinfo_file = os.readlink(localtime_file) |
| 713 |
except OSError: |
| 714 |
# OSError means "end of symlink chain" or broken link. |
| 715 |
break |
| 716 |
else: |
| 717 |
return zoneinfo_file.replace(zoneinfo_dir, "") |
| 718 |
|
| 719 |
# Strategy 3: |
| 720 |
# (If /etc/localtime is not symlinked) |
| 721 |
# Check all files in /usr/share/zoneinfo and return first non-link match. |
| 722 |
for dname, dummy, fnames in sorted(os.walk(zoneinfo_dir)): |
| 723 |
for fname in sorted(fnames): |
| 724 |
zoneinfo_file = os.path.join(dname, fname) |
| 725 |
if not os.path.islink(zoneinfo_file) and filecmp.cmp(zoneinfo_file, localtime_file): |
| 726 |
return zoneinfo_file.replace(zoneinfo_dir, "") |
| 727 |
|
| 728 |
# Strategy 4: |
| 729 |
# As a fall-back, return 'UTC' as default assumption. |
| 730 |
self.module.warn("Could not identify timezone name from /etc/localtime. Assuming UTC.") |
| 731 |
return "UTC" |
| 732 |
|
| 733 |
def get(self, key, phase): |
| 734 |
"""Lookup the current timezone by resolving `/etc/localtime`.""" |
| 735 |
if key == "name": |
| 736 |
return self.__get_timezone() |
| 737 |
else: |
| 738 |
self.module.fail_json(msg=f"{key} is not a supported option on target platform") |
| 739 |
|
| 740 |
def set(self, key, value): |
| 741 |
if key == "name": |
| 742 |
# First determine if the requested timezone is valid by looking in |
| 743 |
# the zoneinfo directory. |
| 744 |
zonefile = f"/usr/share/zoneinfo/{value}" |
| 745 |
try: |
| 746 |
if not os.path.isfile(zonefile): |
| 747 |
self.module.fail_json(msg=f"{value} is not a recognized timezone") |
| 748 |
except Exception: |
| 749 |
self.module.fail_json(msg=f"Failed to stat {zonefile}") |
| 750 |
|
| 751 |
# Now (somewhat) atomically update the symlink by creating a new |
| 752 |
# symlink and move it into place. Otherwise we have to remove the |
| 753 |
# original symlink and create the new symlink, however that would |
| 754 |
# create a race condition in case another process tries to read |
| 755 |
# /etc/localtime between removal and creation. |
| 756 |
suffix = "".join([random.choice(string.ascii_letters + string.digits) for x in range(0, 10)]) |
| 757 |
new_localtime = f"/etc/localtime.{suffix}" |
| 758 |
|
| 759 |
try: |
| 760 |
os.symlink(zonefile, new_localtime) |
| 761 |
os.rename(new_localtime, "/etc/localtime") |
| 762 |
except Exception: |
| 763 |
os.remove(new_localtime) |
| 764 |
self.module.fail_json(msg="Could not update /etc/localtime") |
| 765 |
else: |
| 766 |
self.module.fail_json(msg=f"{key} is not a supported option on target platform") |
| 767 |
|
| 768 |
|
| 769 |
class AIXTimezone(Timezone): |
| 770 |
"""This is a Timezone manipulation class for AIX instances. |
| 771 |
|
| 772 |
It uses the C(chtz) utility to set the timezone, and |
| 773 |
inspects C(/etc/environment) to determine the current timezone. |
| 774 |
|
| 775 |
While AIX time zones can be set using two formats (POSIX and |
| 776 |
Olson) the preferred method is Olson. |
| 777 |
See the following article for more information: |
| 778 |
https://developer.ibm.com/articles/au-aix-posix/ |
| 779 |
|
| 780 |
NB: AIX needs to be rebooted in order for the change to be |
| 781 |
activated. |
| 782 |
""" |
| 783 |
|
| 784 |
def __init__(self, module): |
| 785 |
super().__init__(module) |
| 786 |
self.settimezone = self.module.get_bin_path("chtz", required=True) |
| 787 |
|
| 788 |
def __get_timezone(self): |
| 789 |
"""Return the current value of TZ= in /etc/environment""" |
| 790 |
try: |
| 791 |
with open("/etc/environment") as f: |
| 792 |
etcenvironment = f.read() |
| 793 |
except Exception: |
| 794 |
self.module.fail_json(msg="Issue reading contents of /etc/environment") |
| 795 |
|
| 796 |
match = re.search(r"^TZ=(.*)$", etcenvironment, re.MULTILINE) |
| 797 |
if match: |
| 798 |
return match.group(1) |
| 799 |
else: |
| 800 |
return None |
| 801 |
|
| 802 |
def get(self, key, phase): |
| 803 |
"""Lookup the current timezone name in `/etc/environment`. If anything else |
| 804 |
is requested, or if the TZ field is not set we fail. |
| 805 |
""" |
| 806 |
if key == "name": |
| 807 |
return self.__get_timezone() |
| 808 |
else: |
| 809 |
self.module.fail_json(msg=f"{key} is not a supported option on target platform") |
| 810 |
|
| 811 |
def set(self, key, value): |
| 812 |
"""Set the requested timezone through chtz, an invalid timezone name |
| 813 |
will be rejected and we have no further input validation to perform. |
| 814 |
""" |
| 815 |
if key == "name": |
| 816 |
# chtz seems to always return 0 on AIX 7.2, even for invalid timezone values. |
| 817 |
# It will only return non-zero if the chtz command itself fails, it does not check for |
| 818 |
# valid timezones. We need to perform a basic check to confirm that the timezone |
| 819 |
# definition exists in /usr/share/lib/zoneinfo |
| 820 |
# This does mean that we can only support Olson for now. The below commented out regex |
| 821 |
# detects Olson date formats, so in the future we could detect Posix or Olson and |
| 822 |
# act accordingly. |
| 823 |
|
| 824 |
# regex_olson = re.compile('^([a-z0-9_\-\+]+\/?)+$', re.IGNORECASE) |
| 825 |
# if not regex_olson.match(value): |
| 826 |
# msg = 'Supplied timezone (%s) does not appear to a be valid Olson string' % value |
| 827 |
# self.module.fail_json(msg=msg) |
| 828 |
|
| 829 |
# First determine if the requested timezone is valid by looking in the zoneinfo |
| 830 |
# directory. |
| 831 |
zonefile = f"/usr/share/lib/zoneinfo/{value}" |
| 832 |
try: |
| 833 |
if not os.path.isfile(zonefile): |
| 834 |
self.module.fail_json(msg=f"{value} is not a recognized timezone.") |
| 835 |
except Exception: |
| 836 |
self.module.fail_json(msg=f"Failed to check {zonefile}.") |
| 837 |
|
| 838 |
# Now set the TZ using chtz |
| 839 |
cmd = ["chtz", value] |
| 840 |
(rc, stdout, stderr) = self.module.run_command(cmd) |
| 841 |
|
| 842 |
if rc != 0: |
| 843 |
self.module.fail_json(msg=stderr) |
| 844 |
|
| 845 |
# The best condition check we can do is to check the value of TZ after making the |
| 846 |
# change. |
| 847 |
TZ = self.__get_timezone() |
| 848 |
if value != TZ: |
| 849 |
msg = f"TZ value does not match post-change (Actual: {TZ}, Expected: {value})." |
| 850 |
self.module.fail_json(msg=msg) |
| 851 |
|
| 852 |
else: |
| 853 |
self.module.fail_json(msg=f"{key} is not a supported option on target platform") |
| 854 |
|
| 855 |
|
| 856 |
def main(): |
| 857 |
# Construct 'module' and 'tz' |
| 858 |
module = AnsibleModule( |
| 859 |
argument_spec=dict( |
| 860 |
hwclock=dict(type="str", choices=["local", "UTC"], aliases=["rtc"]), |
| 861 |
name=dict(type="str"), |
| 862 |
), |
| 863 |
required_one_of=[["hwclock", "name"]], |
| 864 |
supports_check_mode=True, |
| 865 |
) |
| 866 |
module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"} |
| 867 |
tz = Timezone(module) |
| 868 |
|
| 869 |
# Check the current state |
| 870 |
tz.check(phase="before") |
| 871 |
if module.check_mode: |
| 872 |
diff = tz.diff("before", "planned") |
| 873 |
# In check mode, 'planned' state is treated as 'after' state |
| 874 |
diff["after"] = diff.pop("planned") |
| 875 |
else: |
| 876 |
# Make change |
| 877 |
tz.change() |
| 878 |
# Check the current state |
| 879 |
tz.check(phase="after") |
| 880 |
# Examine if the current state matches planned state |
| 881 |
(after, planned) = tz.diff("after", "planned").values() |
| 882 |
if after != planned: |
| 883 |
tz.abort(f"still not desired state, though changes have made - planned: {planned}, after: {after}") |
| 884 |
diff = tz.diff("before", "after") |
| 885 |
|
| 886 |
changed = diff["before"] != diff["after"] |
| 887 |
if len(tz.msg) > 0: |
| 888 |
module.exit_json(changed=changed, diff=diff, msg="\n".join(tz.msg)) |
| 889 |
else: |
| 890 |
module.exit_json(changed=changed, diff=diff) |
| 891 |
|
| 892 |
|
| 893 |
if __name__ == "__main__": |
| 894 |
main() |