class Hashicorptools::CodeDeploy

Constants

AWS_REGION_US_EAST_1

Attributes

git[R]

Public Instance Methods

deploy() click to toggle source
# File lib/hashicorptools/code_deploy.rb, line 60
def deploy
  @git = Git.open('..')

  # We set defaults (depending on environment) for aws_regions if not passed in
  aws_regions = options[:aws_regions] || default_regions

  commit = if options[:commit].present?
             git.gcommit(options[:commit])
           else
             branch = options[:branch].nil? ? :main : options[:branch].to_sym
             git.checkout(branch)
             git.log.first
           end

  puts "Deploying to environment #{options[:environment]} - regions: #{aws_regions.join(', ')}
        commit: #{commit.sha}
        message: #{commit.message}"

  puts "Deploying for regions: #{aws_regions}"

  all_succeeded = true
  aws_regions.each_slice(2) do |aws_regions_batch|
    puts "Deploying for batch of regions: #{aws_regions_batch}"

    threads = []
    aws_regions_batch.each do |aws_region|
      thread = Thread.new{ region_deployment(aws_region).create_deployment(commit.sha, commit.message) }
      threads.push(thread)
    end

    threads.each_with_index do |thread, index|
      begin
        # thread.value waits for the thread to finish with #join, then returns the value of the expression
        thread_succeeded = thread.value
        all_succeeded = all_succeeded && thread_succeeded
      rescue StandardError => e
        # Don't quit whole program on exception in thread, just print exception and exit thread
        puts "[#{aws_regions[index]}] EXCEPTION: #{e}"
        all_succeeded = false
      end
    end
  end

  # If deployment succeeded, tag the commit that was deployed for the environment
  if all_succeeded
    create_tag(options[:environment], commit)
  end

  # Return a success or failure status code to be consumed by bash
  exit(all_succeeded)
end

Private Instance Methods

create_tag(environment, commit) click to toggle source
# File lib/hashicorptools/code_deploy.rb, line 122
def create_tag(environment, commit)
  # Delete previous tag in the remote repository
  git.push('origin', ":#{environment}")

  # Create the tag (replacing if it already exists) and push to remote repository
  git.add_tag(environment, commit.sha, {f: true})
  git.push('origin', environment)
end
default_regions() click to toggle source
# File lib/hashicorptools/code_deploy.rb, line 118
def default_regions
  [AWS_REGION_US_EAST_1]
end
region_deployment(aws_region) click to toggle source
# File lib/hashicorptools/code_deploy.rb, line 114
def region_deployment(aws_region)
  RegionDeployment.new(aws_region: aws_region, environment: options[:environment])
end