Skip to content

Instantly share code, notes, and snippets.

@aliasmee
Created August 23, 2018 06:28
Show Gist options
  • Save aliasmee/25d0c26304c60999f7c10e1d6c48180a to your computer and use it in GitHub Desktop.
Save aliasmee/25d0c26304c60999f7c10e1d6c48180a to your computer and use it in GitHub Desktop.
using groovy script generate multi cronjob yaml from a template
apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: ${jobName}
labels:
app: data-job
spec:
schedule: "${cronTime}"
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 3
jobTemplate:
spec:
template:
spec:
containers:
- name: data
image: hub.docker.io/testimage:${imageTag}
envFrom:
- configMapRef:
name: some-cm
args:
- /bin/bash
- -l
- -c
- ${jobCommand}
restartPolicy: OnFailure
#!groovy
/*
Document: Extract job information from k8s_jobs.txt. Generate kubernetes cronjob yaml.
*/
def jobFileName = "./k8s_jobs.txt"
def jobManifest = new File(jobFileName)
//def regex = /^(\S.*\*+?)\s+JOB_NAME=(\S.*)\s+(cd\s.*)/
def regex = /^(\S.*\*+?)\s+JOB_NAME=(\S.*?)\s(.*?)$/
def jobPattern = ~regex
def jobTemlateFile = new File("./cronJobTemplate.yaml")
def targetPath = "./jobs"
def imageTag = "IMAGE_TAG"
def jobGenerator(jobFile, pattern, templateFile, targetFilePath, currentBranch) {
if ( !new File(targetFilePath).exists() ) {
new File(targetFilePath).mkdirs()
}
jobFile.eachLine { line->
if (( matcher = line =~ pattern )) {
jobList = [ jobName: matcher[0][2].replaceAll("::","-").toLowerCase(), cronTime: matcher[0][1], jobCommand: matcher[0][3], imageTag: "$currentBranch"]
templateEngine = new groovy.text.GStringTemplateEngine()
converteFile = templateEngine.createTemplate(templateFile).make(jobList)
File targetFile = new File("${targetFilePath}/${matcher[0][2].replaceAll("::","-")}.yaml")
targetFile.text = converteFile.toString()
}
}
}
jobGenerator(jobManifest, jobPattern, jobTemlateFile, targetPath, imageTag)
0,15,30,45 * * * * JOB_NAME=Etl::Invest cd /app && some command
0,15,30,45 * * * * JOB_NAME=Etl::NewsWorker cd /app && some command
0 * * * * JOB_NAME=Takeover cd /app && some command
0 * * * * JOB_NAME=JointInves cd /app && some command
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment