-
Notifications
You must be signed in to change notification settings - Fork 10
/
IsoImager.cs
74 lines (61 loc) · 1.92 KB
/
IsoImager.cs
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
using System.Text;
using DiscUtils.Iso9660;
public class IsoImager
{
private IEnumerable<string> FindSshKeys()
{
var homeDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var keys = new List<string>();
foreach (var file in Directory.EnumerateFiles(Path.Combine(homeDir, ".ssh")))
{
if (file.EndsWith(".pub"))
{
keys.Add(File.ReadAllText(file));
}
}
return keys;
}
public FileInfo CreateImage(string hostname, DirectoryInfo outputDirectory, string customCmd = "")
{
var keys = "[" + string.Join(",", this.FindSshKeys().Select(key => $"\"{key.Trim()}\"")) + "]";
var userData = $"""
Content-Type: multipart/mixed; boundary="==BOUNDARY=="
MIME-Version: 1.0
--==BOUNDARY==
Content-Type: text/cloud-config; charset="us-ascii"
#cloud-config
preserve_hostname: False
hostname: {hostname}
users:
- default
- name: user
groups: ['sudo']
shell: /bin/bash
sudo: ALL=(ALL) NOPASSWD:ALL
ssh-authorized-keys:
{keys}
output:
all: ">> /var/log/cloud-init.log"
ssh_genkeytypes: ['ed25519', 'rsa']
ssh_authorized_keys:
{keys}
runcmd:
- systemctl stop networking && systemctl start networking
- systemctl disable cloud-init.service
- echo; {customCmd}
--==BOUNDARY==--
""";
var metaData = $"""
instance-id: {hostname}
local-hostname: {hostname}
""";
var builder = new CDBuilder();
builder.UseJoliet = true;
builder.VolumeIdentifier = "cidata";
builder.AddFile(@"user-data", Encoding.UTF8.GetBytes(userData));
builder.AddFile(@"meta-data", Encoding.UTF8.GetBytes(metaData));
var outputFile = Path.Combine(outputDirectory.FullName, "cloudInit.iso");
builder.Build(outputFile);
return new FileInfo(outputFile);
}
}