Sha256: fa4d09f25638a6222f785cde82d8bb7db3329ab5d8f9ec0e5e22b7b16a40dbb6

Contents?: true

Size: 1.69 KB

Versions: 25

Compression:

Stored size: 1.69 KB

Contents

class Terraspace::Terraform::Api
  class Token
    include Terraspace::Util::Logging

    attr_reader :token
    def initialize
      @creds_path = "#{ENV['HOME']}/.terraform.d/credentials.tfrc.json"
      @hostname = hostname
    end

    def get
      @token = ENV['TERRAFORM_TOKEN']
      return @token if @token
      @token = load
      return @token if @token
      error_exit!
    end

    def load
      return unless File.exist?(@creds_path)

      data = JSON.load(IO.read(@creds_path))
      @token = data.dig('credentials', @hostname, 'token')
      return @token if @token

      return unless hostname_configured?
      logger.error "You configured a cloud.hostname: #{@hostname}".color(:red)
      logger.error <<~EOL
        But it was not found into your #{@creds_path}
        Please double check it.
      EOL
      @token
    end

    # Internal note only way to get here is to bypass init. Example:
    #
    #     terraspace up demo --no-init
    #
    def error_exit!
      login_hostname = @hostname if hostname_configured?
      logger.error "ERROR: Unable to not find a Terraform token. A Terraform token is needed for Terraspace to call the Terraform API.".color(:red)
      logger.error <<~EOL
        Here are some ways to provide the Terraform token:

            1. By running: terraform login #{login_hostname}
            2. With an env variable: export TERRAFORM_TOKEN=xxx

        Please configure a Terraform token and try again.
      EOL
      exit 1
    end

    def hostname
      ENV['TS_HOST'] || Terraspace.config.cloud.hostname || 'app.terraform.io'
    end

    def hostname_configured?
      !!Terraspace.config.cloud.hostname
    end

    def self.get
      new.get
    end
  end
end

Version data entries

25 entries across 25 versions & 1 rubygems

Version Path
terraspace-0.3.4 lib/terraspace/terraform/api/token.rb
terraspace-0.3.3 lib/terraspace/terraform/api/token.rb
terraspace-0.3.2 lib/terraspace/terraform/api/token.rb
terraspace-0.3.1 lib/terraspace/terraform/api/token.rb
terraspace-0.3.0 lib/terraspace/terraform/api/token.rb