summaryrefslogtreecommitdiff
path: root/cloud-init.py
blob: 814a5b752a7bc2c77bd91a2d0dafae816d38dcf4 (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
import os
import yaml


def log(msg):
    logfile.write(msg)
    logfile.write("\n")
    logfile.flush()


logfile = open("/tmp/vmadm.script", "w")
log("vmadm cloud-init script starting")

if os.environ.get("VMADM_TESTING"):
    filename = "smoke/user-data"
    etc = "x"
else:
    filename = "/var/lib/cloud/instance/user-data.txt"
    etc = "/etc/ssh"

key_types = ("rsa", "dsa", "ecdsa", "ed25519")

log(f"loading user-data from {filename}")
obj = yaml.safe_load(open(filename))

ssh_keys = obj.get("ssh_keys", {})
user_ca_pubkey = obj.get("user_ca_pubkey", {})
allow_authorized_keys = obj.get("allow_authorized_keys", True)

keys = []
certs = []

for key_type in key_types:
    filename = os.path.join(etc, f"ssh_host_{key_type}_key.pub")
    if os.path.exists(filename):
        log(f"removing {filename}")
        os.remove(filename)
    else:
        log(f"file {filename} does not exist")

for key_type in key_types:
    key = ssh_keys.get(f"{key_type}_private")
    cert = ssh_keys.get(f"{key_type}_certificate")
    log(f"key {key_type} {key}")
    log(f"cert {key_type} {cert }")

    if key:
        filename = os.path.join(etc, f"ssh_host_{key_type}_key")
        log(f"writing key {filename}")
        keys.append(filename)
        with open(filename, "w") as f:
            f.write(key)

    if cert:
        filename = os.path.join(etc, f"ssh_host_{key_type}_key-cert.pub")
        log(f"writing cert {filename}")
        certs.append(filename)
        with open(filename, "w") as f:
            f.write(cert)

user_ca_filename = os.path.join(etc, "user-ca-keys")
if user_ca_pubkey:
    with open(user_ca_filename, "w") as f:
        f.write(user_ca_pubkey)

config = os.path.join(etc, "sshd_config")
data = ""
if os.path.exists(config):
    data = open(config).read()

log(f"configuring sshd {config}")
log(f"keys {keys}")
log(f"certs {certs}")

with open(config, "w") as f:
    for filename in keys:
        log(f"hostkey {filename}")
        f.write(f"hostkey {filename}\n")
    for filename in certs:
        log(f"hostcert {filename}")
        f.write(f"hostcertificate {filename}\n")
    if user_ca_pubkey:
        log(f"trustedusercakeys {user_ca_filename}")
        f.write(f"trustedusercakeys {user_ca_filename}\n")
    if not allow_authorized_keys:
        f.write("authorizedkeysfile none\n")
    f.write(data)

log("vmadm cloud-init script ending")
logfile.close()