2024-08-23 04:43:26 -07:00
|
|
|
// @ts-check
|
|
|
|
|
|
|
|
import path from 'path';
|
|
|
|
import { $, fs } from 'zx';
|
|
|
|
|
|
|
|
const paths = {
|
|
|
|
infraCodeDir: path.resolve('infra'),
|
|
|
|
terraformStateFile: path.join(path.resolve('infra'), 'terraform.tfstate'),
|
|
|
|
};
|
|
|
|
|
|
|
|
export class TerraformClient {
|
2024-08-29 22:46:55 -07:00
|
|
|
constructor({ isVerbose = false }) {
|
2024-08-23 04:43:26 -07:00
|
|
|
this.isVerbose = isVerbose;
|
|
|
|
this.$$ = $({
|
|
|
|
cwd: paths.infraCodeDir,
|
|
|
|
verbose: isVerbose,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @typedef {Object} BenchmarkEnv
|
|
|
|
* @property {string} vmName
|
2024-09-02 04:58:24 -07:00
|
|
|
* @property {string} ip
|
|
|
|
* @property {string} sshUsername
|
|
|
|
* @property {string} sshPrivateKeyPath
|
2024-08-23 04:43:26 -07:00
|
|
|
*
|
|
|
|
* @returns {Promise<BenchmarkEnv>}
|
|
|
|
*/
|
|
|
|
async provisionEnvironment() {
|
|
|
|
console.log('Provisioning cloud environment...');
|
|
|
|
|
|
|
|
await this.$$`terraform init`;
|
2024-09-02 04:58:24 -07:00
|
|
|
// await this.$$`terraform apply -input=false -auto-approve`;
|
|
|
|
|
|
|
|
const privateKeyName = await this.extractPrivateKey();
|
2024-08-23 04:43:26 -07:00
|
|
|
|
|
|
|
return {
|
2024-09-02 04:58:24 -07:00
|
|
|
ip: await this.getTerraformOutput('ip'),
|
|
|
|
sshUsername: await this.getTerraformOutput('ssh_username'),
|
|
|
|
sshPrivateKeyPath: path.join(paths.infraCodeDir, privateKeyName),
|
2024-08-23 04:43:26 -07:00
|
|
|
vmName: await this.getTerraformOutput('vm_name'),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
async destroyEnvironment() {
|
|
|
|
if (!fs.existsSync(paths.terraformStateFile)) {
|
|
|
|
console.log('No cloud environment to destroy. Skipping...');
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
console.log('Destroying cloud environment...');
|
|
|
|
|
2024-09-02 04:58:24 -07:00
|
|
|
// await this.$$`terraform destroy -input=false -auto-approve`;
|
2024-08-23 04:43:26 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
async getTerraformOutput(key) {
|
|
|
|
const output = await this.$$`terraform output -raw ${key}`;
|
|
|
|
return output.stdout.trim();
|
|
|
|
}
|
2024-09-02 04:58:24 -07:00
|
|
|
|
|
|
|
async extractPrivateKey() {
|
|
|
|
await this.$$`terraform output -raw ssh_private_key > privatekey.pem`;
|
|
|
|
await this.$$`chmod 600 privatekey.pem`;
|
|
|
|
|
|
|
|
return 'privatekey.pem';
|
|
|
|
}
|
2024-08-23 04:43:26 -07:00
|
|
|
}
|