class BuildAppImage

Public Instance Methods

main() click to toggle source
# File lib/build_app_image.rb, line 5
def main
  options = get_options

  gcr_url = "gcr.io/#{options[:project_id]}/#{options[:image_repo]}"

  image_url = build_image(gcr_url, options)
end

Private Instance Methods

build_image(gcr_url, options) click to toggle source
# File lib/build_app_image.rb, line 64
def build_image(gcr_url, options)
  commit_image_tag = ENV['CI_COMMIT_SHORT_SHA'] || `git rev-parse --short HEAD`
  time_image_tag=`TZ=IST-5:30 date +'%Y.%m.%d.%HH.%MM.%SS'`
  commit_image_url = "#{gcr_url}:#{commit_image_tag}".strip
  time_image_url = "#{gcr_url}:#{time_image_tag}".strip

  project_id = options[:project_id]

  shell_cmd("gcloud builds submit --project #{project_id} --timeout=20m --tag #{time_image_url} || true")

  shell_cmd("gcloud container images add-tag --quiet #{time_image_url} #{commit_image_url}")

  opt_image_url = options[:image_tag] && "#{gcr_url}:#{options[:image_tag]}"

  opt_image_url && shell_cmd("gcloud container images add-tag --quiet #{time_image_url} #{opt_image_url}")
  shell_cmd("echo \"IMAGE_TAG=#{commit_image_tag}\" >> build.env")
end
get_options() click to toggle source
# File lib/build_app_image.rb, line 14
def get_options
  options = {}

  require_options_keys = [:project_id, :image_repo]

  opt_parser = OptionParser.new do |opts|
    opts.banner = "Usage: ather build [options]"

    opts.on("--image-tag IMAGE_TAG", "Addtional Image tag to build [optional]") do |val|
      options[:image_tag] = val
    end

    opts.on("--project-id PROJECT_ID", "GCP project id [required or set env var PROJECT_ID]") do |val|
      options[:project_id] = val
    end

    opts.on("--image-repo IMAGE_REPO", "Image repo to deploy [required or set env var IMAGE_REPO]") do |val|
      options[:image_repo] = val
    end

    opts.on("-h", "--help", "Prints this help") do
      puts opts
      exit
    end
  end

  opt_parser.parse!

  require_options_keys.each do |key|
    options[key] ||= ENV[key.to_s.upcase]
    if options[key].nil?
      puts "ERROR: Required option --#{key.to_s.gsub('_', '-')} or set env var #{key.to_s.upcase} \n"
      opt_parser.parse! %w[--help]
      exit 1
    end
  end

  options
end
shell_cmd(cmd) click to toggle source
# File lib/build_app_image.rb, line 54
def shell_cmd(cmd)
  puts "EXECUTING : \e[32m\e[1m#{cmd}\e[22m\e[0m"
  op = system(cmd)
  if !op
    puts "FAILED : \e[31m\e[1m#{cmd}\e[22m\e[0m"
    exit 1
  end
  puts "SUCCESS : \e[32m\e[1m#{cmd}\e[22m\e[0m"
end