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
|
#!/usr/bin/env python
from __future__ import (
absolute_import,
print_function,
unicode_literals,
)
import json
import os
import sys
from curtin import util
DATASOURCE_LIST = """\
datasource_list: [ MAAS ]
"""
DATASOURCE = """\
datasource:
MAAS: {{consumer_key: {consumer_key}, metadata_url: '{url}',
token_key: {token_key}, token_secret: {token_secret}}}
"""
def get_datasource(**kwargs):
"""Returns the format cloud-init datasource."""
return DATASOURCE_LIST + DATASOURCE.format(**kwargs)
def load_config(path):
"""Loads the curtin config."""
with open(path, 'r') as stream:
return json.load(stream)
def extract_maas_parameters(config):
"""Extracts the needed values from the debconf
entry."""
params = {}
for line in config.splitlines():
cloud, key, type, value = line.split()[:4]
if key == "cloud-init/maas-metadata-url":
params['url'] = value
elif key == "cloud-init/maas-metadata-credentials":
values = value.split("&")
for oauth in values:
key, value = oauth.split('=')
if key == 'oauth_token_key':
params['token_key'] = value
elif key == 'oauth_token_secret':
params['token_secret'] = value
elif key == 'oauth_consumer_key':
params['consumer_key'] = value
return params
def get_maas_debconf_selections(config):
"""Gets the debconf selections from the curtin config."""
try:
return config['debconf_selections']['maas']
except KeyError:
return None
def write_datasource(target, data):
"""Writes the cloudinit config into
/etc/cloud/cloud.cfg.d/90_datasource.cfg."""
path = os.path.join(
target, 'etc', 'cloud', 'cloud.cfg.d', '90_datasource.cfg')
with open(path, 'w') as stream:
stream.write(data + '\n')
def main():
state = util.load_command_environment()
target = state['target']
if target is None:
print("Target was not provided in the environment.")
sys.exit(1)
config_f = state['config']
if config_f is None:
print("Config was not provided in the environment.")
sys.exit(1)
config = load_config(config_f)
debconf = get_maas_debconf_selections(config)
if debconf is None:
print("Failed to get the debconf_selections.")
sys.exit(1)
params = extract_maas_parameters(debconf)
datasource = get_datasource(**params)
write_datasource(target, datasource)
if __name__ == "__main__":
main()
|