summaryrefslogtreecommitdiff
path: root/plugins/modules/vyos_hostname.py
blob: f1c901e84547c22a78c74b5426b8f019d0ca9054 (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
#!/usr/bin/python

from ansible.module_utils.basic import AnsibleModule
from ansible_collections.vyos.rest.plugins.module_utils.vyos import VyOSModule


def get_running_config(vyos):

    raw = vyos.get_config(["system", "host-name"])

    hostname = None

    if isinstance(raw, dict):
        hostname = raw.get("host-name")

    elif isinstance(raw, str):
        hostname = raw.strip()
    else:
        hostname = None

    return {"hostname": hostname}

def build_commands(want, have, state):

    commands = []

    want_host = want.get("hostname")
    have_host = have.get("hostname")

    if state in ["merged", "replaced", "overridden"]:

        if want_host and want_host != have_host:
            commands.append({
                "op": "set",
                "path": ["system", "host-name", want_host]
            })

    elif state == "deleted":

        if have_host:
            commands.append({
                "op": "delete",
                "path": ["system", "host-name"]
            })

    return commands


def main():

    argument_spec = dict(
        config=dict(
            type="dict",
            options=dict(
                hostname=dict(type="str")
            )
        ),
        state=dict(
            default="merged",
            choices=[
                "merged",
                "replaced",
                "overridden",
                "deleted",
                "gathered",
            ],
        ),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    vyos = VyOSModule(module)

    state = module.params["state"]
    want = module.params.get("config") or {}

    have = get_running_config(vyos)

    if state == "gathered":
        module.exit_json(
            changed=False,
            gathered=have
        )

    commands = build_commands(want, have, state)

    if module.check_mode:
        module.exit_json(
            changed=bool(commands),
            commands=commands
        )

    if commands:

        response = vyos.apply_commands(commands)

        # save config if change applied
        saved = vyos.save_config()

        module.exit_json(
            changed=True,
            before=have,
            after=want,
            commands=commands,
            saved=saved,
            response=response
        )

    module.exit_json(
        changed=False,
        before=have,
        after=have
    )


if __name__ == "__main__":
    main()