blue-australia-88467
11/08/2024, 7:35 PMimport * as pulumi from "@pulumi/pulumi";
import * as hcloud from "@pulumi/hcloud";
import { remote } from "@pulumi/command";
import * as fs from "fs";
import * as child_process from "child_process";
import * as os from "os";
import * as path from "path";
export function createHetznerServerWithSSHKey(config: pulumi.Config) {
const homeDir = os.homedir();
const sshKeyPath = path.join(homeDir, ".ssh", "pulumi_generated_key");
const publicKeyPath = `${sshKeyPath}.pub`;
const email = config.require("email");
const sshKeyName = config.require("sshKeyName");
const serverName = config.require("serverName");
try {
if (!fs.existsSync(sshKeyPath) || !fs.existsSync(publicKeyPath)) {
console.log("SSH key not found, creating a new one...");
child_process.execSync(
`ssh-keygen -t rsa -b 4096 -C "${email}" -f ${sshKeyPath} -q -N ""`,
{
stdio: "inherit",
},
);
console.log("SSH key generated successfully.");
} else {
console.log(sshKeyPath);
console.log("SSH key already exists, skipping generation.");
}
} catch (error) {
console.error("Error generating SSH key:", error);
process.exit(1);
}
const sshPublicKey = fs.readFileSync(publicKeyPath, "utf-8").trim();
const sshPrivateKey = fs.readFileSync("/home/myusername/.ssh/pulumi_generated_key", "utf-8").trim();
const sshKey = new hcloud.SshKey(sshKeyName, {
name: sshKeyName,
publicKey: sshPublicKey,
});
// Disable password Auth
const userData = `
#cloud-config
ssh_pwauth: false
`;
const server = new hcloud.Server(serverName, {
serverType: "cpx11",
image: "docker-ce",
// image: "ubuntu-22.04",
sshKeys: [sshKey.name],
location: "nbg1",
userData: userData,
labels: { environment: "dev" },
});
const ip = server.ipv4Address;
const remotePath = "/home/"
const uploadEnvFile = new remote.CopyToRemote("uploadEnvFile", {
connection: {
host: ip,
user: "root",
privateKey: pulumi.secret(sshPrivateKey),
},
source: new pulumi.asset.FileAsset("./.env.dev"),
remotePath: `${remotePath}.env.dev`,
});
const uploadComposeFile = new remote.CopyToRemote("uploadComposeFile", {
connection: {
host: ip,
user: "root",
privateKey: pulumi.secret(sshPrivateKey),
},
source: new pulumi.asset.FileAsset("./docker-compose-prod.yaml"),
remotePath: `${remotePath}docker-compose-prod.yaml`,
});
return server.ipv4Address;
}