Skip to content

Instantly share code, notes, and snippets.

@vicsz
Last active September 11, 2021 07:51
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save vicsz/b04c31f27a91b0d32b55b1bf718ab705 to your computer and use it in GitHub Desktop.
Gradle Bamboo Deploy Release Branch Task
import groovy.json.JsonSlurper
/*
Gradle commandLine task to trigger deployments from release branches
This will trigger deployments for all Deployment Projects for specific plan
Note that bambooUsername and bambooPassword need to be set (environment variables)
.. also for first time usage override the bambooUrl variable, and rootPlanKey
examples:
gradle release43toQa //Deploy release43 to Qa environments
gradle release42toProd //Deploy release42 to Prod environments
Note: this was tested on Bamboo 6.1. The deployment REST API stuff was added recently , so it will no work on older versions of Bamboo (5.7)
*/
tasks.addRule("Pattern: release<version>to<env>") { String taskName ->
def regexMatcher = taskName =~ /release(?<version>\d+)to(?<env>\w+)/
if (regexMatcher.matches()) {
task(taskName) {
doLast {
String version = regexMatcher.group('version')
String environmentName = regexMatcher.group('env')
String rootPlanKey = 'MY-KEY'
//GetBranchPlanKey
Object branchPlan = bambooGet("plan/${rootPlanKey}/branch/release-${version}")
if (branchPlan == null)
throw new IllegalArgumentException("Unable to find branch release-${version} for planKey ${rootPlanKey}")
//Wait for build to finish
while (bambooGet("plan/${branchPlan.key}").isBuilding){
sleep(2000)
println "Waiting for plan to finish"
}
//Get Build Info
Object buildResult = bambooGet("result/${branchPlan.key}-latest")
//Build Release Name is -- Branch Name + Build Number , as per Bamboo defaults
String buildReleaseName = "${buildResult.planName}-${buildResult.buildNumber}"
//Get Related Deployment Projects
Object deploymentProjects = bambooGet("deploy/project/forPlan?planKey=${rootPlanKey}")
deploymentProjects.each { deploymentProject ->
//Get Deployment Project Details
Object deploymentProjectDetails = bambooGet("deploy/project/${deploymentProject.id}")
//Get Environment
Object environment = deploymentProjectDetails.environments.find {
it.name.equalsIgnoreCase(environmentName)
}
if (environment == null)
throw new IllegalArgumentException("Unable to find environment $environmentName for deployment project $deploymentProjectDetails.name")
//Create Release if one doesn't exist already
Object release = bambooGet("deploy/project/${deploymentProject.id}/versions").versions.find { it.name == buildReleaseName }
if (release == null) {
release = bambooPost("deploy/project/${deploymentProject.id}/version", "{\"planResultKey\" : \"${buildResult.buildResultKey}\", \"name\" : \"${buildReleaseName}\"}")
}
println "Triggering ${buildReleaseName} deployment to ${environmentName} on ${deploymentProjectDetails.name}"
//Invoke actual deploy
bambooPost("queue/deployment/?environmentId=${environment.id}&versionId=${release.id}")
}
}
}
}
}
HttpURLConnection getBambooConnection(String url){
String username = System.env.bambooUsername
String password = System.env.bambooPassword
String bambooUrl = 'http://myBamboo.address.com'
if(username==null || password==null)
throw new IllegalArgumentException("Please ensure bambooUsername and bambooPassword are configured with correct values.")
HttpURLConnection connection = new URL("${bambooUrl}/rest/api/latest/${url}${url.contains("?")?"":"/.json?max-result=2000"}").openConnection() as HttpURLConnection
connection.addRequestProperty("Authorization","Basic " + (username + ":" + password).bytes.encodeBase64().toString())
return connection
}
Object bambooPost(String url, String content = null){
HttpURLConnection connection = getBambooConnection(url)
connection.setDoInput(true)
connection.setUseCaches(false)
connection.setRequestProperty( "Content-Type", "application/json" )
connection.setRequestProperty("Accept", "application/json")
connection.setRequestMethod("POST")
if(content != null) {
connection.setDoOutput(true)
connection.outputStream.withWriter { it.write(content) }
}
if(connection.getResponseCode() != 200)
println connection.errorStream.text
return new JsonSlurper().parseText(connection.inputStream.text)
}
Object bambooGet(String url){
HttpURLConnection connection = getBambooConnection(url)
if(connection.getResponseCode() != 200)
println connection.errorStream.text
return new JsonSlurper().parseText(connection.inputStream.text)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment