Workaround to cancel redundant builds


#1

Since this isn’t a feature on circle2 yet, I’ve written a short ruby script to accomplish this:

#! /usr/bin/env ruby
require 'net/http'
require 'json'

CIRCLE_PROJECT_REPO=ENV["CIRCLE_PROJECT_REPONAME"]
CIRCLE_PROJECT_USER=ENV["CIRCLE_PROJECT_USERNAME"]
CIRCLE_BRANCH=ENV["CIRCLE_BRANCH"]
CIRCLE_BUILD_NUM=ENV["CIRCLE_BUILD_NUM"].to_i
CIRCLE_USER=ENV["CIRCLE_USERNAME"]
CIRCLE_API_TOKEN=ENV["CIRCLE_API_TOKEN"]
CIRCLE_WORKFLOW_ID=ENV["CIRCLE_WORKFLOW_ID"]

CIRCLE_API_BASE_URL ="https://circleci.com/api/v1.1"
GET_CIRCLE_BUILDS_URL="#{CIRCLE_API_BASE_URL}/project/github/#{CIRCLE_PROJECT_USER}/#{CIRCLE_PROJECT_REPO}?circle-token=#{CIRCLE_API_TOKEN}"

puts(GET_CIRCLE_BUILDS_URL)
res = Net::HTTP.get(URI(GET_CIRCLE_BUILDS_URL))
json_res = JSON.parse(res)

# get all previous jobs in other workflows for this user with no ssh users
prev_running_build_nums = []

for build in json_res
  if build["status"] == "running" &&
    build["branch"] == CIRCLE_BRANCH &&
    build["user"]["login"] == CIRCLE_USER &&
    build["build_num"] < CIRCLE_BUILD_NUM &&
    build["workflows"]["workflow_id"] != CIRCLE_WORKFLOW_ID && 
    build["ssh_users"].length == 0

    prev_running_build_nums << build["build_num"]
  end
end
# ensure this gets printed
STDOUT.write("Cancelling the following builds:")
STDOUT.write(prev_running_build_nums)

# cancel build
for build_num in prev_running_build_nums
  cancel_build_url="#{CIRCLE_API_BASE_URL}/project/github/#{CIRCLE_PROJECT_USER}/#{CIRCLE_PROJECT_REPO}/#{build_num}/cancel?circle-token=#{CIRCLE_API_TOKEN}"
  puts(cancel_build_url)
  uri = URI.parse(cancel_build_url)
  request = Net::HTTP::Post.new(uri)
  req_options = {
    use_ssl: true
  }
  res = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
    http.request(request)
  end
end

hopefully it’s useful to others


#2

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.