vagrant-terraform 0.4 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
1
  require "log4r"
2
2
  require 'vagrant-terraform/util/terraform_execute'
3
3
  require 'vagrant-terraform/util/machine_names'
4
-
5
- $terraform_refreshed = nil
4
+ require 'vagrant-terraform/util/terraform_state'
5
+ require 'vagrant-terraform/util/proxmox_api'
6
6
 
7
7
  module VagrantPlugins
8
8
  module TerraformProvider
@@ -24,42 +24,69 @@ module VagrantPlugins
24
24
  end
25
25
 
26
26
  def read_state(env)
27
- env[:machine_tf_dir] = ".vagrant/terraform/#{machine_vmname(env[:machine])}"
27
+ env[:machine_tf_dir] = terraform_dir(env[:machine])
28
28
  terraform_state_file = "#{env[:machine_tf_dir]}/terraform.tfstate"
29
- if File.exist?(env[:machine_tf_dir]) && File.exist?(terraform_state_file)
30
- # read_state might get called several times. Avoid refreshing 5 times in a row
31
- # for example during "vagrant up" for no obvious reason.
32
- if $terraform_refreshed.nil?
33
- terraform_execute(env, 'terraform refresh', 'is not running')
34
- $terraform_refreshed = true
35
- end
29
+ return :not_created unless File.exist?(env[:machine_tf_dir]) && File.exist?(terraform_state_file)
36
30
 
37
- json_data = File.read(terraform_state_file)
38
- data = JSON.parse(json_data)
31
+ # read_state might get called several times. Avoid refreshing 5 times in a row
32
+ # for example during "vagrant up" for no obvious reason. Tracked per
33
+ # machine: a single process may read the state of several machines
34
+ # (multi-machine `vagrant status`, `vagrant global-status --prune`),
35
+ # and each one needs its own refresh.
36
+ unless terraform_refreshed?(env[:machine_tf_dir])
37
+ terraform_execute(env, 'terraform refresh', 'is not running')
38
+ end
39
39
 
40
- # Navigate to the "vm_state" value
41
- resources = data["resources"]
42
- return :not_created if resources.nil? || resources.empty?
40
+ attributes = Util::TerraformState.read_attributes(terraform_state_file)
41
+ return :not_created if attributes.nil?
43
42
 
44
- first_resource = resources.first # TODO: find by name
45
- instances = first_resource["instances"]
46
- return :not_created if instances.nil? || instances.empty?
43
+ if env[:machine].provider_config.guest_type == :container
44
+ read_container_state(env, attributes)
45
+ else
46
+ read_vm_state(env, attributes)
47
+ end
48
+ end
47
49
 
48
- attributes = instances.first["attributes"]
49
- return :not_created if attributes.nil?
50
- return :not_created if attributes["vm_state"].nil?
50
+ def read_vm_state(env, attributes)
51
+ return :not_created if attributes["vm_state"].nil?
51
52
 
52
- ip_addr = attributes["default_ipv4_address"]
53
- unless ip_addr.nil?
54
- env[:ip_address] = ip_addr
55
- end
53
+ ip_addr = attributes["default_ipv4_address"]
54
+ env[:ip_address] = ip_addr unless ip_addr.nil?
56
55
 
57
- return attributes["vm_state"].to_sym
58
- else
59
- return :not_created
56
+ attributes["vm_state"].to_sym
57
+ end
58
+
59
+ def read_container_state(env, attributes)
60
+ vmid = attributes["vmid"]
61
+ return :not_created if vmid.nil?
62
+
63
+ config = env[:machine].provider_config
64
+ node = Util::ProxmoxApi.container_node(attributes, config)
65
+
66
+ begin
67
+ status = Util::ProxmoxApi.container_status(config, node, vmid)
68
+ rescue Errors::ProxmoxApiError => e
69
+ # Don't let an unreachable API (or a token lacking rights) abort
70
+ # every command: report :unknown, which still counts as created,
71
+ # so `vagrant destroy` can proceed (terraform resolves the
72
+ # container itself) and `global-status --prune` keeps the entry.
73
+ @logger.warn("container status lookup failed: #{e.message}")
74
+ env[:ui].warn("Unable to read container #{vmid} state from Proxmox node '#{node}': #{e.message}")
75
+ return :unknown
60
76
  end
77
+
78
+ if status == :running
79
+ begin
80
+ ip = Util::ProxmoxApi.container_ip(config, node, vmid)
81
+ env[:ip_address] = ip unless ip.nil?
82
+ rescue Errors::ProxmoxApiError => e
83
+ @logger.debug("container IP lookup failed: #{e.message}")
84
+ end
85
+ end
86
+
87
+ status
61
88
  end
62
89
  end
63
90
  end
64
91
  end
65
- end
92
+ end
@@ -2,6 +2,7 @@ require 'log4r'
2
2
  require 'vagrant-terraform/errors'
3
3
  require 'vagrant-terraform/util/terraform_execute'
4
4
  require 'vagrant-terraform/util/update_vm_state'
5
+ require 'vagrant-terraform/util/proxmox_api'
5
6
 
6
7
  module VagrantPlugins
7
8
  module TerraformProvider
@@ -24,9 +25,16 @@ module VagrantPlugins
24
25
 
25
26
  begin
26
27
  terraform_dir = env[:machine_tf_dir]
27
- terraform_main_file = "#{terraform_dir}/main.tf"
28
- update_vm_state(terraform_main_file, "running")
29
- terraform_execute(env, 'terraform apply -auto-approve')
28
+ if config.guest_type == :container
29
+ # Via the API, not terraform: see ProxmoxApi.set_container_power.
30
+ ref = Util::ProxmoxApi.container_ref(terraform_dir, config)
31
+ raise Errors::StartVMError, :error_message => "no container found in #{terraform_dir}/terraform.tfstate" if ref.nil?
32
+ Util::ProxmoxApi.set_container_power(config, *ref, :running)
33
+ else
34
+ terraform_main_file = "#{terraform_dir}/main.tf"
35
+ update_vm_state(terraform_main_file, "vm_state", "\"running\"")
36
+ terraform_execute(env, 'terraform apply -auto-approve')
37
+ end
30
38
  rescue Exception => e
31
39
  fault_message = /Error was \"\[?(.+?)\]?\".*/.match(e.message)[1] rescue e.message
32
40
  # TODO: retry in some case?
@@ -0,0 +1,40 @@
1
+ require "log4r"
2
+
3
+ module VagrantPlugins
4
+ module TerraformProvider
5
+ module Action
6
+ # Wraps a state-changing action chain and, once it has finished,
7
+ # refreshes this machine's entry in Vagrant's global machine index
8
+ # (what `vagrant global-status` displays).
9
+ #
10
+ # Vagrant core only writes the index entry's state in two places:
11
+ # Machine#id= (sets it to "preparing" when the machine is first
12
+ # created) and Machine#state (sets it to the provider's current short
13
+ # state). Our up/halt chains read state via the ReadState middleware
14
+ # directly, never via Machine#state, so without this a freshly created
15
+ # VM stays "preparing" and a halted one stays "running" in
16
+ # global-status until someone happens to run `vagrant status`.
17
+ class UpdateIndexState
18
+ def initialize(app, env)
19
+ @app = app
20
+ @logger = Log4r::Logger.new("vagrant_terraform::action::update_index_state")
21
+ end
22
+
23
+ def call(env)
24
+ @app.call(env)
25
+
26
+ # No id means the machine isn't (or is no longer) registered in
27
+ # the index; Machine#state would have nothing to update.
28
+ return if env[:machine].id.nil?
29
+
30
+ begin
31
+ env[:machine].state
32
+ rescue => e
33
+ # Purely bookkeeping: don't fail an otherwise successful action.
34
+ @logger.warn("failed to refresh machine index state: #{e.class}: #{e.message}")
35
+ end
36
+ end
37
+ end
38
+ end
39
+ end
40
+ end
@@ -3,6 +3,7 @@ require 'socket'
3
3
  require 'timeout'
4
4
  require 'vagrant-terraform/util/timer'
5
5
  require 'vagrant-terraform/util/terraform_execute'
6
+ require 'vagrant-terraform/util/proxmox_api'
6
7
  require 'net/ssh'
7
8
 
8
9
  module VagrantPlugins
@@ -54,16 +55,27 @@ module VagrantPlugins
54
55
  def call(env)
55
56
  # Initialize metrics if they haven't been
56
57
  env[:metrics] ||= {}
58
+ config = env[:machine].provider_config
57
59
 
58
- # Wait for VM to obtain an ip address.
60
+ # Wait for VM/container to obtain an ip address.
59
61
  env[:metrics]["instance_ip_time"] = Util::Timer.time do
60
62
  env[:ui].info(I18n.t("vagrant_terraform.waiting_for_ip"))
61
63
  for attempt in 1..100
62
64
  # If we're interrupted don't worry about waiting
63
65
  next if env[:interrupted]
64
66
 
65
- output = terraform_execute(env, "terraform refresh")
66
- ip_addr = output.match(/\b(?:\d{1,3}\.){3}\d{1,3}\b/)&.to_s
67
+ ip_addr = if config.guest_type == :container
68
+ begin
69
+ Util::ProxmoxApi.container_ip_for_machine(env[:machine_tf_dir], config)
70
+ rescue Errors::ProxmoxApiError => e
71
+ @logger.debug("container IP lookup failed, retrying: #{e.message}")
72
+ nil
73
+ end
74
+ else
75
+ output = terraform_execute(env, "terraform refresh")
76
+ output.match(/\b(?:\d{1,3}\.){3}\d{1,3}\b/)&.to_s
77
+ end
78
+
67
79
  unless ip_addr.nil?
68
80
  env[:ui].info("Got IP (attempt #{attempt}): #{ip_addr}")
69
81
  # Check if SSH-Server is up
@@ -1,5 +1,6 @@
1
1
  require 'fileutils'
2
2
  require 'vagrant/action/builder'
3
+ require 'vagrant-terraform/util/machine_names'
3
4
 
4
5
  module VagrantPlugins
5
6
  module TerraformProvider
@@ -12,6 +13,7 @@ module VagrantPlugins
12
13
  Vagrant::Action::Builder.new.tap do |b|
13
14
  b.use HandleBox
14
15
  b.use ConfigValidate
16
+ b.use UpdateIndexState
15
17
 
16
18
  b.use Call, ReadState do |env, b2|
17
19
  b2.use SetupTerraform
@@ -26,7 +28,11 @@ module VagrantPlugins
26
28
  end
27
29
 
28
30
  if env[:machine_state_id] == :not_created
29
- b2.use CreateVM
31
+ if env[:machine].provider_config.guest_type == :container
32
+ b2.use CreateContainer
33
+ else
34
+ b2.use CreateVM
35
+ end
30
36
  b2.use Provision
31
37
  b2.use SetHostname
32
38
  end
@@ -47,9 +53,15 @@ module VagrantPlugins
47
53
  b.use Call, IsCreated do |env, b2|
48
54
  if !env[:result]
49
55
  unless env[:machine].id.nil?
50
- dir = ".vagrant/terraform/#{env[:machine].id}"
56
+ dir = Util::MachineNames.terraform_dir(env[:machine])
51
57
  env[:ui].info("Removing: " + dir)
52
58
  FileUtils.rm_rf(dir)
59
+ # Deregister too: clears .vagrant/machines/<name>/<provider>/id
60
+ # and deletes the global machine index entry, which would
61
+ # otherwise linger in `vagrant global-status` with whatever
62
+ # state it last had (e.g. "running") for a machine that no
63
+ # longer exists.
64
+ env[:machine].id = nil
53
65
  end
54
66
  env[:ui].info(I18n.t("vagrant_terraform.not_created"))
55
67
  next
@@ -105,6 +117,7 @@ module VagrantPlugins
105
117
 
106
118
  def self.action_halt
107
119
  Vagrant::Action::Builder.new.tap do |b|
120
+ b.use UpdateIndexState
108
121
  b.use Call, IsRunning do |env, b2|
109
122
  if env[:machine_state_id] == :powering_up
110
123
  env[:ui].info(I18n.t("vagrant_terraform.powering_up"))
@@ -170,6 +183,7 @@ module VagrantPlugins
170
183
  action_root = Pathname.new(File.expand_path("../action", __FILE__))
171
184
  autoload :SetupTerraform, action_root.join("setup_terraform")
172
185
  autoload :CreateVM, action_root.join("create_vm")
186
+ autoload :CreateContainer, action_root.join("create_container")
173
187
  autoload :DestroyVM, action_root.join("destroy_vm")
174
188
  autoload :HaltVM, action_root.join("halt_vm")
175
189
  autoload :IsCreated, action_root.join("is_created")
@@ -179,6 +193,7 @@ module VagrantPlugins
179
193
  autoload :WaitForVmUp, action_root.join("wait_for_vm_up")
180
194
 
181
195
  autoload :StartVM, action_root.join("start_vm")
196
+ autoload :UpdateIndexState, action_root.join("update_index_state")
182
197
  # autoload :SyncedFolders, 'vagrant/action/builtin/synced_folders'
183
198
  autoload :SyncedFolderCleanup, 'vagrant/action/builtin/synced_folder_cleanup'
184
199
  end
@@ -4,6 +4,9 @@ require 'filesize'
4
4
  module VagrantPlugins
5
5
  module TerraformProvider
6
6
  class Config < Vagrant.plugin('2', :config)
7
+ VMID_MIN = 10000
8
+ VMID_MAX = 999999999
9
+
7
10
  attr_reader :disks
8
11
 
9
12
  attr_accessor :api_url
@@ -29,6 +32,9 @@ module VagrantPlugins
29
32
  attr_accessor :full_clone
30
33
  attr_accessor :serial_port
31
34
  attr_accessor :vmid
35
+ attr_accessor :guest_type
36
+ attr_accessor :ostemplate
37
+ attr_accessor :unprivileged
32
38
 
33
39
  def initialize
34
40
  @api_url = UNSET_VALUE
@@ -54,6 +60,9 @@ module VagrantPlugins
54
60
  @full_clone = UNSET_VALUE
55
61
  @serial_port = UNSET_VALUE
56
62
  @vmid = UNSET_VALUE
63
+ @guest_type = UNSET_VALUE
64
+ @ostemplate = UNSET_VALUE
65
+ @unprivileged = UNSET_VALUE
57
66
  end
58
67
 
59
68
  def finalize!
@@ -82,44 +91,120 @@ module VagrantPlugins
82
91
 
83
92
  @vmid = nil if @vmid == UNSET_VALUE
84
93
 
94
+ # Problems found while coercing values. Reported from #validate as a
95
+ # normal Vagrant config error, instead of raising here, which
96
+ # aborts Vagrantfile loading with a raw Ruby stack trace. "@__"
97
+ # keeps them out of Config#merge.
98
+ # (@__vmid_range is deliberately not reset: if finalize! runs again,
99
+ # @vmid is already the Integer picked from the range.)
100
+ @__finalize_errors = []
101
+
85
102
  if @vmid != nil
86
103
  if @vmid.is_a?(String) && @vmid.include?('-')
87
- begin
88
- range = @vmid.split('-').map(&:to_i)
89
- raise if range.size != 2 || range[0] > range[1] || range[0] < 10000 || range[1] > 999999999
90
- @vmid = rand(range[0]..range[1])
91
- rescue
92
- raise "Invalid vmid range format or out of allowed bounds (10000-999999999): #{@vmid}"
104
+ range = @vmid.split('-').map { |v| Integer(v.strip, exception: false) }
105
+ if range.size != 2 || range.include?(nil) || range[0] > range[1] ||
106
+ range[0] < VMID_MIN || range[1] > VMID_MAX
107
+ @__finalize_errors << I18n.t("vagrant_terraform.config.vmid_range_invalid",
108
+ value: @vmid, min: VMID_MIN, max: VMID_MAX)
109
+ @vmid = nil
110
+ else
111
+ # Kept so a VMID conflict at creation can retry with another
112
+ # id from the same range (see #reroll_vmid!).
113
+ @__vmid_range = range[0]..range[1]
114
+ @vmid = rand(@__vmid_range)
93
115
  end
94
116
  else
95
- begin
96
- @vmid = @vmid.to_i
97
- raise if @vmid < 10000 || @vmid > 999999999
98
- rescue
99
- raise "Invalid vmid value or out of allowed bounds (10000-999999999): #{@vmid}"
117
+ value = @vmid.is_a?(Integer) ? @vmid : Integer(@vmid.to_s.strip, exception: false)
118
+ if value.nil? || value < VMID_MIN || value > VMID_MAX
119
+ @__finalize_errors << I18n.t("vagrant_terraform.config.vmid_invalid",
120
+ value: @vmid, min: VMID_MIN, max: VMID_MAX)
121
+ @vmid = nil
122
+ else
123
+ @vmid = value
100
124
  end
101
125
  end
102
126
  end
103
127
 
104
- unless disk_size.nil?
105
- begin
106
- @disk_size = Filesize.from(@disk_size).to_f('B').to_i
107
- rescue ArgumentError
108
- raise "Not able to parse 'disk_size' #{@disk_size}."
128
+ if @guest_type == UNSET_VALUE
129
+ @guest_type = :vm
130
+ else
131
+ @guest_type = @guest_type.to_s.to_sym
132
+ unless [:vm, :container].include?(@guest_type)
133
+ @__finalize_errors << I18n.t("vagrant_terraform.config.guest_type_invalid",
134
+ value: @guest_type.inspect)
109
135
  end
110
136
  end
111
137
 
112
- begin
113
- @memory_size = Filesize.from(@memory_size).to_f('B').to_i
114
- rescue ArgumentError
115
- raise "Not able to parse `memory_size`."
138
+ @ostemplate = nil if @ostemplate == UNSET_VALUE
139
+ @unprivileged = true if @unprivileged == UNSET_VALUE
140
+
141
+ @disk_size = parse_size('disk_size', @disk_size) unless @disk_size.nil?
142
+ @memory_size = parse_size('memory_size', @memory_size)
143
+ @balloon = parse_size('balloon', @balloon)
144
+ end
145
+
146
+ # Picks a different vmid from the configured range after a VMID
147
+ # conflict. Returns the new vmid, or nil when there is nothing else
148
+ # to try (no range, or a range of one).
149
+ def reroll_vmid!
150
+ return nil if @__vmid_range.nil? || @__vmid_range.size < 2
151
+
152
+ candidate = @vmid
153
+ candidate = rand(@__vmid_range) while candidate == @vmid
154
+ @vmid = candidate
155
+ end
156
+
157
+ def vmid_from_range?
158
+ !@__vmid_range.nil?
159
+ end
160
+
161
+ def validate(machine)
162
+ errors = _detected_errors
163
+ errors.concat(@__finalize_errors || [])
164
+
165
+ errors << required('target_node') if @target_node.nil?
166
+ errors << required('storage_domain') if @storage_domain.nil?
167
+ errors << required('disk_size') if @disk_size.nil?
168
+ if @guest_type == :container
169
+ errors << I18n.t("vagrant_terraform.config.required_for_container", field: 'ostemplate') if @ostemplate.nil?
170
+ elsif @template.nil?
171
+ errors << required('template')
116
172
  end
117
173
 
118
- begin
119
- @balloon = Filesize.from(@balloon).to_f('B').to_i
120
- rescue ArgumentError
121
- raise "Not able to parse `balloon`."
174
+ private_networks = machine.config.vm.networks.select { |type, _| type == :private_network }
175
+ private_networks.each do |_, options|
176
+ ip = options[:terraform__ip]
177
+ if !ip.nil? && !ip.to_s.include?("/")
178
+ errors << I18n.t("vagrant_terraform.config.ip_not_cidr", value: ip)
179
+ end
180
+ if options[:terraform__network_name].nil?
181
+ errors << I18n.t("vagrant_terraform.config.network_name_missing")
182
+ end
122
183
  end
184
+
185
+ # Only private networks become container NICs, and the IP is read
186
+ # from eth0. Without one the container gets no interface at all and
187
+ # `vagrant up` would just time out waiting for an IP.
188
+ if @guest_type == :container && private_networks.empty?
189
+ errors << I18n.t("vagrant_terraform.config.container_no_network")
190
+ end
191
+
192
+ { "Terraform Provider" => errors }
193
+ end
194
+
195
+ private
196
+
197
+ def required(field)
198
+ I18n.t("vagrant_terraform.config.required", field: field)
199
+ end
200
+
201
+ # Parses a human-readable size ("2 GiB", "8 GB", or a byte count) into
202
+ # bytes. On failure records an error and returns the value unchanged.
203
+ def parse_size(field, value)
204
+ Filesize.from(value.to_s).to_f('B').to_i
205
+ rescue ArgumentError
206
+ @__finalize_errors << I18n.t("vagrant_terraform.config.size_unparsable", field: field, value: value)
207
+ value
123
208
  end
124
209
 
125
210
  end
@@ -27,6 +27,10 @@ module VagrantPlugins
27
27
  error_key(:terraform_execution_error)
28
28
  end
29
29
 
30
+ class ProxmoxApiError < VagrantTerraformError
31
+ error_key(:proxmox_api_error)
32
+ end
33
+
30
34
  end
31
35
  end
32
36
  end
@@ -21,6 +21,9 @@ module VagrantPlugins
21
21
  DESC
22
22
 
23
23
  config("terraform", :provider) do
24
+ # Config#finalize!/#validate produce translated messages, and the
25
+ # config can be finalized before the provider class is loaded.
26
+ setup_i18n
24
27
  require_relative "config"
25
28
  Config
26
29
  end
@@ -36,8 +39,10 @@ module VagrantPlugins
36
39
 
37
40
  # This initializes the internationalization strings.
38
41
  def self.setup_i18n
39
- I18n.load_path << File.expand_path("locales/en.yml",
40
- TerraformProvider.source_root)
42
+ path = File.expand_path("locales/en.yml", TerraformProvider.source_root)
43
+ return if I18n.load_path.include?(path)
44
+
45
+ I18n.load_path << path
41
46
  I18n.reload!
42
47
  end
43
48
 
@@ -1,4 +1,5 @@
1
1
  require 'vagrant'
2
+ require 'vagrant-terraform/util/container_ssh'
2
3
 
3
4
  module VagrantPlugins
4
5
  module TerraformProvider
@@ -9,6 +10,7 @@ module VagrantPlugins
9
10
  class Provider < Vagrant.plugin('2', :provider)
10
11
  def initialize(machine)
11
12
  @machine = machine
13
+ Util::ContainerSsh.apply_overrides(machine)
12
14
  end
13
15
 
14
16
  # This should return an action callable for the given name.
@@ -0,0 +1,49 @@
1
+ module VagrantPlugins
2
+ module TerraformProvider
3
+ module Util
4
+ # SSH/rsync config adjustments for LXC containers logged into as root.
5
+ #
6
+ # Containers SSH in as root by default (see ReadSSHInfo), and stock CT
7
+ # templates commonly don't have a `sudo` binary at all. Vagrant still
8
+ # wraps privileged guest commands in config.ssh.sudo_command, and the
9
+ # rsync synced-folder implementation separately defaults its remote
10
+ # --rsync-path to the literal "sudo rsync"
11
+ # (plugins/synced_folders/rsync/default_unix_cap.rb) -- it is passed
12
+ # straight to the local rsync binary, not through the SSH communicator.
13
+ # As root there is nothing to escalate to, so both become no-ops.
14
+ #
15
+ # Applied once from Provider#initialize, so every command that uses
16
+ # this machine sees it: up/provision as well as `vagrant rsync` and
17
+ # `vagrant rsync-auto`, which use the machine config directly without
18
+ # going through any of this plugin's action chains.
19
+ #
20
+ # Only when the effective SSH user is root: with a non-root
21
+ # config.ssh.username, privileged commands genuinely need sudo.
22
+ module ContainerSsh
23
+ DEFAULT_SUDO_COMMAND = "sudo -E -H %c".freeze
24
+
25
+ module_function
26
+
27
+ def root_login?(machine)
28
+ username = machine.config.ssh.username
29
+ username.nil? || username.to_s == "root"
30
+ end
31
+
32
+ def apply_overrides(machine)
33
+ return unless machine.provider_config.guest_type == :container
34
+ return unless root_login?(machine)
35
+
36
+ ssh = machine.config.ssh
37
+ # Leave a user-customised sudo_command alone.
38
+ ssh.sudo_command = "%c" if ssh.sudo_command == DEFAULT_SUDO_COMMAND
39
+
40
+ # rsync__rsync_path is Vagrant's documented per-folder override for
41
+ # exactly this; ||= keeps an explicit user setting.
42
+ machine.config.vm.synced_folders.each_value do |folder_opts|
43
+ folder_opts[:rsync__rsync_path] ||= "rsync"
44
+ end
45
+ end
46
+ end
47
+ end
48
+ end
49
+ end
@@ -17,6 +17,24 @@ module VagrantPlugins
17
17
  machine.id
18
18
  end
19
19
  end
20
+
21
+ # Absolute path of the directory holding all per-machine terraform
22
+ # working directories (and the VM-creation lock file) for this
23
+ # Vagrant project: <project>/.vagrant/terraform.
24
+ #
25
+ # Must be absolute: Vagrant does not chdir to the project root, so a
26
+ # cwd-relative ".vagrant/terraform" breaks whenever vagrant runs with
27
+ # a different cwd -- `vagrant global-status --prune` (which loads
28
+ # every project's environment from wherever it's invoked), commands
29
+ # given a global-status machine id from another directory, or plain
30
+ # commands run from a project subdirectory.
31
+ def terraform_base_dir(machine)
32
+ machine.env.local_data_path.join("terraform").to_s
33
+ end
34
+
35
+ def terraform_dir(machine)
36
+ File.join(terraform_base_dir(machine), machine_vmname(machine))
37
+ end
20
38
  end
21
39
  end
22
40
  end