summaryrefslogtreecommitdiffstats
path: root/lib/ansible/modules/hostname.py
blob: 1f0bfa03c23dd86f97a6954b41c179117edf8bcb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright: (c) 2013, Hiroaki Nakamura <hnakamur@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import annotations


DOCUMENTATION = '''
---
module: hostname
author:
    - Adrian Likins (@alikins)
    - Hideki Saito (@saito-hideki)
version_added: "1.4"
short_description: Manage hostname
requirements: [ hostname ]
description:
    - Set system's hostname. Supports most OSs/Distributions including those using C(systemd).
    - Windows, HP-UX, and AIX are not currently supported.
notes:
    - This module does B(NOT) modify C(/etc/hosts). You need to modify it yourself using other modules such as M(ansible.builtin.template)
      or M(ansible.builtin.replace).
    - On macOS, this module uses C(scutil) to set C(HostName), C(ComputerName), and C(LocalHostName). Since C(LocalHostName)
      cannot contain spaces or most special characters, this module will replace characters when setting C(LocalHostName).
options:
    name:
        description:
            - Name of the host.
            - If the value is a fully qualified domain name that does not resolve from the given host,
              this will cause the module to hang for a few seconds while waiting for the name resolution attempt to timeout.
        type: str
        required: true
    use:
        description:
            - Which strategy to use to update the hostname.
            - If not set we try to autodetect, but this can be problematic, particularly with containers as they can present misleading information.
            - Note that 'systemd' should be specified for RHEL/EL/CentOS 7+. Older distributions should use 'redhat'.
        choices: ['alpine', 'debian', 'freebsd', 'generic', 'macos', 'macosx', 'darwin', 'openbsd', 'openrc', 'redhat', 'sles', 'solaris', 'systemd']
        type: str
        version_added: '2.9'
extends_documentation_fragment:
- action_common_attributes
- action_common_attributes.facts
attributes:
    check_mode:
        support: full
    diff_mode:
        support: full
    facts:
        support: full
    platform:
        platforms: posix
'''

EXAMPLES = '''
- name: Set a hostname
  ansible.builtin.hostname:
    name: web01

- name: Set a hostname specifying strategy
  ansible.builtin.hostname:
    name: web01
    use: systemd
'''

import os
import platform
import socket
import traceback

import ansible.module_utils.compat.typing as t

from ansible.module_utils.basic import (
    AnsibleModule,
    get_distribution,
    get_distribution_version,
)
from ansible.module_utils.common.sys_info import get_platform_subclass
from ansible.module_utils.facts.system.service_mgr import ServiceMgrFactCollector
from ansible.module_utils.facts.utils import get_file_lines, get_file_content
from ansible.module_utils.common.text.converters import to_native, to_text

STRATS = {
    'alpine': 'Alpine',
    'debian': 'Systemd',
    'freebsd': 'FreeBSD',
    'generic': 'Base',
    'macos': 'Darwin',
    'macosx': 'Darwin',
    'darwin': 'Darwin',
    'openbsd': 'OpenBSD',
    'openrc': 'OpenRC',
    'redhat': 'RedHat',
    'sles': 'SLES',
    'solaris': 'Solaris',
    'systemd': 'Systemd',
}


class BaseStrategy(object):
    def __init__(self, module):
        self.module = module
        self.changed = False

    def update_current_and_permanent_hostname(self):
        self.update_current_hostname()
        self.update_permanent_hostname()
        return self.changed

    def update_current_hostname(self):
        name = self.module.params['name']
        current_name = self.get_current_hostname()
        if current_name != name:
            if not self.module.check_mode:
                self.set_current_hostname(name)
            self.changed = True

    def update_permanent_hostname(self):
        name = self.module.params['name']
        permanent_name = self.get_permanent_hostname()
        if permanent_name != name:
            if not self.module.check_mode:
                self.set_permanent_hostname(name)
            self.changed = True

    def get_current_hostname(self):
        return self.get_permanent_hostname()

    def set_current_hostname(self, name):
        pass

    def get_permanent_hostname(self):
        raise NotImplementedError

    def set_permanent_hostname(self, name):
        raise NotImplementedError


class UnimplementedStrategy(BaseStrategy):
    def update_current_and_permanent_hostname(self):
        self.unimplemented_error()

    def update_current_hostname(self):
        self.unimplemented_error()

    def update_permanent_hostname(self):
        self.unimplemented_error()

    def get_current_hostname(self):
        self.unimplemented_error()

    def set_current_hostname(self, name):
        self.unimplemented_error()

    def get_permanent_hostname(self):
        self.unimplemented_error()

    def set_permanent_hostname(self, name):
        self.unimplemented_error()

    def unimplemented_error(self):
        system = platform.system()
        distribution = get_distribution()
        if distribution is not None:
            msg_platform = '%s (%s)' % (system, distribution)
        else:
            msg_platform = system
        self.module.fail_json(
            msg='hostname module cannot be used on platform %s' % msg_platform)


class CommandStrategy(BaseStrategy):
    COMMAND = 'hostname'

    def __init__(self, module):
        super(CommandStrategy, self).__init__(module)
        self.hostname_cmd = self.module.get_bin_path(self.COMMAND, True)

    def get_current_hostname(self):
        cmd = [self.hostname_cmd]
        rc, out, err = self.module.run_command(cmd)
        if rc != 0:
            self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err))
        return to_native(out).strip()

    def set_current_hostname(self, name):
        cmd = [self.hostname_cmd, name]
        rc, out, err = self.module.run_command(cmd)
        if rc != 0:
            self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err))

    def get_permanent_hostname(self):
        return 'UNKNOWN'

    def set_permanent_hostname(self, name):
        pass


class FileStrategy(BaseStrategy):
    FILE = '/etc/hostname'

    def get_permanent_hostname(self):
        if not os.path.isfile(self.FILE):
            return ''

        try:
            return get_file_content(self.FILE, default='', strip=True)
        except Exception as e:
            self.module.fail_json(
                msg="failed to read hostname: %s" % to_native(e),
                exception=traceback.format_exc())

    def set_permanent_hostname(self, name):
        try:
            with open(self.FILE, 'w+') as f:
                f.write("%s\n" % name)
        except Exception as e:
            self.module.fail_json(
                msg="failed to update hostname: %s" % to_native(e),
                exception=traceback.format_exc())


class SLESStrategy(FileStrategy):
    """
    This is a SLES Hostname strategy class - it edits the
    /etc/HOSTNAME file.
    """
    FILE = '/etc/HOSTNAME'


class RedHatStrategy(BaseStrategy):
    """
    This is a Redhat Hostname strategy class - it edits the
    /etc/sysconfig/network file.
    """
    NETWORK_FILE = '/etc/sysconfig/network'

    def get_permanent_hostname(self):
        try:
            for line in get_file_lines(self.NETWORK_FILE):
                line = to_native(line).strip()
                if line.startswith('HOSTNAME'):
                    k, v = line.split('=')
                    return v.strip()
            self.module.fail_json(
                "Unable to locate HOSTNAME entry in %s" % self.NETWORK_FILE
            )
        except Exception as e:
            self.module.fail_json(
                msg="failed to read hostname: %s" % to_native(e),
                exception=traceback.format_exc())

    def set_permanent_hostname(self, name):
        try:
            lines = []
            found = False
            content = get_file_content(self.NETWORK_FILE, strip=False) or ""
            for line in content.splitlines(True):
                line = to_native(line)
                if line.strip().startswith('HOSTNAME'):
                    lines.append("HOSTNAME=%s\n" % name)
                    found = True
                else:
                    lines.append(line)
            if not found:
                lines.append("HOSTNAME=%s\n" % name)
            with open(self.NETWORK_FILE, 'w+') as f:
                f.writelines(lines)
        except Exception as e:
            self.module.fail_json(
                msg="failed to update hostname: %s" % to_native(e),
                exception=traceback.format_exc())


class AlpineStrategy(FileStrategy):
    """
    This is a Alpine Linux Hostname manipulation strategy class - it edits
    the /etc/hostname file then run hostname -F /etc/hostname.
    """

    FILE = '/etc/hostname'
    COMMAND = 'hostname'

    def set_current_hostname(self, name):
        super(AlpineStrategy, self).set_current_hostname(name)
        hostname_cmd = self.module.get_bin_path(self.COMMAND, True)

        cmd = [hostname_cmd, '-F', self.FILE]
        rc, out, err = self.module.run_command(cmd)
        if rc != 0:
            self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err))


class SystemdStrategy(BaseStrategy):
    """
    This is a Systemd hostname manipulation strategy class - it uses
    the hostnamectl command.
    """

    COMMAND = "hostnamectl"

    def __init__(self, module):
        super(SystemdStrategy, self).__init__(module)
        self.hostnamectl_cmd = self.module.get_bin_path(self.COMMAND, True)

    def get_current_hostname(self):
        cmd = [self.hostnamectl_cmd, '--transient', 'status']
        rc, out, err = self.module.run_command(cmd)
        if rc != 0:
            self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err))
        return to_native(out).strip()

    def set_current_hostname(self, name):
        if len(name) > 64:
            self.module.fail_json(msg="name cannot be longer than 64 characters on systemd servers, try a shorter name")
        cmd = [self.hostnamectl_cmd, '--transient', 'set-hostname', name]
        rc, out, err = self.module.run_command(cmd)
        if rc != 0:
            self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err))

    def get_permanent_hostname(self):
        cmd = [self.hostnamectl_cmd, '--static', 'status']
        rc, out, err = self.module.run_command(cmd)
        if rc != 0:
            self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err))
        return to_native(out).strip()

    def set_permanent_hostname(self, name):
        if len(name) > 64:
            self.module.fail_json(msg="name cannot be longer than 64 characters on systemd servers, try a shorter name")
        cmd = [self.hostnamectl_cmd, '--pretty', '--static', 'set-hostname', name]
        rc, out, err = self.module.run_command(cmd)
        if rc != 0:
            self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err))

    def update_current_and_permanent_hostname(self):
        # Must set the permanent hostname prior to current to avoid NetworkManager complaints
        # about setting the hostname outside of NetworkManager
        self.update_permanent_hostname()
        self.update_current_hostname()
        return self.changed


class OpenRCStrategy(BaseStrategy):
    """
    This is a Gentoo (OpenRC) Hostname manipulation strategy class - it edits
    the /etc/conf.d/hostname file.
    """

    FILE = '/etc/conf.d/hostname'

    def get_permanent_hostname(self):
        if not os.path.isfile(self.FILE):
            return ''

        try:
            for line in get_file_lines(self.FILE):
                line = line.strip()
                if line.startswith('hostname='):
                    return line[10:].strip('"')
        except Exception as e:
            self.module.fail_json(
                msg="failed to read hostname: %s" % to_native(e),
                exception=traceback.format_exc())

    def set_permanent_hostname(self, name):
        try:
            lines = [x.strip() for x in get_file_lines(self.FILE)]

            for i, line in enumerate(lines):
                if line.startswith('hostname='):
                    lines[i] = 'hostname="%s"' % name
                    break

            with open(self.FILE, 'w') as f:
                f.write('\n'.join(lines) + '\n')
        except Exception as e:
            self.module.fail_json(
                msg="failed to update hostname: %s" % to_native(e),
                exception=traceback.format_exc())


class OpenBSDStrategy(FileStrategy):
    """
    This is a OpenBSD family Hostname manipulation strategy class - it edits
    the /etc/myname file for the permanent hostname and executes hostname
    command for the current hostname.
    """

    FILE = '/etc/myname'
    COMMAND = "hostname"

    def __init__(self, module):
        super(OpenBSDStrategy, self).__init__(module)
        self.hostname_cmd = self.module.get_bin_path(self.COMMAND, True)

    def get_current_hostname(self):
        cmd = [self.hostname_cmd]
        rc, out, err = self.module.run_command(cmd)
        if rc != 0:
            self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err))
        return to_native(out).strip()

    def set_current_hostname(self, name):
        cmd = [self.hostname_cmd, name]
        rc, out, err = self.module.run_command(cmd)
        if rc != 0:
            self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err))


class SolarisStrategy(BaseStrategy):
    """
    This is a Solaris11 or later Hostname manipulation strategy class - it
    execute hostname command.
    """

    COMMAND = "hostname"

    def __init__(self, module):
        super(SolarisStrategy, self).__init__(module)
        self.hostname_cmd = self.module.get_bin_path(self.COMMAND, True)

    def set_current_hostname(self, name):
        cmd_option = '-t'
        cmd = [self.hostname_cmd, cmd_option, name]
        rc, out, err = self.module.run_command(cmd)
        if rc != 0:
            self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err))

    def get_permanent_hostname(self):
        fmri = 'svc:/system/identity:node'
        pattern = 'config/nodename'
        cmd = '/usr/sbin/svccfg -s %s listprop -o value %s' % (fmri, pattern)
        rc, out, err = self.module.run_command(cmd, use_unsafe_shell=True)
        if rc != 0:
            self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err))
        return to_native(out).strip()

    def set_permanent_hostname(self, name):
        cmd = [self.hostname_cmd, name]
        rc, out, err = self.module.run_command(cmd)
        if rc != 0:
            self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err))


class FreeBSDStrategy(BaseStrategy):
    """
    This is a FreeBSD hostname manipulation strategy class - it edits
    the /etc/rc.conf.d/hostname file.
    """

    FILE = '/etc/rc.conf.d/hostname'
    COMMAND = "hostname"

    def __init__(self, module):
        super(FreeBSDStrategy, self).__init__(module)
        self.hostname_cmd = self.module.get_bin_path(self.COMMAND, True)

    def get_current_hostname(self):
        cmd = [self.hostname_cmd]
        rc, out, err = self.module.run_command(cmd)
        if rc != 0:
            self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err))
        return to_native(out).strip()

    def set_current_hostname(self, name):
        cmd = [self.hostname_cmd, name]
        rc, out, err = self.module.run_command(cmd)
        if rc != 0:
            self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err))

    def get_permanent_hostname(self):
        if not os.path.isfile(self.FILE):
            return ''

        try:
            for line in get_file_lines(self.FILE):
                line = line.strip()
                if line.startswith('hostname='):
                    return line[10:].strip('"')
        except Exception as e:
            self.module.fail_json(
                msg="failed to read hostname: %s" % to_native(e),
                exception=traceback.format_exc())

    def set_permanent_hostname(self, name):
        try:
            if os.path.isfile(self.FILE):
                lines = [x.strip() for x in get_file_lines(self.FILE)]

                for i, line in enumerate(lines):
                    if line.startswith('hostname='):
                        lines[i] = 'hostname="%s"' % name
                        break
            else:
                lines = ['hostname="%s"' % name]

            with open(self.FILE, 'w') as f:
                f.write('\n'.join(lines) + '\n')
        except Exception as e:
            self.module.fail_json(
                msg="failed to update hostname: %s" % to_native(e),
                exception=traceback.format_exc())


class DarwinStrategy(BaseStrategy):
    """
    This is a macOS hostname manipulation strategy class. It uses
    /usr/sbin/scutil to set ComputerName, HostName, and LocalHostName.

    HostName corresponds to what most platforms consider to be hostname.
    It controls the name used on the command line and SSH.

    However, macOS also has LocalHostName and ComputerName settings.
    LocalHostName controls the Bonjour/ZeroConf name, used by services
    like AirDrop. This class implements a method, _scrub_hostname(), that mimics
    the transformations macOS makes on hostnames when enterened in the Sharing
    preference pane. It replaces spaces with dashes and removes all special
    characters.

    ComputerName is the name used for user-facing GUI services, like the
    System Preferences/Sharing pane and when users connect to the Mac over the network.
    """

    def __init__(self, module):
        super(DarwinStrategy, self).__init__(module)

        self.scutil = self.module.get_bin_path('scutil', True)
        self.name_types = ('HostName', 'ComputerName', 'LocalHostName')
        self.scrubbed_name = self._scrub_hostname(self.module.params['name'])

    def _scrub_hostname(self, name):
        """
        LocalHostName only accepts valid DNS characters while HostName and ComputerName
        accept a much wider range of characters. This function aims to mimic how macOS
        translates a friendly name to the LocalHostName.
        """

        # Replace all these characters with a single dash
        name = to_text(name)
        replace_chars = u'\'"~`!@#$%^&*(){}[]/=?+\\|-_ '
        delete_chars = u".'"
        table = str.maketrans(replace_chars, '-' * len(replace_chars), delete_chars)
        name = name.translate(table)

        # Replace multiple dashes with a single dash
        while '-' * 2 in name:
            name = name.replace('-' * 2, '')

        name = name.rstrip('-')
        return name

    def get_current_hostname(self):
        cmd = [self.scutil, '--get', 'HostName']
        rc, out, err = self.module.run_command(cmd)
        if rc != 0 and 'HostName: not set' not in err:
            self.module.fail_json(msg="Failed to get current hostname rc=%d, out=%s, err=%s" % (rc, out, err))

        return to_native(out).strip()

    def get_permanent_hostname(self):
        cmd = [self.scutil, '--get', 'ComputerName']
        rc, out, err = self.module.run_command(cmd)
        if rc != 0:
            self.module.fail_json(msg="Failed to get permanent hostname rc=%d, out=%s, err=%s" % (rc, out, err))

        return to_native(out).strip()

    def set_permanent_hostname(self, name):
        for hostname_type in self.name_types:
            cmd = [self.scutil, '--set', hostname_type]
            if hostname_type == 'LocalHostName':
                cmd.append(to_native(self.scrubbed_name))
            else:
                cmd.append(to_native(name))
            rc, out, err = self.module.run_command(cmd)
            if rc != 0:
                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))

    def set_current_hostname(self, name):
        pass

    def update_current_hostname(self):
        pass

    def update_permanent_hostname(self):
        name = self.module.params['name']

        # Get all the current host name values in the order of self.name_types
        all_names = tuple(self.module.run_command([self.scutil, '--get', name_type])[1].strip() for name_type in self.name_types)

        # Get the expected host name values based on the order in self.name_types
        expected_names = tuple(self.scrubbed_name if n == 'LocalHostName' else name for n in self.name_types)

        # Ensure all three names are updated
        if all_names != expected_names:
            if not self.module.check_mode:
                self.set_permanent_hostname(name)
            self.changed = True


class Hostname(object):
    """
    This is a generic Hostname manipulation class that is subclassed
    based on platform.

    A subclass may wish to set different strategy instance to self.strategy.

    All subclasses MUST define platform and distribution (which may be None).
    """

    platform = 'Generic'
    distribution = None  # type: str | None
    strategy_class = UnimplementedStrategy  # type: t.Type[BaseStrategy]

    def __new__(cls, *args, **kwargs):
        new_cls = get_platform_subclass(Hostname)
        return super(cls, new_cls).__new__(new_cls)

    def __init__(self, module):
        self.module = module
        self.name = module.params['name']
        self.use = module.params['use']

        if self.use is not None:
            strat = globals()['%sStrategy' % STRATS[self.use]]
            self.strategy = strat(module)
        elif platform.system() == 'Linux' and ServiceMgrFactCollector.is_systemd_managed(module):
            # This is Linux and systemd is active
            self.strategy = SystemdStrategy(module)
        else:
            self.strategy = self.strategy_class(module)

    def update_current_and_permanent_hostname(self):
        return self.strategy.update_current_and_permanent_hostname()

    def get_current_hostname(self):
        return self.strategy.get_current_hostname()

    def set_current_hostname(self, name):
        self.strategy.set_current_hostname(name)

    def get_permanent_hostname(self):
        return self.strategy.get_permanent_hostname()

    def set_permanent_hostname(self, name):
        self.strategy.set_permanent_hostname(name)


class SLESHostname(Hostname):
    platform = 'Linux'
    distribution = 'Sles'
    try:
        distribution_version = get_distribution_version()
        # cast to float may raise ValueError on non SLES, we use float for a little more safety over int
        if distribution_version and 10 <= float(distribution_version) <= 12:
            strategy_class = SLESStrategy  # type: t.Type[BaseStrategy]
        else:
            raise ValueError()
    except ValueError:
        strategy_class = UnimplementedStrategy


class RHELHostname(Hostname):
    platform = 'Linux'
    distribution = 'Redhat'
    strategy_class = RedHatStrategy


class CentOSHostname(Hostname):
    platform = 'Linux'
    distribution = 'Centos'
    strategy_class = RedHatStrategy


class AnolisOSHostname(Hostname):
    platform = 'Linux'
    distribution = 'Anolis'
    strategy_class = RedHatStrategy


class CloudlinuxserverHostname(Hostname):
    platform = 'Linux'
    distribution = 'Cloudlinuxserver'
    strategy_class = RedHatStrategy


class CloudlinuxHostname(Hostname):
    platform = 'Linux'
    distribution = 'Cloudlinux'
    strategy_class = RedHatStrategy


class AlinuxHostname(Hostname):
    platform = 'Linux'
    distribution = 'Alinux'
    strategy_class = RedHatStrategy


class ScientificHostname(Hostname):
    platform = 'Linux'
    distribution = 'Scientific'
    strategy_class = RedHatStrategy


class OracleLinuxHostname(Hostname):
    platform = 'Linux'
    distribution = 'Oracle'
    strategy_class = RedHatStrategy


class VirtuozzoLinuxHostname(Hostname):
    platform = 'Linux'
    distribution = 'Virtuozzo'
    strategy_class = RedHatStrategy


class AmazonLinuxHostname(Hostname):
    platform = 'Linux'
    distribution = 'Amazon'
    strategy_class = RedHatStrategy


class DebianHostname(Hostname):
    platform = 'Linux'
    distribution = 'Debian'
    strategy_class = FileStrategy


class KylinHostname(Hostname):
    platform = 'Linux'
    distribution = 'Kylin'
    strategy_class = FileStrategy


class CumulusHostname(Hostname):
    platform = 'Linux'
    distribution = 'Cumulus-linux'
    strategy_class = FileStrategy


class KaliHostname(Hostname):
    platform = 'Linux'
    distribution = 'Kali'
    strategy_class = FileStrategy


class ParrotHostname(Hostname):
    platform = 'Linux'
    distribution = 'Parrot'
    strategy_class = FileStrategy


class UbuntuHostname(Hostname):
    platform = 'Linux'
    distribution = 'Ubuntu'
    strategy_class = FileStrategy


class LinuxmintHostname(Hostname):
    platform = 'Linux'
    distribution = 'Linuxmint'
    strategy_class = FileStrategy


class LinaroHostname(Hostname):
    platform = 'Linux'
    distribution = 'Linaro'
    strategy_class = FileStrategy


class DevuanHostname(Hostname):
    platform = 'Linux'
    distribution = 'Devuan'
    strategy_class = FileStrategy


class RaspbianHostname(Hostname):
    platform = 'Linux'
    distribution = 'Raspbian'
    strategy_class = FileStrategy


class UosHostname(Hostname):
    platform = 'Linux'
    distribution = 'Uos'
    strategy_class = FileStrategy


class DeepinHostname(Hostname):
    platform = 'Linux'
    distribution = 'Deepin'
    strategy_class = FileStrategy


class GentooHostname(Hostname):
    platform = 'Linux'
    distribution = 'Gentoo'
    strategy_class = OpenRCStrategy


class ALTLinuxHostname(Hostname):
    platform = 'Linux'
    distribution = 'Altlinux'
    strategy_class = RedHatStrategy


class AlpineLinuxHostname(Hostname):
    platform = 'Linux'
    distribution = 'Alpine'
    strategy_class = AlpineStrategy


class OpenBSDHostname(Hostname):
    platform = 'OpenBSD'
    distribution = None
    strategy_class = OpenBSDStrategy


class SolarisHostname(Hostname):
    platform = 'SunOS'
    distribution = None
    strategy_class = SolarisStrategy


class FreeBSDHostname(Hostname):
    platform = 'FreeBSD'
    distribution = None
    strategy_class = FreeBSDStrategy


class NetBSDHostname(Hostname):
    platform = 'NetBSD'
    distribution = None
    strategy_class = FreeBSDStrategy


class NeonHostname(Hostname):
    platform = 'Linux'
    distribution = 'Neon'
    strategy_class = FileStrategy


class DarwinHostname(Hostname):
    platform = 'Darwin'
    distribution = None
    strategy_class = DarwinStrategy


class VoidLinuxHostname(Hostname):
    platform = 'Linux'
    distribution = 'Void'
    strategy_class = FileStrategy


class PopHostname(Hostname):
    platform = 'Linux'
    distribution = 'Pop'
    strategy_class = FileStrategy


class EurolinuxHostname(Hostname):
    platform = 'Linux'
    distribution = 'Eurolinux'
    strategy_class = RedHatStrategy


def main():
    module = AnsibleModule(
        argument_spec=dict(
            name=dict(type='str', required=True),
            use=dict(type='str', choices=list(STRATS.keys()))
        ),
        supports_check_mode=True,
    )

    hostname = Hostname(module)
    name = module.params['name']

    current_hostname = hostname.get_current_hostname()
    permanent_hostname = hostname.get_permanent_hostname()

    changed = hostname.update_current_and_permanent_hostname()

    if name != current_hostname:
        name_before = current_hostname
    elif name != permanent_hostname:
        name_before = permanent_hostname
    else:
        name_before = permanent_hostname

    # NOTE: socket.getfqdn() calls gethostbyaddr(socket.gethostname()), which can be
    # slow to return if the name does not resolve correctly.
    kw = dict(changed=changed, name=name,
              ansible_facts=dict(ansible_hostname=name.split('.')[0],
                                 ansible_nodename=name,
                                 ansible_fqdn=socket.getfqdn(),
                                 ansible_domain='.'.join(socket.getfqdn().split('.')[1:])))

    if changed:
        kw['diff'] = {'after': 'hostname = ' + name + '\n',
                      'before': 'hostname = ' + name_before + '\n'}

    module.exit_json(**kw)


if __name__ == '__main__':
    main()