Class: Terraspace::Terraform::Api::Var

Inherits:
Object
  • Object
show all
Extended by:
Memoist
Includes:
Client, Util::Logging
Defined in:
lib/terraspace/terraform/api/var.rb

Constant Summary collapse

@@current_vars_resp =
nil

Instance Method Summary collapse

Methods included from Util::Logging

#logger

Methods included from Client

#http

Constructor Details

#initialize(workspace, attrs = {}) ⇒ Var

Returns a new instance of Var.



7
8
9
10
# File 'lib/terraspace/terraform/api/var.rb', line 7

def initialize(workspace, attrs={})
  @workspace, @attrs = workspace, attrs
  @workspace_id = @workspace['id']
end

Instance Method Details

#categoryObject



63
64
65
# File 'lib/terraspace/terraform/api/var.rb', line 63

def category
  @attrs['category'] || 'terraform' # default category when not set is terraform
end

#createObject



37
38
39
40
# File 'lib/terraspace/terraform/api/var.rb', line 37

def create
  logger.info "Creating Terraform Cloud #{category} variable: #{@attrs['key']}"
  http.post("workspaces/#{@workspace_id}/vars", payload)
end

#current_var_respObject



55
56
57
58
59
60
61
# File 'lib/terraspace/terraform/api/var.rb', line 55

def current_var_resp
  current_vars_resp['data'].find do |item|
    attributes = item['attributes']
    attributes['key'] == @attrs['key'] &&
    attributes['category'] == category
  end
end

#current_vars_respObject



68
69
70
# File 'lib/terraspace/terraform/api/var.rb', line 68

def current_vars_resp
  @@current_vars_resp ||= http.get("workspaces/#{@workspace_id}/vars")
end

#exist?Boolean

Returns:

  • (Boolean)


51
52
53
# File 'lib/terraspace/terraform/api/var.rb', line 51

def exist?
  !!current_var_resp
end

#overwrite?Boolean

Returns:

  • (Boolean)


24
25
26
27
28
29
30
31
# File 'lib/terraspace/terraform/api/var.rb', line 24

def overwrite?
  cloud = Terraspace.config.cloud
  if @attrs['sensitive']
    cloud.overwrite_sensitive
  else
    cloud.overwrite
  end
end

#payload(id = nil) ⇒ Object



42
43
44
45
46
47
48
49
# File 'lib/terraspace/terraform/api/var.rb', line 42

def payload(id=nil)
  data = {
    type: "vars",
    attributes: @attrs
  }
  data[:id] = id if id
  { data: data }
end

#syncObject



12
13
14
# File 'lib/terraspace/terraform/api/var.rb', line 12

def sync
  exist? ? update : create
end

#updateObject



16
17
18
19
20
21
22
# File 'lib/terraspace/terraform/api/var.rb', line 16

def update
  return unless overwrite?
  logger.debug "Updating Terraform Cloud #{category} variable: #{@attrs['key']}"
  variable_id = variable_id(@attrs['key'])
  payload = payload(variable_id)
  http.patch("workspaces/#{@workspace_id}/vars/#{variable_id}", payload)
end

#variable_id(key) ⇒ Object



33
34
35
# File 'lib/terraspace/terraform/api/var.rb', line 33

def variable_id(key)
  current_var_resp['id']
end