vagrant-terraform 0.4.1 → 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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ac7e77588766896f79c56df92b0f4a80c4c32d0f943ff31c081a522282bf4e22
4
- data.tar.gz: a438198f169bda35c681dcddc500bee82338027929dfdedc99929541e56ec9b4
3
+ metadata.gz: 7c3f93f036e12968598b172cee8adeae703e7a521c6ce4dc0b23c5d58e8f4f4d
4
+ data.tar.gz: 994bcaf9d35b19851cfc1676899f535ef45beaeef664da4a86a635b23836b306
5
5
  SHA512:
6
- metadata.gz: 31c5bd26aae0ba38a0741995f0838d7ce0462ccaa871cec418a5be6f1e13dea28db1336ed452b36aaf8c7e3d2544e64f69daa17d28b76e81b390b93074a4d84f
7
- data.tar.gz: 0412a3352225bf4d5cb93f83ccd53524d9ad98a61bbceafe0d063174f338229fdccf3951c419954a226d70f63ee466d89661a71034dc059d21977c6c94b64e11
6
+ metadata.gz: d07d9d90380f9a58d9fdae98f1646180eee806da3a96a6e389db1b836f02fba24bb344a739cdeed171669097f79e17f5c4fc510c94491c062d62058bf3ba85f4
7
+ data.tar.gz: 2de68b1a655f4fb8a86031fba470514b7b3d3a6977146b5bfe6d415efc531da73e3a1c3cc10fbc6ea812f8ebf7788f70b2fec7abc98e1eea06698b74890549c3
@@ -12,11 +12,11 @@ jobs:
12
12
  contents: read
13
13
 
14
14
  steps:
15
- - uses: actions/checkout@v4
16
- - name: Set up Ruby 3.3.6
15
+ - uses: actions/checkout@v6
16
+ - name: Set up Ruby 3.3
17
17
  uses: ruby/setup-ruby@v1
18
18
  with:
19
- ruby-version: 3.3.6
19
+ ruby-version: 3.3
20
20
 
21
21
  - name: Build gem
22
22
  run: gem build *.gemspec
@@ -41,10 +41,10 @@ jobs:
41
41
  with:
42
42
  name: gem
43
43
 
44
- - name: Set up Ruby 3.3.6
44
+ - name: Set up Ruby 3.3
45
45
  uses: ruby/setup-ruby@v1
46
46
  with:
47
- ruby-version: 3.3.6
47
+ ruby-version: 3.3
48
48
 
49
49
  - name: Publish to RubyGems
50
50
  run: |
data/.gitignore CHANGED
@@ -8,3 +8,4 @@
8
8
  /manifests
9
9
  vendor
10
10
  tmp
11
+ /.worktrees
data/README.md CHANGED
@@ -114,7 +114,7 @@ Vagrant.configure("2") do |config|
114
114
  terraform.disk_size = '15 GB'
115
115
  terraform.target_node = 'pve1'
116
116
  terraform.storage_domain = '[STORAGE_NAME]'
117
- terraform.vmid = '10000-9999999' # Randomly select a VMID in this range. Optional, defaults to first free
117
+ terraform.vmid = '10000-9999999' # Randomly select a VMID in this range (another one is tried if it's taken). Optional, defaults to first free
118
118
  terraform.nameserver = '1.1.1.1 1.0.0.1'
119
119
  terraform.searchdomain = 'example.com'
120
120
  end
@@ -124,3 +124,68 @@ Vagrant.configure("2") do |config|
124
124
  SHELL
125
125
  end
126
126
  ```
127
+
128
+ ### LXC container example
129
+
130
+ Containers use `terraform.guest_type = :container` and an `ostemplate` (a
131
+ Proxmox CT template volume id) instead of a VM `template`. Download one with,
132
+ e.g.:
133
+ ```
134
+ pveam update
135
+ pveam available --section system | grep ubuntu-24.04
136
+ pveam download local ubuntu-24.04-standard_24.04-1_amd64.tar.zst
137
+ ```
138
+
139
+ Unlike the VM path, no image customization is needed for SSH access — the
140
+ plugin injects the vagrant insecure keypair via `ssh_public_keys`, which
141
+ Proxmox writes to root's `authorized_keys` on stock CT templates. SSH
142
+ defaults to the `root` user for containers unless `config.ssh.username` is
143
+ set explicitly. When logging in as root, which doesn't need to escalate
144
+ privileges, the plugin also points Vagrant's `sudo_command` at a no-op
145
+ wrapper and runs rsync without `sudo`. Vagrant's own guest capabilities
146
+ (installing rsync, setting the hostname, etc.) always run their setup
147
+ commands through `sudo` otherwise, which fails on stock CT templates that
148
+ don't ship a `sudo` binary at all. With a non-root `config.ssh.username`,
149
+ `sudo` is used as normal.
150
+
151
+ A container needs at least one `private_network`; the first one becomes
152
+ `eth0`, which Vagrant uses to reach the container.
153
+
154
+ Containers are started and stopped (`vagrant up` / `vagrant halt`) through
155
+ the Proxmox API rather than `terraform apply`, so the API token needs
156
+ `VM.PowerMgmt` (included in the role above).
157
+
158
+ ```ruby
159
+ Vagrant.configure("2") do |config|
160
+ config.vm.box = 'dummy'
161
+ config.vm.hostname = "example-container.local"
162
+
163
+ config.vm.network :private_network,
164
+ :terraform__network_name => 'vmbr0', :terraform__ip => '192.168.0.52/24', :terraform__gateway => '192.168.0.1'
165
+
166
+ config.vm.provider :terraform do |terraform|
167
+ terraform.guest_type = :container
168
+ terraform.api_url = 'https://[PVE_ADDRESS]:8006/api2/json'
169
+ terraform.api_token_id = "terraform@pve!automation"
170
+ terraform.api_token_secret = "[API_TOKEN]"
171
+ terraform.insecure = true
172
+ terraform.ostemplate = 'local:vztmpl/ubuntu-24.04-standard_24.04-1_amd64.tar.zst'
173
+ terraform.unprivileged = true
174
+ terraform.cpu_cores = 2
175
+ terraform.memory_size = '2 GiB'
176
+ terraform.disk_size = '8 GB'
177
+ terraform.target_node = 'pve1'
178
+ terraform.storage_domain = '[STORAGE_NAME]'
179
+ end
180
+ end
181
+ ```
182
+
183
+ A full example is in [`examples/Vagrantfile.lxc`](examples/Vagrantfile.lxc).
184
+
185
+ The following VM-only options are ignored when `guest_type = :container`:
186
+ `vga`, `balloon`, `cpu_type`, `template`, `full_clone`, `serial_port`,
187
+ `os_type`.
188
+
189
+ Not yet supported for containers (may be added later): cloning from an
190
+ existing LXC container, extra `mountpoint`s beyond the root filesystem, the
191
+ `features` block (nesting/fuse/keyctl), resource pools, HA state, IPv6.
@@ -0,0 +1,37 @@
1
+ Vagrant.configure("2") do |config|
2
+ config.vm.box = 'dummy'
3
+ config.vm.box_url = 'https://github.com/mika-b/vagrant-terraform/blob/main/example_box/dummy.box?raw=true'
4
+
5
+ config.vm.hostname = "example-container.local"
6
+
7
+ config.vm.synced_folder './', '/vagrant', type: 'rsync', rsync__exclude: ["log/", ".git/"]
8
+ config.ssh.forward_agent = true
9
+
10
+ config.vm.network :private_network,
11
+ :terraform__network_name => 'vmbr0', :terraform__ip => '192.168.0.52/24', :terraform__gateway => '192.168.0.1'
12
+ config.vm.network :private_network,
13
+ :terraform__network_name => 'testmgmt' # DHCP
14
+
15
+ config.vm.provider :terraform do |terraform|
16
+ terraform.guest_type = :container
17
+ terraform.api_url = 'https://[PVE_ADDRESS]:8006/api2/json'
18
+ terraform.api_token_id = "terraform@pve!automation"
19
+ terraform.api_token_secret = "[API_TOKEN]"
20
+ terraform.insecure = true
21
+ terraform.debug = false
22
+ terraform.description = "Created by: #{ENV['USER']}"
23
+ terraform.ostemplate = 'local:vztmpl/ubuntu-24.04-standard_24.04-1_amd64.tar.zst'
24
+ terraform.unprivileged = true
25
+ terraform.cpu_cores = 2
26
+ terraform.memory_size = '2 GiB'
27
+ terraform.disk_size = '8 GB'
28
+ terraform.target_node = 'pve1'
29
+ terraform.storage_domain = '[STORAGE_NAME]'
30
+ terraform.nameserver = '1.1.1.1 1.0.0.1'
31
+ terraform.searchdomain = 'example.com'
32
+ end
33
+
34
+ config.vm.provision "shell", inline: <<-SHELL
35
+ ip a
36
+ SHELL
37
+ end
@@ -0,0 +1,240 @@
1
+ require 'log4r'
2
+ require 'vagrant-terraform/util/machine_names'
3
+ require 'vagrant-terraform/util/terraform_execute'
4
+ require 'vagrant-terraform/util/vmid_conflict'
5
+ require 'vagrant/util/retryable'
6
+
7
+ module VagrantPlugins
8
+ module TerraformProvider
9
+ module Action
10
+ class CreateContainer
11
+ include Util::TerraformExecute
12
+ include Util::MachineNames
13
+ include Vagrant::Util::Retryable
14
+
15
+ def initialize(app, env)
16
+ @logger = Log4r::Logger.new("vagrant_terraform::action::create_container")
17
+ @app = app
18
+ end
19
+
20
+ def call(env)
21
+ config = env[:machine].provider_config
22
+ vmname = machine_vmname(env[:machine])
23
+
24
+ networks = []
25
+ private_network_idx = 0
26
+ env[:machine].config.vm.networks.each do |network|
27
+ type, options = network
28
+ next unless type == :private_network
29
+
30
+ # IP format and network name are checked in Config#validate.
31
+
32
+ networks << {
33
+ :idx => private_network_idx,
34
+ :bridge => options[:terraform__network_name],
35
+ :ip => options[:terraform__ip] || "dhcp",
36
+ :gateway => options[:terraform__gateway],
37
+ }
38
+ private_network_idx += 1
39
+ end
40
+
41
+ env[:ui].info(I18n.t("vagrant_terraform.creating_container"))
42
+ env[:ui].info(" -- Name: #{vmname}")
43
+ env[:ui].info(" -- OS template: #{config.ostemplate}")
44
+ env[:ui].info(" -- Description: #{config.description}")
45
+ env[:ui].info(" -- Target node: #{config.target_node}")
46
+ env[:ui].info(" -- Storage domain: #{config.storage_domain}")
47
+ env[:ui].info(" -- CPU Cores: #{config.cpu_cores}")
48
+ env[:ui].info(" -- Memory: #{Filesize.from("#{config.memory_size} B").to_f('MB').to_i} MB")
49
+ env[:ui].info(" -- Disk: #{Filesize.from("#{config.disk_size} B").to_f('GB').to_i} GB")
50
+
51
+ main_tf = render_main_tf(config, vmname, networks)
52
+
53
+ env[:machine].id = vmname
54
+ terraform_dir = env[:machine_tf_dir]
55
+ terraform_main_file = "#{terraform_dir}/main.tf"
56
+ File.write(terraform_main_file, main_tf)
57
+
58
+ # Avoid downloading the provider every time even when it's in the cache
59
+ ENV['TF_PLUGIN_CACHE_MAY_BREAK_DEPENDENCY_LOCK_FILE'] = "1"
60
+ retryable(on: Errors::TerraformError, tries: 100, sleep: 1) do
61
+ begin
62
+ terraform_execute(env, 'terraform init')
63
+ rescue Errors::TerraformError => e
64
+ ansi_escape_regex = /\e\[(?:[0-9]{1,2}(?:;[0-9]{1,2})*)?[m|K]/
65
+ if e.message.gsub(ansi_escape_regex, '').include?("Failed to install provider")
66
+ @logger.debug("Failed to install provider, retrying")
67
+ raise e
68
+ end
69
+
70
+ # Anything else is not transient: surface it now rather than
71
+ # carrying on to an `apply` that fails with a misleading error.
72
+ # (Not as a TerraformError -- retryable would retry that.)
73
+ fault_message = e.message
74
+ unless config.debug
75
+ fault_message = /Error: (.*)/.match(e.message.gsub(ansi_escape_regex, ''))[1] rescue e.message
76
+ end
77
+ raise Errors::CreateVMError, :error_message => "terraform init failed: #{fault_message}"
78
+ end
79
+ end
80
+
81
+ retryable(on: Errors::TerraformError, tries: 10, sleep: 1) do
82
+ begin
83
+ lockfile = File.join(terraform_base_dir(env[:machine]), 'lock')
84
+ max_retries = 300
85
+ retry_delay = 2
86
+
87
+ File.open(lockfile, 'w') do |file|
88
+ retries = 0
89
+
90
+ # Container creation can't be done in parallel because multiple
91
+ # containers might get the same VMID.
92
+ until file.flock(File::LOCK_EX | File::LOCK_NB)
93
+ if retries >= max_retries
94
+ raise Errors::CreateVMError,
95
+ :error_message => "Failed to acquire lock after #{max_retries} attempts. Exiting."
96
+ end
97
+
98
+ @logger.debug("Lock is currently held. Retrying in #{retry_delay} seconds...")
99
+ retries += 1
100
+ sleep(retry_delay)
101
+ end
102
+
103
+ begin
104
+ terraform_execute(env, "terraform apply -auto-approve")
105
+ ensure
106
+ file.flock(File::LOCK_UN)
107
+ end
108
+ end
109
+
110
+ rescue Errors::TerraformError => e
111
+ ansi_escape_regex = /\e\[(?:[0-9]{1,2}(?:;[0-9]{1,2})*)?[m|K]/
112
+
113
+ if e.message.gsub(ansi_escape_regex, '').include?("Error: can't lock file")
114
+ env[:ui].info("Proxmox unable to get lock, retrying")
115
+ raise e
116
+ end
117
+
118
+ if e.message.gsub(ansi_escape_regex, '').include?("error: got lock request timeout")
119
+ env[:ui].info("Proxmox unable to get storage lock, retrying")
120
+ raise e
121
+ end
122
+
123
+ if e.message.gsub(ansi_escape_regex, '').include?("command timed out")
124
+ env[:ui].info("Proxmox clone failed with command timeout, retrying")
125
+ raise e
126
+ end
127
+
128
+ if e.message.gsub(ansi_escape_regex, '').include?("got no worker upid")
129
+ env[:ui].info("Proxmox error: 'got no worker upid', retrying")
130
+ raise e
131
+ end
132
+
133
+ if e.message.gsub(ansi_escape_regex, '') =~ /.*volume .* does not exist/
134
+ env[:ui].info("Volume not created, retrying. Error was: #{e.message}")
135
+ raise e
136
+ end
137
+
138
+ if e.message.gsub(ansi_escape_regex, '').include?("Request cancelled")
139
+ env[:ui].info("Proxmox error: Request cancelled")
140
+ raise e
141
+ end
142
+
143
+ if Util::VmidConflict.conflict?(e.message.gsub(ansi_escape_regex, ''))
144
+ # Raises CreateVMError if retrying can't help (fixed vmid).
145
+ Util::VmidConflict.prepare_retry(env, config, terraform_main_file, e.message.gsub(ansi_escape_regex, ''))
146
+ raise e
147
+ end
148
+
149
+ # Not retryable. Always re-raise as CreateVMError: a
150
+ # TerraformError would be caught by `retryable` and retried.
151
+ fault_message = e.message
152
+ unless config.debug
153
+ fault_message = /Error: (.*)/.match(e.message.gsub(ansi_escape_regex, ''))[1] rescue e.message
154
+ end
155
+ raise Errors::CreateVMError,
156
+ :error_message => fault_message
157
+ end
158
+ end
159
+
160
+ @app.call(env)
161
+ end
162
+
163
+ # Pure HCL rendering, independent of the Vagrant `env`, so it can be
164
+ # exercised directly. `config` must respond to target_node,
165
+ # ostemplate, unprivileged, cpu_cores, memory_size, onboot,
166
+ # description, nameserver, searchdomain, storage_domain, disk_size,
167
+ # vmid, api_url, api_token_id, api_token_secret, insecure, debug.
168
+ # `networks` is an array of {:idx, :bridge, :ip, :gateway} hashes.
169
+ def render_main_tf(config, vmname, networks)
170
+ network_blocks = networks.map do |net|
171
+ gw_line = (net[:gateway].nil? || net[:ip] == "dhcp") ? "" : "\n gw = \"#{net[:gateway]}\""
172
+ <<-NET
173
+ network {
174
+ name = "eth#{net[:idx]}"
175
+ bridge = "#{net[:bridge]}"
176
+ ip = "#{net[:ip]}"#{gw_line}
177
+ }
178
+ NET
179
+ end.join
180
+
181
+ vmid_line = config.vmid ? " vmid = \"#{config.vmid}\"\n" : ""
182
+
183
+ <<-END
184
+ provider "proxmox" {
185
+ pm_api_url = "#{config.api_url}"
186
+ pm_api_token_id = "#{config.api_token_id}"
187
+ pm_api_token_secret = "#{config.api_token_secret}"
188
+ pm_tls_insecure = #{config.insecure.to_s}
189
+ pm_debug = #{config.debug}
190
+ }
191
+
192
+ resource "proxmox_lxc" "#{vmname.gsub(/\./, '-')}" {
193
+ target_node = "#{config.target_node}"
194
+ hostname = "#{vmname}"
195
+ ostemplate = "#{config.ostemplate}"
196
+ unprivileged = #{config.unprivileged}
197
+ cores = #{config.cpu_cores.to_i}
198
+ memory = #{Filesize.from("#{config.memory_size} B").to_f('MB').to_i}
199
+ onboot = #{config.onboot}
200
+ description = "#{config.description}"
201
+ nameserver = "#{config.nameserver}"
202
+ searchdomain = "#{config.searchdomain}"
203
+ start = false
204
+ #{vmid_line}
205
+ rootfs {
206
+ storage = "#{config.storage_domain}"
207
+ size = "#{Filesize.from("#{config.disk_size} B").to_f('GB').to_i}G"
208
+ }
209
+
210
+ ssh_public_keys = <<EOF
211
+ ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9HZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6kivAIhyfHilFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYCzRdK8jlqm8tehUc9c9WhQ== vagrant insecure public key
212
+ EOF
213
+
214
+ #{network_blocks}}
215
+
216
+ terraform {
217
+ required_version = ">= 1.8.0"
218
+ required_providers {
219
+ proxmox = {
220
+ source = "telmate/proxmox"
221
+ version = "3.0.2-rc05"
222
+ }
223
+ }
224
+ }
225
+ END
226
+ end
227
+
228
+ def recover(env)
229
+ return if env["vagrant.error"].is_a?(Vagrant::Errors::VagrantError)
230
+ env[:ui].info(I18n.t("vagrant_terraform.error_recovering"))
231
+ destroy_env = env.dup
232
+ destroy_env.delete(:interrupted)
233
+ destroy_env[:config_validate] = false
234
+ destroy_env[:force_confirm_destroy] = true
235
+ env[:action_runner].run(Action.action_destroy, destroy_env)
236
+ end
237
+ end
238
+ end
239
+ end
240
+ end
@@ -1,6 +1,7 @@
1
1
  require 'log4r'
2
2
  require 'vagrant-terraform/util/machine_names'
3
3
  require 'vagrant-terraform/util/terraform_execute'
4
+ require 'vagrant-terraform/util/vmid_conflict'
4
5
  require 'vagrant/util/retryable'
5
6
 
6
7
  module VagrantPlugins
@@ -19,18 +20,6 @@ module VagrantPlugins
19
20
  def call(env)
20
21
  # Get config.
21
22
  config = env[:machine].provider_config
22
- if config.target_node.nil?
23
- raise "'target_node' must not be empty."
24
- end
25
-
26
- if config.storage_domain.nil?
27
- raise "'storage_domain' must not be empty."
28
- end
29
-
30
- if config.disk_size.nil?
31
- raise "'disk_size' must be set."
32
- end
33
-
34
23
  vmname = machine_vmname(env[:machine])
35
24
 
36
25
  main_tf = <<-END
@@ -144,11 +133,8 @@ END
144
133
 
145
134
  # Only private networks are supported
146
135
  next unless type == :private_network
136
+ # IP format and network name are checked in Config#validate.
147
137
  if ! options[:terraform__ip].nil?
148
- if ! options[:terraform__ip].include? "/"
149
- raise "IP must be given in CIDR form, for example 192.168.0.10/24"
150
- end
151
-
152
138
  if options[:terraform__gateway].nil?
153
139
  network_str = network_template.gsub(/%IP%/, "ip=#{options[:terraform__ip]}")
154
140
  else
@@ -195,12 +181,21 @@ END
195
181
  @logger.debug("Failed to install provider, retrying")
196
182
  raise e
197
183
  end
184
+
185
+ # Anything else is not transient: surface it now rather than
186
+ # carrying on to an `apply` that fails with a misleading error.
187
+ # (Not as a TerraformError -- retryable would retry that.)
188
+ fault_message = e.message
189
+ unless config.debug
190
+ fault_message = /Error: (.*)/.match(e.message.gsub(ansi_escape_regex, ''))[1] rescue e.message
191
+ end
192
+ raise Errors::CreateVMError, :error_message => "terraform init failed: #{fault_message}"
198
193
  end
199
194
  end
200
195
 
201
196
  retryable(on: Errors::TerraformError, tries: 10, sleep: 1) do
202
197
  begin
203
- lockfile = '.vagrant/terraform/lock'
198
+ lockfile = File.join(terraform_base_dir(env[:machine]), 'lock')
204
199
  max_retries = 300
205
200
  retry_delay = 2
206
201
 
@@ -280,18 +275,20 @@ END
280
275
  raise e
281
276
  end
282
277
 
283
- if e.message.gsub(ansi_escape_regex, '') =~ /.*Error: [0-9 ]*unable to create VM [0-9]*: config file already exists/
284
- env[:ui].info("Proxmox ID conflict, retrying")
278
+ if Util::VmidConflict.conflict?(e.message.gsub(ansi_escape_regex, ''))
279
+ # Raises CreateVMError if retrying can't help (fixed vmid).
280
+ Util::VmidConflict.prepare_retry(env, config, terraform_main_file, e.message.gsub(ansi_escape_regex, ''))
285
281
  raise e
286
282
  end
287
283
 
288
- if config.debug
289
- raise e
290
- else
284
+ # Not retryable. Always re-raise as CreateVMError: a
285
+ # TerraformError would be caught by `retryable` and retried.
286
+ fault_message = e.message
287
+ unless config.debug
291
288
  fault_message = /Error: (.*)/.match(e.message.gsub(ansi_escape_regex, ''))[1] rescue e.message
292
- raise Errors::CreateVMError,
293
- :error_message => fault_message
294
289
  end
290
+ raise Errors::CreateVMError,
291
+ :error_message => fault_message
295
292
  end
296
293
  end
297
294
 
@@ -21,7 +21,7 @@ module VagrantPlugins
21
21
  begin
22
22
  # for some reason here the machine_tf_dir is not in env even though read_state has been called
23
23
  # multiple times on 'vagrant halt' before we get here.
24
- terraform_dir = ".vagrant/terraform/#{env[:machine].id}"
24
+ terraform_dir = Util::MachineNames.terraform_dir(env[:machine])
25
25
 
26
26
  terraform_execute(env, 'terraform destroy -auto-approve')
27
27
  FileUtils.rm_rf(terraform_dir)
@@ -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
@@ -21,10 +22,17 @@ module VagrantPlugins
21
22
  env[:ui].info(I18n.t("vagrant_terraform.halt_vm"))
22
23
 
23
24
  begin
24
- terraform_dir = ".vagrant/terraform/#{env[:machine].id}"
25
- terraform_main_file = "#{terraform_dir}/main.tf"
26
- update_vm_state(terraform_main_file, "stopped")
27
- terraform_execute(env, 'terraform apply -auto-approve')
25
+ config = env[:machine].provider_config
26
+ terraform_dir = Util::MachineNames.terraform_dir(env[:machine])
27
+ if config.guest_type == :container
28
+ # Via the API, not terraform: see ProxmoxApi.set_container_power.
29
+ ref = Util::ProxmoxApi.container_ref(terraform_dir, config)
30
+ Util::ProxmoxApi.set_container_power(config, *ref, :stopped) unless ref.nil?
31
+ else
32
+ terraform_main_file = "#{terraform_dir}/main.tf"
33
+ update_vm_state(terraform_main_file, "vm_state", "\"stopped\"")
34
+ terraform_execute(env, 'terraform apply -auto-approve')
35
+ end
28
36
  rescue Exception => e
29
37
  # TODO: need to retry in some case?
30
38
  # retry if e.message =~ /something/
@@ -1,5 +1,6 @@
1
1
  require "log4r"
2
2
  require 'vagrant-terraform/util/terraform_execute'
3
+ require 'vagrant-terraform/util/proxmox_api'
3
4
 
4
5
  module VagrantPlugins
5
6
  module TerraformProvider
@@ -25,14 +26,27 @@ module VagrantPlugins
25
26
  # Otherwise, it returns nil.
26
27
  def read_ssh_info(env)
27
28
  machine = env[:machine]
29
+ config = machine.provider_config
28
30
 
29
- ip_addr = terraform_execute(env, "terraform output -raw public_ip")
31
+ ip_addr = if config.guest_type == :container
32
+ begin
33
+ Util::ProxmoxApi.container_ip_for_machine(env[:machine_tf_dir], config)
34
+ rescue Errors::ProxmoxApiError => e
35
+ @logger.debug("container IP lookup failed: #{e.message}")
36
+ nil
37
+ end
38
+ else
39
+ terraform_execute(env, "terraform output -raw public_ip")
40
+ end
30
41
  return nil if ip_addr.nil?
31
42
 
43
+ username = machine.config.ssh.username
44
+ username = "root" if config.guest_type == :container && username.nil?
45
+
32
46
  return {
33
47
  :host => ip_addr,
34
48
  :port => machine.config.ssh.guest_port,
35
- :username => machine.config.ssh.username,
49
+ :username => username,
36
50
  :private_key_path => machine.config.ssh.private_key_path,
37
51
  :forward_agent => machine.config.ssh.forward_agent,
38
52
  :forward_x11 => machine.config.ssh.forward_x11,