Sha256: fa0f02cd46680f943e9af80cb8f999e14f2a7820b1f2c95e606cf783509fba82

Contents?: true

Size: 1.62 KB

Versions: 7

Compression:

Stored size: 1.62 KB

Contents

require 'picsolve_docker_builder/base'
require 'fileutils'
require 'securerandom'

module PicsolveDockerBuilder
  module Helpers
    # Ruby class that forwards a ssh auth socket into a docker container
    class SshAuthForwarding
      include PicsolveDockerBuilder::Base

      def initialize
        fail 'Environment var SSH_AUTH_SOCK not found, ssh forward impossible' \
          if env_ssh_auth_sock.nil?
      end

      def generate_dir_path
        File.join(
          File.dirname(env_ssh_auth_sock),
          "docker_builder_temp_#{SecureRandom.hex(2)}"
        )
      end

      def create_dir
        dir = generate_dir_path
        begin
          Dir.mkdir(dir, 0700)
          # ensure cleanup
          at_exit do
            cleanup(dir)
          end
        rescue Errno::EEXIST
          FileUtils.rm_rf(dir)
          log.warn "Directory '#{dir}' already exists, removing it"
          retry
        end

        log.debug \
          "Creating temporary dir '#{dir}' for mapping auth socket into docker"
        FileUtils.chmod 0700, dir
        FileUtils.ln env_ssh_auth_sock, File.join(dir, 'ssh_auth_sock')
        dir
      end

      def cleanup(dir = nil)
        # return if nothing to do
        if dir.nil?
          if @dir.nil?
            return
          else
            dir = @dir
            @dir = nil
          end
        end

        log.debug "Removing temporary dir '#{dir}'"
        FileUtils.rm_rf(dir)
      end

      def dir
        @dir ||= create_dir
      end

      def env_var_name
        'SSH_AUTH_SOCK'
      end

      def env_ssh_auth_sock
        ENV[env_var_name]
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
picsolve_docker_builder-0.5.5 lib/picsolve_docker_builder/helpers/ssh_auth_forwarding.rb
picsolve_docker_builder-0.5.4 lib/picsolve_docker_builder/helpers/ssh_auth_forwarding.rb
picsolve_docker_builder-0.5.3 lib/picsolve_docker_builder/helpers/ssh_auth_forwarding.rb
picsolve_docker_builder-0.5.2 lib/picsolve_docker_builder/helpers/ssh_auth_forwarding.rb
picsolve_docker_builder-0.5.1 lib/picsolve_docker_builder/helpers/ssh_auth_forwarding.rb
picsolve_docker_builder-0.5.0 lib/picsolve_docker_builder/helpers/ssh_auth_forwarding.rb
picsolve_docker_builder-0.4.0 lib/picsolve_docker_builder/helpers/ssh_auth_forwarding.rb