import { execSync } from 'child_process'; import fs from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; import { loadTencentCredentials, tc3Request } from './tencent-lib.mjs'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const root = path.join(__dirname, '..', '..'); const keyPath = path.join(root, 'deploy', 'id_rsa_tencent'); const region = 'ap-nanjing'; const instanceId = process.argv[2] || 'ins-dn3v0znu'; const keyName = 'canteen_deploy_key'; function getPublicKey() { const pubPath = `${keyPath}.pub`; if (fs.existsSync(pubPath)) { return fs.readFileSync(pubPath, 'utf8').trim(); } return execSync(`ssh-keygen -y -f "${keyPath}"`, { encoding: 'utf8' }).trim(); } async function main() { const { secretId, secretKey } = loadTencentCredentials(); const cred = { secretId, secretKey }; const publicKey = getPublicKey(); console.log('Importing key pair...'); const imported = await tc3Request({ ...cred, service: 'cvm', region, action: 'ImportKeyPair', version: '2017-03-12', payload: { KeyName: keyName, PublicKey: publicKey, ProjectId: 0 }, }); if (imported.Response?.Error) { const code = imported.Response.Error.Code; if (code !== 'InvalidKeyPairName.Duplicate' && code !== 'InvalidParameterValue.KeyPairAlreadyExists') { throw new Error(`${code}: ${imported.Response.Error.Message}`); } console.log('Key pair already exists, reusing...'); } let keyId = imported.Response?.KeyId; if (!keyId) { const listed = await tc3Request({ ...cred, service: 'cvm', region, action: 'DescribeKeyPairs', version: '2017-03-12', payload: { Filters: [{ Name: 'key-name', Values: [keyName] }] }, }); keyId = listed.Response?.KeyPairSet?.[0]?.KeyId; } if (!keyId) throw new Error('Could not resolve KeyId'); console.log(`Associating ${keyId} -> ${instanceId}`); let assoc = await tc3Request({ ...cred, service: 'cvm', region, action: 'ModifyInstancesAttribute', version: '2017-03-12', payload: { InstanceIds: [instanceId], LoginSettings: { KeyIds: [keyId] }, }, }); if (assoc.Response?.Error) { console.log('ModifyInstancesAttribute failed, trying AssociateInstancesKeyPairs...'); assoc = await tc3Request({ ...cred, service: 'cvm', region, action: 'AssociateInstancesKeyPairs', version: '2017-03-12', payload: { InstanceIds: [instanceId], KeyIds: [keyId], ForceStop: false }, }); } if (assoc.Response?.Error) { throw new Error(`${assoc.Response.Error.Code}: ${assoc.Response.Error.Message}`); } console.log('OK: SSH key bound to instance. Wait ~30s then retry SSH.'); } main().catch((err) => { console.error(err.message || err); process.exit(1); });