| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright: (c) 2013, Hiroaki Nakamura <[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 = """ |
| 10 |
--- |
| 11 |
module: hostname |
| 12 |
author: |
| 13 |
- Adrian Likins (@alikins) |
| 14 |
- Hideki Saito (@saito-hideki) |
| 15 |
version_added: "1.4" |
| 16 |
short_description: Manage hostname |
| 17 |
requirements: [ hostname ] |
| 18 |
description: |
| 19 |
- Set system's hostname. Supports most OSs/Distributions including those using C(systemd). |
| 20 |
- Windows, HP-UX, and AIX are not currently supported. |
| 21 |
notes: |
| 22 |
- This module does B(NOT) modify C(/etc/hosts). You need to modify it yourself using other modules such as M(ansible.builtin.template) |
| 23 |
or M(ansible.builtin.replace). |
| 24 |
- On macOS, this module uses C(scutil) to set C(HostName), C(ComputerName), and C(LocalHostName). Since C(LocalHostName) |
| 25 |
cannot contain spaces or most special characters, this module will replace characters when setting C(LocalHostName). |
| 26 |
options: |
| 27 |
name: |
| 28 |
description: |
| 29 |
- Name of the host. |
| 30 |
- If the value is a fully qualified domain name that does not resolve from the given host, |
| 31 |
this will cause the module to hang for a few seconds while waiting for the name resolution attempt to timeout. |
| 32 |
type: str |
| 33 |
required: true |
| 34 |
use: |
| 35 |
description: |
| 36 |
- Which strategy to use to update the hostname. |
| 37 |
- If not set we try to autodetect, but this can be problematic, particularly with containers as they can present misleading information. |
| 38 |
- Note that V(systemd) should be specified for RHEL/EL/CentOS 7+. Older distributions should use V(redhat). |
| 39 |
choices: ['alpine', 'debian', 'freebsd', 'generic', 'macos', 'macosx', 'darwin', 'openbsd', 'openrc', 'redhat', 'sles', 'solaris', 'systemd'] |
| 40 |
type: str |
| 41 |
version_added: '2.9' |
| 42 |
extends_documentation_fragment: |
| 43 |
- action_common_attributes |
| 44 |
- action_common_attributes.facts |
| 45 |
attributes: |
| 46 |
check_mode: |
| 47 |
support: full |
| 48 |
diff_mode: |
| 49 |
support: full |
| 50 |
facts: |
| 51 |
support: full |
| 52 |
platform: |
| 53 |
platforms: posix |
| 54 |
""" |
| 55 |
|
| 56 |
EXAMPLES = """ |
| 57 |
- name: Set a hostname |
| 58 |
ansible.builtin.hostname: |
| 59 |
name: web01 |
| 60 |
|
| 61 |
- name: Set a hostname specifying strategy |
| 62 |
ansible.builtin.hostname: |
| 63 |
name: web01 |
| 64 |
use: systemd |
| 65 |
""" |
| 66 |
|
| 67 |
import os |
| 68 |
import platform |
| 69 |
import socket |
| 70 |
import typing as t |
| 71 |
|
| 72 |
from ansible.module_utils.basic import ( |
| 73 |
AnsibleModule, |
| 74 |
get_distribution, |
| 75 |
get_distribution_version, |
| 76 |
) |
| 77 |
from ansible.module_utils.common.sys_info import get_platform_subclass |
| 78 |
from ansible.module_utils.facts.system.service_mgr import ServiceMgrFactCollector |
| 79 |
from ansible.module_utils.facts.utils import get_file_lines, get_file_content |
| 80 |
from ansible.module_utils.common.text.converters import to_native, to_text |
| 81 |
|
| 82 |
STRATS = { |
| 83 |
'alpine': 'Alpine', |
| 84 |
'debian': 'Systemd', |
| 85 |
'freebsd': 'FreeBSD', |
| 86 |
'generic': 'Base', |
| 87 |
'macos': 'Darwin', |
| 88 |
'macosx': 'Darwin', |
| 89 |
'darwin': 'Darwin', |
| 90 |
'openbsd': 'OpenBSD', |
| 91 |
'openrc': 'OpenRC', |
| 92 |
'redhat': 'RedHat', |
| 93 |
'sles': 'SLES', |
| 94 |
'solaris': 'Solaris', |
| 95 |
'systemd': 'Systemd', |
| 96 |
} |
| 97 |
|
| 98 |
|
| 99 |
class BaseStrategy(object): |
| 100 |
def __init__(self, module): |
| 101 |
self.module = module |
| 102 |
self.changed = False |
| 103 |
|
| 104 |
def update_current_and_permanent_hostname(self): |
| 105 |
self.update_current_hostname() |
| 106 |
self.update_permanent_hostname() |
| 107 |
return self.changed |
| 108 |
|
| 109 |
def update_current_hostname(self): |
| 110 |
name = self.module.params['name'] |
| 111 |
current_name = self.get_current_hostname() |
| 112 |
if current_name != name: |
| 113 |
if not self.module.check_mode: |
| 114 |
self.set_current_hostname(name) |
| 115 |
self.changed = True |
| 116 |
|
| 117 |
def update_permanent_hostname(self): |
| 118 |
name = self.module.params['name'] |
| 119 |
permanent_name = self.get_permanent_hostname() |
| 120 |
if permanent_name != name: |
| 121 |
if not self.module.check_mode: |
| 122 |
self.set_permanent_hostname(name) |
| 123 |
self.changed = True |
| 124 |
|
| 125 |
def get_current_hostname(self): |
| 126 |
return self.get_permanent_hostname() |
| 127 |
|
| 128 |
def set_current_hostname(self, name): |
| 129 |
pass |
| 130 |
|
| 131 |
def get_permanent_hostname(self): |
| 132 |
raise NotImplementedError |
| 133 |
|
| 134 |
def set_permanent_hostname(self, name): |
| 135 |
raise NotImplementedError |
| 136 |
|
| 137 |
|
| 138 |
class UnimplementedStrategy(BaseStrategy): |
| 139 |
def update_current_and_permanent_hostname(self): |
| 140 |
self.unimplemented_error() |
| 141 |
|
| 142 |
def update_current_hostname(self): |
| 143 |
self.unimplemented_error() |
| 144 |
|
| 145 |
def update_permanent_hostname(self): |
| 146 |
self.unimplemented_error() |
| 147 |
|
| 148 |
def get_current_hostname(self): |
| 149 |
self.unimplemented_error() |
| 150 |
|
| 151 |
def set_current_hostname(self, name): |
| 152 |
self.unimplemented_error() |
| 153 |
|
| 154 |
def get_permanent_hostname(self): |
| 155 |
self.unimplemented_error() |
| 156 |
|
| 157 |
def set_permanent_hostname(self, name): |
| 158 |
self.unimplemented_error() |
| 159 |
|
| 160 |
def unimplemented_error(self): |
| 161 |
system = platform.system() |
| 162 |
distribution = get_distribution() |
| 163 |
if distribution is not None: |
| 164 |
msg_platform = '%s (%s)' % (system, distribution) |
| 165 |
else: |
| 166 |
msg_platform = system |
| 167 |
self.module.fail_json( |
| 168 |
msg='hostname module cannot be used on platform %s' % msg_platform) |
| 169 |
|
| 170 |
|
| 171 |
class CommandStrategy(BaseStrategy): |
| 172 |
COMMAND = 'hostname' |
| 173 |
|
| 174 |
def __init__(self, module): |
| 175 |
super(CommandStrategy, self).__init__(module) |
| 176 |
self.hostname_cmd = self.module.get_bin_path(self.COMMAND, True) |
| 177 |
|
| 178 |
def get_current_hostname(self): |
| 179 |
cmd = [self.hostname_cmd] |
| 180 |
rc, out, err = self.module.run_command(cmd) |
| 181 |
if rc != 0: |
| 182 |
self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) |
| 183 |
return to_native(out).strip() |
| 184 |
|
| 185 |
def set_current_hostname(self, name): |
| 186 |
cmd = [self.hostname_cmd, name] |
| 187 |
rc, out, err = self.module.run_command(cmd) |
| 188 |
if rc != 0: |
| 189 |
self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) |
| 190 |
|
| 191 |
def get_permanent_hostname(self): |
| 192 |
return 'UNKNOWN' |
| 193 |
|
| 194 |
def set_permanent_hostname(self, name): |
| 195 |
pass |
| 196 |
|
| 197 |
|
| 198 |
class FileStrategy(BaseStrategy): |
| 199 |
FILE = '/etc/hostname' |
| 200 |
|
| 201 |
def get_permanent_hostname(self): |
| 202 |
if not os.path.isfile(self.FILE): |
| 203 |
return '' |
| 204 |
|
| 205 |
try: |
| 206 |
return get_file_content(self.FILE, default='', strip=True) |
| 207 |
except Exception as e: |
| 208 |
self.module.fail_json( |
| 209 |
msg="failed to read hostname: %s" % to_native(e)) |
| 210 |
|
| 211 |
def set_permanent_hostname(self, name): |
| 212 |
try: |
| 213 |
with open(self.FILE, 'w+') as f: |
| 214 |
f.write("%s\n" % name) |
| 215 |
except Exception as e: |
| 216 |
self.module.fail_json(msg="failed to update hostname: %s" % to_native(e)) |
| 217 |
|
| 218 |
|
| 219 |
class SLESStrategy(FileStrategy): |
| 220 |
""" |
| 221 |
This is a SLES Hostname strategy class - it edits the |
| 222 |
/etc/HOSTNAME file. |
| 223 |
""" |
| 224 |
FILE = '/etc/HOSTNAME' |
| 225 |
|
| 226 |
|
| 227 |
class RedHatStrategy(BaseStrategy): |
| 228 |
""" |
| 229 |
This is a Redhat Hostname strategy class - it edits the |
| 230 |
/etc/sysconfig/network file. |
| 231 |
""" |
| 232 |
NETWORK_FILE = '/etc/sysconfig/network' |
| 233 |
|
| 234 |
def get_permanent_hostname(self): |
| 235 |
try: |
| 236 |
for line in get_file_lines(self.NETWORK_FILE): |
| 237 |
line = to_native(line).strip() |
| 238 |
if line.startswith('HOSTNAME'): |
| 239 |
k, v = line.split('=') |
| 240 |
return v.strip() |
| 241 |
self.module.fail_json( |
| 242 |
"Unable to locate HOSTNAME entry in %s" % self.NETWORK_FILE |
| 243 |
) |
| 244 |
except Exception as e: |
| 245 |
self.module.fail_json( |
| 246 |
msg="failed to read hostname: %s" % to_native(e)) |
| 247 |
|
| 248 |
def set_permanent_hostname(self, name): |
| 249 |
try: |
| 250 |
lines = [] |
| 251 |
found = False |
| 252 |
content = get_file_content(self.NETWORK_FILE, strip=False) or "" |
| 253 |
for line in content.splitlines(True): |
| 254 |
line = to_native(line) |
| 255 |
if line.strip().startswith('HOSTNAME'): |
| 256 |
lines.append("HOSTNAME=%s\n" % name) |
| 257 |
found = True |
| 258 |
else: |
| 259 |
lines.append(line) |
| 260 |
if not found: |
| 261 |
lines.append("HOSTNAME=%s\n" % name) |
| 262 |
with open(self.NETWORK_FILE, 'w+') as f: |
| 263 |
f.writelines(lines) |
| 264 |
except Exception as e: |
| 265 |
self.module.fail_json(msg="failed to update hostname: %s" % to_native(e)) |
| 266 |
|
| 267 |
|
| 268 |
class AlpineStrategy(FileStrategy): |
| 269 |
""" |
| 270 |
This is a Alpine Linux Hostname manipulation strategy class - it edits |
| 271 |
the /etc/hostname file then run hostname -F /etc/hostname. |
| 272 |
""" |
| 273 |
|
| 274 |
FILE = '/etc/hostname' |
| 275 |
COMMAND = 'hostname' |
| 276 |
|
| 277 |
def set_current_hostname(self, name): |
| 278 |
super(AlpineStrategy, self).set_current_hostname(name) |
| 279 |
hostname_cmd = self.module.get_bin_path(self.COMMAND, True) |
| 280 |
|
| 281 |
cmd = [hostname_cmd, '-F', self.FILE] |
| 282 |
rc, out, err = self.module.run_command(cmd) |
| 283 |
if rc != 0: |
| 284 |
self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) |
| 285 |
|
| 286 |
|
| 287 |
class SystemdStrategy(BaseStrategy): |
| 288 |
""" |
| 289 |
This is a Systemd hostname manipulation strategy class - it uses |
| 290 |
the hostnamectl command. |
| 291 |
""" |
| 292 |
|
| 293 |
COMMAND = "hostnamectl" |
| 294 |
|
| 295 |
def __init__(self, module): |
| 296 |
super(SystemdStrategy, self).__init__(module) |
| 297 |
self.hostnamectl_cmd = self.module.get_bin_path(self.COMMAND, True) |
| 298 |
|
| 299 |
def get_current_hostname(self): |
| 300 |
cmd = [self.hostnamectl_cmd, '--transient', 'status'] |
| 301 |
rc, out, err = self.module.run_command(cmd) |
| 302 |
if rc != 0: |
| 303 |
self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) |
| 304 |
return to_native(out).strip() |
| 305 |
|
| 306 |
def set_current_hostname(self, name): |
| 307 |
if len(name) > 64: |
| 308 |
self.module.fail_json(msg="name cannot be longer than 64 characters on systemd servers, try a shorter name") |
| 309 |
cmd = [self.hostnamectl_cmd, '--transient', 'set-hostname', name] |
| 310 |
rc, out, err = self.module.run_command(cmd) |
| 311 |
if rc != 0: |
| 312 |
self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) |
| 313 |
|
| 314 |
def get_permanent_hostname(self): |
| 315 |
cmd = [self.hostnamectl_cmd, '--static', 'status'] |
| 316 |
rc, out, err = self.module.run_command(cmd) |
| 317 |
if rc != 0: |
| 318 |
self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) |
| 319 |
return to_native(out).strip() |
| 320 |
|
| 321 |
def set_permanent_hostname(self, name): |
| 322 |
if len(name) > 64: |
| 323 |
self.module.fail_json(msg="name cannot be longer than 64 characters on systemd servers, try a shorter name") |
| 324 |
cmd = [self.hostnamectl_cmd, '--pretty', '--static', 'set-hostname', name] |
| 325 |
rc, out, err = self.module.run_command(cmd) |
| 326 |
if rc != 0: |
| 327 |
self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) |
| 328 |
|
| 329 |
def update_current_and_permanent_hostname(self): |
| 330 |
# Must set the permanent hostname prior to current to avoid NetworkManager complaints |
| 331 |
# about setting the hostname outside of NetworkManager |
| 332 |
self.update_permanent_hostname() |
| 333 |
self.update_current_hostname() |
| 334 |
return self.changed |
| 335 |
|
| 336 |
|
| 337 |
class OpenRCStrategy(BaseStrategy): |
| 338 |
""" |
| 339 |
This is a Gentoo (OpenRC) Hostname manipulation strategy class - it edits |
| 340 |
the /etc/conf.d/hostname file. |
| 341 |
""" |
| 342 |
|
| 343 |
FILE = '/etc/conf.d/hostname' |
| 344 |
|
| 345 |
def get_permanent_hostname(self): |
| 346 |
if not os.path.isfile(self.FILE): |
| 347 |
return '' |
| 348 |
|
| 349 |
try: |
| 350 |
for line in get_file_lines(self.FILE): |
| 351 |
line = line.strip() |
| 352 |
if line.startswith('hostname='): |
| 353 |
return line[10:].strip('"') |
| 354 |
except Exception as e: |
| 355 |
self.module.fail_json(msg="failed to read hostname: %s" % to_native(e)) |
| 356 |
|
| 357 |
def set_permanent_hostname(self, name): |
| 358 |
try: |
| 359 |
lines = [x.strip() for x in get_file_lines(self.FILE)] |
| 360 |
|
| 361 |
for i, line in enumerate(lines): |
| 362 |
if line.startswith('hostname='): |
| 363 |
lines[i] = 'hostname="%s"' % name |
| 364 |
break |
| 365 |
|
| 366 |
with open(self.FILE, 'w') as f: |
| 367 |
f.write('\n'.join(lines) + '\n') |
| 368 |
except Exception as e: |
| 369 |
self.module.fail_json(msg="failed to update hostname: %s" % to_native(e)) |
| 370 |
|
| 371 |
|
| 372 |
class OpenBSDStrategy(FileStrategy): |
| 373 |
""" |
| 374 |
This is a OpenBSD family Hostname manipulation strategy class - it edits |
| 375 |
the /etc/myname file for the permanent hostname and executes hostname |
| 376 |
command for the current hostname. |
| 377 |
""" |
| 378 |
|
| 379 |
FILE = '/etc/myname' |
| 380 |
COMMAND = "hostname" |
| 381 |
|
| 382 |
def __init__(self, module): |
| 383 |
super(OpenBSDStrategy, self).__init__(module) |
| 384 |
self.hostname_cmd = self.module.get_bin_path(self.COMMAND, True) |
| 385 |
|
| 386 |
def get_current_hostname(self): |
| 387 |
cmd = [self.hostname_cmd] |
| 388 |
rc, out, err = self.module.run_command(cmd) |
| 389 |
if rc != 0: |
| 390 |
self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) |
| 391 |
return to_native(out).strip() |
| 392 |
|
| 393 |
def set_current_hostname(self, name): |
| 394 |
cmd = [self.hostname_cmd, name] |
| 395 |
rc, out, err = self.module.run_command(cmd) |
| 396 |
if rc != 0: |
| 397 |
self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) |
| 398 |
|
| 399 |
|
| 400 |
class SolarisStrategy(BaseStrategy): |
| 401 |
""" |
| 402 |
This is a Solaris11 or later Hostname manipulation strategy class - it |
| 403 |
execute hostname command. |
| 404 |
""" |
| 405 |
|
| 406 |
COMMAND = "hostname" |
| 407 |
|
| 408 |
def __init__(self, module): |
| 409 |
super(SolarisStrategy, self).__init__(module) |
| 410 |
self.hostname_cmd = self.module.get_bin_path(self.COMMAND, True) |
| 411 |
|
| 412 |
def set_current_hostname(self, name): |
| 413 |
cmd_option = '-t' |
| 414 |
cmd = [self.hostname_cmd, cmd_option, name] |
| 415 |
rc, out, err = self.module.run_command(cmd) |
| 416 |
if rc != 0: |
| 417 |
self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) |
| 418 |
|
| 419 |
def get_permanent_hostname(self): |
| 420 |
fmri = 'svc:/system/identity:node' |
| 421 |
pattern = 'config/nodename' |
| 422 |
cmd = '/usr/sbin/svccfg -s %s listprop -o value %s' % (fmri, pattern) |
| 423 |
rc, out, err = self.module.run_command(cmd, use_unsafe_shell=True) |
| 424 |
if rc != 0: |
| 425 |
self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) |
| 426 |
return to_native(out).strip() |
| 427 |
|
| 428 |
def set_permanent_hostname(self, name): |
| 429 |
cmd = [self.hostname_cmd, name] |
| 430 |
rc, out, err = self.module.run_command(cmd) |
| 431 |
if rc != 0: |
| 432 |
self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) |
| 433 |
|
| 434 |
|
| 435 |
class FreeBSDStrategy(BaseStrategy): |
| 436 |
""" |
| 437 |
This is a FreeBSD hostname manipulation strategy class - it edits |
| 438 |
the /etc/rc.conf.d/hostname file. |
| 439 |
""" |
| 440 |
|
| 441 |
FILE = '/etc/rc.conf.d/hostname' |
| 442 |
COMMAND = "hostname" |
| 443 |
|
| 444 |
def __init__(self, module): |
| 445 |
super(FreeBSDStrategy, self).__init__(module) |
| 446 |
self.hostname_cmd = self.module.get_bin_path(self.COMMAND, True) |
| 447 |
|
| 448 |
def get_current_hostname(self): |
| 449 |
cmd = [self.hostname_cmd] |
| 450 |
rc, out, err = self.module.run_command(cmd) |
| 451 |
if rc != 0: |
| 452 |
self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) |
| 453 |
return to_native(out).strip() |
| 454 |
|
| 455 |
def set_current_hostname(self, name): |
| 456 |
cmd = [self.hostname_cmd, name] |
| 457 |
rc, out, err = self.module.run_command(cmd) |
| 458 |
if rc != 0: |
| 459 |
self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err)) |
| 460 |
|
| 461 |
def get_permanent_hostname(self): |
| 462 |
if not os.path.isfile(self.FILE): |
| 463 |
return '' |
| 464 |
|
| 465 |
try: |
| 466 |
for line in get_file_lines(self.FILE): |
| 467 |
line = line.strip() |
| 468 |
if line.startswith('hostname='): |
| 469 |
return line[10:].strip('"') |
| 470 |
except Exception as e: |
| 471 |
self.module.fail_json(msg="failed to read hostname: %s" % to_native(e)) |
| 472 |
|
| 473 |
def set_permanent_hostname(self, name): |
| 474 |
try: |
| 475 |
if os.path.isfile(self.FILE): |
| 476 |
lines = [x.strip() for x in get_file_lines(self.FILE)] |
| 477 |
|
| 478 |
for i, line in enumerate(lines): |
| 479 |
if line.startswith('hostname='): |
| 480 |
lines[i] = 'hostname="%s"' % name |
| 481 |
break |
| 482 |
else: |
| 483 |
lines = ['hostname="%s"' % name] |
| 484 |
|
| 485 |
with open(self.FILE, 'w') as f: |
| 486 |
f.write('\n'.join(lines) + '\n') |
| 487 |
except Exception as e: |
| 488 |
self.module.fail_json(msg="failed to update hostname: %s" % to_native(e)) |
| 489 |
|
| 490 |
|
| 491 |
class DarwinStrategy(BaseStrategy): |
| 492 |
""" |
| 493 |
This is a macOS hostname manipulation strategy class. It uses |
| 494 |
/usr/sbin/scutil to set ComputerName, HostName, and LocalHostName. |
| 495 |
|
| 496 |
HostName corresponds to what most platforms consider to be hostname. |
| 497 |
It controls the name used on the command line and SSH. |
| 498 |
|
| 499 |
However, macOS also has LocalHostName and ComputerName settings. |
| 500 |
LocalHostName controls the Bonjour/ZeroConf name, used by services |
| 501 |
like AirDrop. This class implements a method, _scrub_hostname(), that mimics |
| 502 |
the transformations macOS makes on hostnames when entered in the Sharing |
| 503 |
preference pane. It replaces spaces with dashes and removes all special |
| 504 |
characters. |
| 505 |
|
| 506 |
ComputerName is the name used for user-facing GUI services, like the |
| 507 |
System Preferences/Sharing pane and when users connect to the Mac over the network. |
| 508 |
""" |
| 509 |
|
| 510 |
def __init__(self, module): |
| 511 |
super(DarwinStrategy, self).__init__(module) |
| 512 |
|
| 513 |
self.scutil = self.module.get_bin_path('scutil', True) |
| 514 |
self.name_types = ('HostName', 'ComputerName', 'LocalHostName') |
| 515 |
self.scrubbed_name = self._scrub_hostname(self.module.params['name']) |
| 516 |
|
| 517 |
def _scrub_hostname(self, name): |
| 518 |
""" |
| 519 |
LocalHostName only accepts valid DNS characters while HostName and ComputerName |
| 520 |
accept a much wider range of characters. This function aims to mimic how macOS |
| 521 |
translates a friendly name to the LocalHostName. |
| 522 |
""" |
| 523 |
|
| 524 |
# Replace all these characters with a single dash |
| 525 |
name = to_text(name) |
| 526 |
replace_chars = u'\'"~`!@#$%^&*(){}[]/=?+\\|-_ ' |
| 527 |
delete_chars = u".'" |
| 528 |
table = str.maketrans(replace_chars, '-' * len(replace_chars), delete_chars) |
| 529 |
name = name.translate(table) |
| 530 |
|
| 531 |
# Replace multiple dashes with a single dash |
| 532 |
while '-' * 2 in name: |
| 533 |
name = name.replace('-' * 2, '') |
| 534 |
|
| 535 |
name = name.rstrip('-') |
| 536 |
return name |
| 537 |
|
| 538 |
def get_current_hostname(self): |
| 539 |
cmd = [self.scutil, '--get', 'HostName'] |
| 540 |
rc, out, err = self.module.run_command(cmd) |
| 541 |
if rc != 0 and 'HostName: not set' not in err: |
| 542 |
self.module.fail_json(msg="Failed to get current hostname rc=%d, out=%s, err=%s" % (rc, out, err)) |
| 543 |
|
| 544 |
return to_native(out).strip() |
| 545 |
|
| 546 |
def get_permanent_hostname(self): |
| 547 |
cmd = [self.scutil, '--get', 'ComputerName'] |
| 548 |
rc, out, err = self.module.run_command(cmd) |
| 549 |
if rc != 0: |
| 550 |
self.module.fail_json(msg="Failed to get permanent hostname rc=%d, out=%s, err=%s" % (rc, out, err)) |
| 551 |
|
| 552 |
return to_native(out).strip() |
| 553 |
|
| 554 |
def set_permanent_hostname(self, name): |
| 555 |
for hostname_type in self.name_types: |
| 556 |
cmd = [self.scutil, '--set', hostname_type] |
| 557 |
if hostname_type == 'LocalHostName': |
| 558 |
cmd.append(to_native(self.scrubbed_name)) |
| 559 |
else: |
| 560 |
cmd.append(to_native(name)) |
| 561 |
rc, out, err = self.module.run_command(cmd) |
| 562 |
if rc != 0: |
| 563 |
self.module.fail_json(msg="Failed to set {3} to '{2}': {0} {1}".format(to_native(out), to_native(err), to_native(name), hostname_type)) |
| 564 |
|
| 565 |
def set_current_hostname(self, name): |
| 566 |
pass |
| 567 |
|
| 568 |
def update_current_hostname(self): |
| 569 |
pass |
| 570 |
|
| 571 |
def update_permanent_hostname(self): |
| 572 |
name = self.module.params['name'] |
| 573 |
|
| 574 |
# Get all the current host name values in the order of self.name_types |
| 575 |
all_names = tuple(self.module.run_command([self.scutil, '--get', name_type])[1].strip() for name_type in self.name_types) |
| 576 |
|
| 577 |
# Get the expected host name values based on the order in self.name_types |
| 578 |
expected_names = tuple(self.scrubbed_name if n == 'LocalHostName' else name for n in self.name_types) |
| 579 |
|
| 580 |
# Ensure all three names are updated |
| 581 |
if all_names != expected_names: |
| 582 |
if not self.module.check_mode: |
| 583 |
self.set_permanent_hostname(name) |
| 584 |
self.changed = True |
| 585 |
|
| 586 |
|
| 587 |
class Hostname(object): |
| 588 |
""" |
| 589 |
This is a generic Hostname manipulation class that is subclassed |
| 590 |
based on platform. |
| 591 |
|
| 592 |
A subclass may wish to set different strategy instance to self.strategy. |
| 593 |
|
| 594 |
All subclasses MUST define platform and distribution (which may be None). |
| 595 |
""" |
| 596 |
|
| 597 |
platform = 'Generic' |
| 598 |
distribution = None # type: str | None |
| 599 |
strategy_class = UnimplementedStrategy # type: t.Type[BaseStrategy] |
| 600 |
|
| 601 |
def __new__(cls, *args, **kwargs): |
| 602 |
new_cls = get_platform_subclass(Hostname) |
| 603 |
return super(cls, new_cls).__new__(new_cls) |
| 604 |
|
| 605 |
def __init__(self, module): |
| 606 |
self.module = module |
| 607 |
self.name = module.params['name'] |
| 608 |
self.use = module.params['use'] |
| 609 |
|
| 610 |
if self.use is not None: |
| 611 |
strategy = globals()['%sStrategy' % STRATS[self.use]] |
| 612 |
self.strategy = strategy(module) |
| 613 |
elif platform.system() == 'Linux' and ServiceMgrFactCollector.is_systemd_managed(module): |
| 614 |
# This is Linux and systemd is active |
| 615 |
self.strategy = SystemdStrategy(module) |
| 616 |
else: |
| 617 |
self.strategy = self.strategy_class(module) |
| 618 |
|
| 619 |
def update_current_and_permanent_hostname(self): |
| 620 |
return self.strategy.update_current_and_permanent_hostname() |
| 621 |
|
| 622 |
def get_current_hostname(self): |
| 623 |
return self.strategy.get_current_hostname() |
| 624 |
|
| 625 |
def set_current_hostname(self, name): |
| 626 |
self.strategy.set_current_hostname(name) |
| 627 |
|
| 628 |
def get_permanent_hostname(self): |
| 629 |
return self.strategy.get_permanent_hostname() |
| 630 |
|
| 631 |
def set_permanent_hostname(self, name): |
| 632 |
self.strategy.set_permanent_hostname(name) |
| 633 |
|
| 634 |
|
| 635 |
class SLESHostname(Hostname): |
| 636 |
platform = 'Linux' |
| 637 |
distribution = 'Sles' |
| 638 |
try: |
| 639 |
distribution_version = get_distribution_version() |
| 640 |
# cast to float may raise ValueError on non SLES, we use float for a little more safety over int |
| 641 |
if distribution_version and 10 <= float(distribution_version) <= 12: |
| 642 |
strategy_class = SLESStrategy # type: t.Type[BaseStrategy] |
| 643 |
else: |
| 644 |
raise ValueError() |
| 645 |
except ValueError: |
| 646 |
strategy_class = UnimplementedStrategy |
| 647 |
|
| 648 |
|
| 649 |
class RHELHostname(Hostname): |
| 650 |
platform = 'Linux' |
| 651 |
distribution = 'Redhat' |
| 652 |
strategy_class = RedHatStrategy |
| 653 |
|
| 654 |
|
| 655 |
class CentOSHostname(Hostname): |
| 656 |
platform = 'Linux' |
| 657 |
distribution = 'Centos' |
| 658 |
strategy_class = RedHatStrategy |
| 659 |
|
| 660 |
|
| 661 |
class AnolisOSHostname(Hostname): |
| 662 |
platform = 'Linux' |
| 663 |
distribution = 'Anolis' |
| 664 |
strategy_class = RedHatStrategy |
| 665 |
|
| 666 |
|
| 667 |
class CloudlinuxserverHostname(Hostname): |
| 668 |
platform = 'Linux' |
| 669 |
distribution = 'Cloudlinuxserver' |
| 670 |
strategy_class = RedHatStrategy |
| 671 |
|
| 672 |
|
| 673 |
class CloudlinuxHostname(Hostname): |
| 674 |
platform = 'Linux' |
| 675 |
distribution = 'Cloudlinux' |
| 676 |
strategy_class = RedHatStrategy |
| 677 |
|
| 678 |
|
| 679 |
class AlinuxHostname(Hostname): |
| 680 |
platform = 'Linux' |
| 681 |
distribution = 'Alinux' |
| 682 |
strategy_class = RedHatStrategy |
| 683 |
|
| 684 |
|
| 685 |
class ScientificHostname(Hostname): |
| 686 |
platform = 'Linux' |
| 687 |
distribution = 'Scientific' |
| 688 |
strategy_class = RedHatStrategy |
| 689 |
|
| 690 |
|
| 691 |
class OracleLinuxHostname(Hostname): |
| 692 |
platform = 'Linux' |
| 693 |
distribution = 'Oracle' |
| 694 |
strategy_class = RedHatStrategy |
| 695 |
|
| 696 |
|
| 697 |
class VirtuozzoLinuxHostname(Hostname): |
| 698 |
platform = 'Linux' |
| 699 |
distribution = 'Virtuozzo' |
| 700 |
strategy_class = RedHatStrategy |
| 701 |
|
| 702 |
|
| 703 |
class AmazonLinuxHostname(Hostname): |
| 704 |
platform = 'Linux' |
| 705 |
distribution = 'Amazon' |
| 706 |
strategy_class = RedHatStrategy |
| 707 |
|
| 708 |
|
| 709 |
class DebianHostname(Hostname): |
| 710 |
platform = 'Linux' |
| 711 |
distribution = 'Debian' |
| 712 |
strategy_class = FileStrategy |
| 713 |
|
| 714 |
|
| 715 |
class KylinHostname(Hostname): |
| 716 |
platform = 'Linux' |
| 717 |
distribution = 'Kylin' |
| 718 |
strategy_class = FileStrategy |
| 719 |
|
| 720 |
|
| 721 |
class CumulusHostname(Hostname): |
| 722 |
platform = 'Linux' |
| 723 |
distribution = 'Cumulus-linux' |
| 724 |
strategy_class = FileStrategy |
| 725 |
|
| 726 |
|
| 727 |
class KaliHostname(Hostname): |
| 728 |
platform = 'Linux' |
| 729 |
distribution = 'Kali' |
| 730 |
strategy_class = FileStrategy |
| 731 |
|
| 732 |
|
| 733 |
class ParrotHostname(Hostname): |
| 734 |
platform = 'Linux' |
| 735 |
distribution = 'Parrot' |
| 736 |
strategy_class = FileStrategy |
| 737 |
|
| 738 |
|
| 739 |
class UbuntuHostname(Hostname): |
| 740 |
platform = 'Linux' |
| 741 |
distribution = 'Ubuntu' |
| 742 |
strategy_class = FileStrategy |
| 743 |
|
| 744 |
|
| 745 |
class LinuxmintHostname(Hostname): |
| 746 |
platform = 'Linux' |
| 747 |
distribution = 'Linuxmint' |
| 748 |
strategy_class = FileStrategy |
| 749 |
|
| 750 |
|
| 751 |
class LinaroHostname(Hostname): |
| 752 |
platform = 'Linux' |
| 753 |
distribution = 'Linaro' |
| 754 |
strategy_class = FileStrategy |
| 755 |
|
| 756 |
|
| 757 |
class DevuanHostname(Hostname): |
| 758 |
platform = 'Linux' |
| 759 |
distribution = 'Devuan' |
| 760 |
strategy_class = FileStrategy |
| 761 |
|
| 762 |
|
| 763 |
class RaspbianHostname(Hostname): |
| 764 |
platform = 'Linux' |
| 765 |
distribution = 'Raspbian' |
| 766 |
strategy_class = FileStrategy |
| 767 |
|
| 768 |
|
| 769 |
class UosHostname(Hostname): |
| 770 |
platform = 'Linux' |
| 771 |
distribution = 'Uos' |
| 772 |
strategy_class = FileStrategy |
| 773 |
|
| 774 |
|
| 775 |
class DeepinHostname(Hostname): |
| 776 |
platform = 'Linux' |
| 777 |
distribution = 'Deepin' |
| 778 |
strategy_class = FileStrategy |
| 779 |
|
| 780 |
|
| 781 |
class GentooHostname(Hostname): |
| 782 |
platform = 'Linux' |
| 783 |
distribution = 'Gentoo' |
| 784 |
strategy_class = OpenRCStrategy |
| 785 |
|
| 786 |
|
| 787 |
class ALTLinuxHostname(Hostname): |
| 788 |
platform = 'Linux' |
| 789 |
distribution = 'Altlinux' |
| 790 |
strategy_class = RedHatStrategy |
| 791 |
|
| 792 |
|
| 793 |
class AlpineLinuxHostname(Hostname): |
| 794 |
platform = 'Linux' |
| 795 |
distribution = 'Alpine' |
| 796 |
strategy_class = AlpineStrategy |
| 797 |
|
| 798 |
|
| 799 |
class OpenBSDHostname(Hostname): |
| 800 |
platform = 'OpenBSD' |
| 801 |
distribution = None |
| 802 |
strategy_class = OpenBSDStrategy |
| 803 |
|
| 804 |
|
| 805 |
class SolarisHostname(Hostname): |
| 806 |
platform = 'SunOS' |
| 807 |
distribution = None |
| 808 |
strategy_class = SolarisStrategy |
| 809 |
|
| 810 |
|
| 811 |
class FreeBSDHostname(Hostname): |
| 812 |
platform = 'FreeBSD' |
| 813 |
distribution = None |
| 814 |
strategy_class = FreeBSDStrategy |
| 815 |
|
| 816 |
|
| 817 |
class NetBSDHostname(Hostname): |
| 818 |
platform = 'NetBSD' |
| 819 |
distribution = None |
| 820 |
strategy_class = FreeBSDStrategy |
| 821 |
|
| 822 |
|
| 823 |
class NeonHostname(Hostname): |
| 824 |
platform = 'Linux' |
| 825 |
distribution = 'Neon' |
| 826 |
strategy_class = FileStrategy |
| 827 |
|
| 828 |
|
| 829 |
class DarwinHostname(Hostname): |
| 830 |
platform = 'Darwin' |
| 831 |
distribution = None |
| 832 |
strategy_class = DarwinStrategy |
| 833 |
|
| 834 |
|
| 835 |
class VoidLinuxHostname(Hostname): |
| 836 |
platform = 'Linux' |
| 837 |
distribution = 'Void' |
| 838 |
strategy_class = FileStrategy |
| 839 |
|
| 840 |
|
| 841 |
class PopHostname(Hostname): |
| 842 |
platform = 'Linux' |
| 843 |
distribution = 'Pop' |
| 844 |
strategy_class = FileStrategy |
| 845 |
|
| 846 |
|
| 847 |
class EurolinuxHostname(Hostname): |
| 848 |
platform = 'Linux' |
| 849 |
distribution = 'Eurolinux' |
| 850 |
strategy_class = RedHatStrategy |
| 851 |
|
| 852 |
|
| 853 |
def main(): |
| 854 |
module = AnsibleModule( |
| 855 |
argument_spec=dict( |
| 856 |
name=dict(type='str', required=True), |
| 857 |
use=dict(type='str', choices=list(STRATS.keys())) |
| 858 |
), |
| 859 |
supports_check_mode=True, |
| 860 |
) |
| 861 |
|
| 862 |
hostname = Hostname(module) |
| 863 |
name = module.params['name'] |
| 864 |
|
| 865 |
current_hostname = hostname.get_current_hostname() |
| 866 |
permanent_hostname = hostname.get_permanent_hostname() |
| 867 |
|
| 868 |
changed = hostname.update_current_and_permanent_hostname() |
| 869 |
|
| 870 |
if name != current_hostname: |
| 871 |
name_before = current_hostname |
| 872 |
else: |
| 873 |
name_before = permanent_hostname |
| 874 |
|
| 875 |
# NOTE: socket.getfqdn() calls gethostbyaddr(socket.gethostname()), which can be |
| 876 |
# slow to return if the name does not resolve correctly. |
| 877 |
kw = dict(changed=changed, name=name, |
| 878 |
ansible_facts=dict(ansible_hostname=name.split('.')[0], |
| 879 |
ansible_nodename=name, |
| 880 |
ansible_fqdn=socket.getfqdn(), |
| 881 |
ansible_domain='.'.join(socket.getfqdn().split('.')[1:]))) |
| 882 |
|
| 883 |
if changed: |
| 884 |
kw['diff'] = {'after': 'hostname = ' + name + '\n', |
| 885 |
'before': 'hostname = ' + name_before + '\n'} |
| 886 |
|
| 887 |
module.exit_json(**kw) |
| 888 |
|
| 889 |
|
| 890 |
if __name__ == '__main__': |
| 891 |
main() |