Class: Terraspace::Terraform::Api::Token

Inherits:
Object
  • Object
show all
Includes:
Util::Logging
Defined in:
lib/terraspace/terraform/api/token.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Util::Logging

#logger

Constructor Details

#initializeToken

Returns a new instance of Token.



6
7
8
9
# File 'lib/terraspace/terraform/api/token.rb', line 6

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

Instance Attribute Details

#tokenObject (readonly)

Returns the value of attribute token.



5
6
7
# File 'lib/terraspace/terraform/api/token.rb', line 5

def token
  @token
end

Class Method Details

.getObject



61
62
63
# File 'lib/terraspace/terraform/api/token.rb', line 61

def self.get
  new.get
end

Instance Method Details

#error_exit!Object

Internal note only way to get here is to bypass init. Example:

terraspace up demo --no-init


39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/terraspace/terraform/api/token.rb', line 39

def error_exit!
   = @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 #{}
        2. With an env variable: export TERRAFORM_TOKEN=xxx

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

#getObject



11
12
13
14
15
16
17
# File 'lib/terraspace/terraform/api/token.rb', line 11

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

#hostnameObject



53
54
55
# File 'lib/terraspace/terraform/api/token.rb', line 53

def hostname
  ENV['TFC_HOST'] || Terraspace.config.tfc.hostname || 'app.terraform.io'
end

#hostname_configured?Boolean

Returns:

  • (Boolean)


57
58
59
# File 'lib/terraspace/terraform/api/token.rb', line 57

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

#loadObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/terraspace/terraform/api/token.rb', line 19

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