deploy-image/src/main.ts
2025-06-15 20:40:36 +08:00

92 lines
3.0 KiB
TypeScript

import * as core from '@actions/core'
import * as k8s from '@kubernetes/client-node'
import * as fs from 'fs'
import * as path from 'path'
import { filter, clone } from 'lodash'
import { Agent } from 'https'
interface Config {
branch: string
cluster: string
namespace: string
deployment: string
}
const insecureAgent = new Agent({
rejectUnauthorized: false
})
/**
* The main function for the action.
*
* @returns Resolves when the action is complete.
*/
export async function run(): Promise<void> {
try {
//
const configPath = core.getInput('config-path')
console.log('configPath:', configPath)
//
const clusterPath = core.getInput('cluster-path')
console.log('clusterPath:', clusterPath)
//
const deployImage: string = core.getInput('image')
console.log('image:', deployImage)
//
const branch: string = String(process.env.GITHUB_REF_NAME)
console.log('branch:', branch)
//
const workspace: string = String(process.env.GITHUB_WORKSPACE)
console.log('workspace:', workspace)
//
const configJson = fs.readFileSync(path.join(workspace, configPath), 'utf8')
console.log('configJson:', configJson)
const deployConfigArr = JSON.parse(configJson) as Config[]
console.log('deployConfigArr:', deployConfigArr)
const filterDeployConfig = filter(deployConfigArr, { branch: branch })
for (const deployConfig of filterDeployConfig) {
console.log('deployConfig:', deployConfig)
const kc = new k8s.KubeConfig()
kc.loadFromFile(
path.join(workspace, clusterPath + deployConfig.cluster + '.yaml')
)
await kc.applyToHTTPSOptions({
httpsAgent: insecureAgent
})
const k8sApi = kc.makeApiClient(k8s.AppsV1Api)
const nowDeployment = await k8sApi.readNamespacedDeployment({
name: deployConfig.deployment,
namespace: deployConfig.namespace
})
console.log('nowDeployment:', nowDeployment)
const deployment = clone(nowDeployment)
if (deployment.spec === undefined) {
console.log('deployment.spec is missing')
continue
}
if (deployment.spec.template.spec === undefined) {
console.log('deployment.spec.template.spec is missing')
continue
}
if (deployment.spec.template.spec.containers.length === 0) {
console.log('deployment.spec.template.spec.containers is zero')
continue
}
deployment.spec.template.spec.containers[0].image = deployImage
const deployRes =
await k8s.KubernetesObjectApi.makeApiClient(kc).patch(nowDeployment)
// const deployRes = await k8sApi.patchNamespacedDeployment({
// name: deployConfig.deployment,
// namespace: deployConfig.namespace,
// body: {
// spec: { template: { spec: { containers: [{ image: deployImage }] } } }
// }
// })
console.log('deployRes:', deployRes)
}
} catch (error) {
// Fail the workflow run if an error occurs
if (error instanceof Error) core.setFailed(error.message)
}
}