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.
@@ -0,0 +1,146 @@
1
+ require 'net/http'
2
+ require 'uri'
3
+ require 'json'
4
+ require 'openssl'
5
+ require 'vagrant-terraform/util/terraform_state'
6
+
7
+ module VagrantPlugins
8
+ module TerraformProvider
9
+ module Util
10
+ module ProxmoxApi
11
+ module_function
12
+
13
+ # Performs a request against the Proxmox API and returns the parsed
14
+ # `data` field of the response envelope. `form` (POST only) is sent
15
+ # as application/x-www-form-urlencoded, which is what the Proxmox
16
+ # API expects.
17
+ #
18
+ # config must respond to api_url, api_token_id, api_token_secret,
19
+ # insecure.
20
+ def request(config, method, path, form = nil)
21
+ uri = URI.join("#{config.api_url}/", path.sub(%r{^/}, ''))
22
+
23
+ http = Net::HTTP.new(uri.host, uri.port)
24
+ http.use_ssl = uri.scheme == 'https'
25
+ http.verify_mode = OpenSSL::SSL::VERIFY_NONE if config.insecure
26
+
27
+ req = method == :post ? Net::HTTP::Post.new(uri) : Net::HTTP::Get.new(uri)
28
+ req['Authorization'] = "PVEAPIToken=#{config.api_token_id}=#{config.api_token_secret}"
29
+ req.set_form_data(form || {}) if method == :post
30
+
31
+ response = http.request(req)
32
+
33
+ unless response.is_a?(Net::HTTPSuccess)
34
+ raise Errors::ProxmoxApiError,
35
+ :error_message => "#{method.to_s.upcase} #{uri} returned #{response.code}: #{response.body}"
36
+ end
37
+
38
+ JSON.parse(response.body)["data"]
39
+ rescue Errors::ProxmoxApiError
40
+ raise
41
+ rescue StandardError => e
42
+ raise Errors::ProxmoxApiError, :error_message => e.message
43
+ end
44
+
45
+ def get(config, path)
46
+ request(config, :get, path)
47
+ end
48
+
49
+ def post(config, path, form = nil)
50
+ request(config, :post, path, form)
51
+ end
52
+
53
+ # data is the parsed `data` field from GET .../status/current.
54
+ # Returns :running or :stopped.
55
+ def extract_status(data)
56
+ return :stopped if data.nil?
57
+ data["status"] == "running" ? :running : :stopped
58
+ end
59
+
60
+ # data is the parsed `data` field from GET .../interfaces (an array
61
+ # of interface hashes). Returns the IPv4 address (without prefix) of
62
+ # the named interface, or nil if it has none yet.
63
+ def extract_ip(data, iface_name = "eth0")
64
+ return nil unless data.is_a?(Array)
65
+ iface = data.find { |i| i["name"] == iface_name }
66
+ return nil if iface.nil? || iface["inet"].nil?
67
+
68
+ iface["inet"].split('/').first
69
+ end
70
+
71
+ # The node a container currently lives on. Prefer what terraform
72
+ # recorded over the Vagrantfile's target_node: the provider's read
73
+ # (run by every `terraform refresh`) writes the live node into
74
+ # `current_node`/`target_node`, so this follows migrations and
75
+ # Vagrantfile edits made after creation.
76
+ def container_node(attributes, config)
77
+ [attributes["current_node"], attributes["target_node"], config.target_node].find do |n|
78
+ !n.nil? && !n.to_s.empty?
79
+ end
80
+ end
81
+
82
+ # [node, vmid] for the container tracked in machine_tf_dir's
83
+ # terraform.tfstate, or nil if there is no such container yet.
84
+ def container_ref(machine_tf_dir, config)
85
+ attributes = TerraformState.read_attributes("#{machine_tf_dir}/terraform.tfstate")
86
+ return nil if attributes.nil? || attributes["vmid"].nil?
87
+
88
+ [container_node(attributes, config), attributes["vmid"]]
89
+ end
90
+
91
+ def container_status(config, node, vmid)
92
+ data = get(config, "nodes/#{node}/lxc/#{vmid}/status/current")
93
+ extract_status(data)
94
+ end
95
+
96
+ def container_ip(config, node, vmid, iface_name = "eth0")
97
+ data = get(config, "nodes/#{node}/lxc/#{vmid}/interfaces")
98
+ extract_ip(data, iface_name)
99
+ end
100
+
101
+ # Starts or stops a container and waits until it reports the
102
+ # requested state.
103
+ #
104
+ # Container power state is managed here rather than through the
105
+ # proxmox_lxc resource's `start` attribute: the telmate provider
106
+ # never reads `start` back from Proxmox and only acts when the
107
+ # configured value differs from the one in terraform.tfstate, so a
108
+ # container started/stopped outside Vagrant could never be brought
109
+ # back to the desired state with `terraform apply`.
110
+ #
111
+ # target is :running or :stopped. Stopping uses a clean shutdown,
112
+ # forced after shutdown_timeout seconds.
113
+ def set_container_power(config, node, vmid, target, shutdown_timeout: 60, wait_timeout: 180)
114
+ return if container_status(config, node, vmid) == target
115
+
116
+ if target == :running
117
+ post(config, "nodes/#{node}/lxc/#{vmid}/status/start")
118
+ else
119
+ post(config, "nodes/#{node}/lxc/#{vmid}/status/shutdown",
120
+ { "timeout" => shutdown_timeout.to_s, "forceStop" => "1" })
121
+ end
122
+
123
+ # The POST only queues a Proxmox task; poll until it has taken effect.
124
+ deadline = Time.now + wait_timeout
125
+ until container_status(config, node, vmid) == target
126
+ if Time.now > deadline
127
+ raise Errors::ProxmoxApiError,
128
+ :error_message => "container #{vmid} on node #{node} did not reach state '#{target}' within #{wait_timeout}s"
129
+ end
130
+ sleep 2
131
+ end
132
+ end
133
+
134
+ # Convenience wrapper used by WaitForVmUp and ReadSSHInfo: returns the
135
+ # container's current IP, or nil if the state file/vmid isn't there
136
+ # yet.
137
+ def container_ip_for_machine(machine_tf_dir, config)
138
+ ref = container_ref(machine_tf_dir, config)
139
+ return nil if ref.nil?
140
+
141
+ container_ip(config, *ref)
142
+ end
143
+ end
144
+ end
145
+ end
146
+ end
@@ -1,14 +1,25 @@
1
1
  require 'open3'
2
+ require 'set'
3
+ require 'vagrant-terraform/util/machine_names'
2
4
 
3
5
  module VagrantPlugins
4
6
  module TerraformProvider
5
7
  module Util
6
8
  module TerraformExecute
9
+ # Terraform working directories whose terraform.tfstate has been
10
+ # brought up to date (by `terraform refresh` or `terraform apply`)
11
+ # during this process. ReadState uses this to refresh each machine at
12
+ # most once per process instead of on every state query.
13
+ REFRESHED_DIRS = Set.new
7
14
 
8
15
  module_function
9
16
 
17
+ def terraform_refreshed?(dir)
18
+ REFRESHED_DIRS.include?(File.expand_path(dir))
19
+ end
20
+
10
21
  def terraform_execute(env, command, ignore_error = nil)
11
- env[:machine_tf_dir] = ".vagrant/terraform/#{env[:machine].id}" if env[:machine_tf_dir].nil?
22
+ env[:machine_tf_dir] = MachineNames.terraform_dir(env[:machine]) if env[:machine_tf_dir].nil?
12
23
  Dir.mkdir(env[:machine_tf_dir]) unless File.exist?(env[:machine_tf_dir])
13
24
 
14
25
  stdout, stderr, status = Open3.capture3(command, :chdir=>env[:machine_tf_dir])
@@ -24,6 +35,13 @@ module VagrantPlugins
24
35
  raise Errors::TerraformError,
25
36
  :error_message => "terraform command '#{command}' failed with status: #{status}, stderr: #{stderr}"
26
37
  end
38
+
39
+ # Both refresh and apply leave terraform.tfstate reflecting the
40
+ # live resource, so a following state read needn't refresh again.
41
+ if command.start_with?('terraform refresh', 'terraform apply')
42
+ REFRESHED_DIRS << File.expand_path(env[:machine_tf_dir])
43
+ end
44
+
27
45
  return stdout
28
46
  end
29
47
  end
@@ -0,0 +1,27 @@
1
+ require 'json'
2
+
3
+ module VagrantPlugins
4
+ module TerraformProvider
5
+ module Util
6
+ module TerraformState
7
+ module_function
8
+
9
+ # Returns the `attributes` hash of the first resource's first
10
+ # instance in a terraform.tfstate file, or nil if the file doesn't
11
+ # exist or declares no resources/instances.
12
+ def read_attributes(state_file)
13
+ return nil unless File.exist?(state_file)
14
+
15
+ data = JSON.parse(File.read(state_file))
16
+ resources = data["resources"]
17
+ return nil if resources.nil? || resources.empty?
18
+
19
+ instances = resources.first["instances"]
20
+ return nil if instances.nil? || instances.empty?
21
+
22
+ instances.first["attributes"]
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
@@ -5,14 +5,14 @@ module VagrantPlugins
5
5
 
6
6
  module_function
7
7
 
8
- def update_vm_state(file_path, new_state)
8
+ def update_vm_state(file_path, key, formatted_value)
9
9
  # Read the file contents
10
10
  lines = File.readlines(file_path)
11
11
 
12
- # Update the line containing "vm_state"
12
+ # Update the line containing the given key
13
13
  updated_lines = lines.map do |line|
14
- if line.strip.start_with?("vm_state")
15
- line.gsub(/vm_state\s*=\s*".*"/, "vm_state = \"#{new_state}\"")
14
+ if line.strip.start_with?(key)
15
+ line.gsub(/#{Regexp.escape(key)}\s*=\s*\S.*/, "#{key} = #{formatted_value}")
16
16
  else
17
17
  line
18
18
  end
@@ -0,0 +1,69 @@
1
+ require 'vagrant-terraform/util/update_vm_state'
2
+
3
+ module VagrantPlugins
4
+ module TerraformProvider
5
+ module Util
6
+ # Handling of "this VMID is taken" failures from `terraform apply`
7
+ # during creation, shared by CreateVM and CreateContainer.
8
+ module VmidConflict
9
+ # Messages meaning the requested VMID is (or just became) taken:
10
+ # - the telmate provider's own pre-check for a set vmid (qemu);
11
+ # - Proxmox's race message, when the id was free at check time but
12
+ # another creation took it first;
13
+ # - Proxmox's "<type> <id> already exists" for a set vmid that is in
14
+ # use (the provider does no pre-check for LXC).
15
+ # Each pattern matches only the short, human-readable part, which is
16
+ # what gets quoted back to the user (not the whole terraform stderr,
17
+ # which includes the full request parameters).
18
+ PATTERNS = [
19
+ /vmId: \d+ already in use/,
20
+ /unable to create (VM|CT) \d+[^\n]*?config file already exists/,
21
+ /\b(VM|CT) \d+ already exists(?: on node '[^'\n]*')?/,
22
+ ].freeze
23
+
24
+ module_function
25
+
26
+ def conflict?(message)
27
+ !conflict_detail(message).nil?
28
+ end
29
+
30
+ # The matched conflict text, e.g. "CT 20000 already exists on node 'pve1'".
31
+ def conflict_detail(message)
32
+ PATTERNS.each do |re|
33
+ match = message[re]
34
+ return match unless match.nil?
35
+ end
36
+ nil
37
+ end
38
+
39
+ # Call when `message` (ANSI-stripped stderr) is a VMID conflict.
40
+ # Returns normally when creation should be retried; raises
41
+ # CreateVMError when retrying can't help.
42
+ #
43
+ # - no vmid configured: Proxmox picked the next free id and lost a
44
+ # race to a parallel creation; the next attempt gets a new one.
45
+ # - vmid from a range: pick another id from the range and rewrite
46
+ # main.tf with it.
47
+ # - fixed vmid: it's simply taken; every retry would fail the same.
48
+ def prepare_retry(env, config, terraform_main_file, message)
49
+ if config.vmid.nil?
50
+ env[:ui].info("Proxmox ID conflict, retrying")
51
+ return
52
+ end
53
+
54
+ old_vmid = config.vmid
55
+ if config.vmid_from_range? && (new_vmid = config.reroll_vmid!)
56
+ env[:ui].info("VMID #{old_vmid} is already in use, retrying with #{new_vmid}")
57
+ UpdateVmState.update_vm_state(terraform_main_file, "vmid", "\"#{new_vmid}\"")
58
+ return
59
+ end
60
+
61
+ raise Errors::CreateVMError,
62
+ :error_message => "VMID #{old_vmid} is already in use. Set a different 'vmid', " \
63
+ "a range such as '10000-10999', or leave it unset. " \
64
+ "(Proxmox: #{conflict_detail(message) || 'VMID conflict'})"
65
+ end
66
+ end
67
+ end
68
+ end
69
+ end
@@ -1,6 +1,6 @@
1
1
  module VagrantPlugins
2
2
  module TerraformProvider
3
- VERSION = '0.4'
3
+ VERSION = '0.5.1'
4
4
  end
5
5
  end
6
6
 
data/locales/en.yml CHANGED
@@ -2,6 +2,8 @@ en:
2
2
  vagrant_terraform:
3
3
  creating_vm: |-
4
4
  Creating VM with the following settings...
5
+ creating_container: |-
6
+ Creating LXC container with the following settings...
5
7
  starting_vm: |-
6
8
  Starting VM.
7
9
  not_created: |-
@@ -27,8 +29,14 @@ en:
27
29
  The instance is running. Use `vagrant halt` to stop it.
28
30
  short_running: |-
29
31
  running
32
+ long_stopped: |-
33
+ The instance is stopped. Use `vagrant up` to start it.
30
34
  short_stopped: |-
31
35
  stopped
36
+ long_unknown: |-
37
+ The instance state could not be read from Proxmox. Check the API URL, token and network connectivity.
38
+ short_unknown: |-
39
+ unknown
32
40
  long_down: |-
33
41
  The instance is not running. Use `vagrant up` to start it.
34
42
  short_down: |-
@@ -45,6 +53,29 @@ en:
45
53
  start_vm_error: |-
46
54
  Unable to start VM: %{error_message}
47
55
  no_ip_error: |-
48
- The VM has not reported an IP address. Please ensure the qemu-guest-agent is running and the machine is up.
56
+ The machine has not reported an IP address. For a VM, ensure the qemu-guest-agent is running and the machine is up. For a container, check that its network bridge and IP (or DHCP) configuration are correct.
49
57
  terraform_execution_error: |-
50
58
  Terraforming failed. Error was '%{error_message}'
59
+ proxmox_api_error: |-
60
+ Proxmox API request failed. Error was '%{error_message}'
61
+ config:
62
+ required: |-
63
+ '%{field}' must be set.
64
+ required_for_container: |-
65
+ '%{field}' must be set for containers.
66
+ vmid_invalid: |-
67
+ Invalid 'vmid' %{value}: must be a number between %{min} and %{max}, or a range like '%{min}-%{max}'.
68
+ vmid_range_invalid: |-
69
+ Invalid 'vmid' range %{value}: must be 'MIN-MAX' with %{min} <= MIN <= MAX <= %{max}.
70
+ guest_type_invalid: |-
71
+ Invalid 'guest_type' %{value}: must be :vm or :container.
72
+ size_unparsable: |-
73
+ Unable to parse '%{field}' value %{value}. Use a size such as '2 GiB' or '8 GB'.
74
+ ip_not_cidr: |-
75
+ terraform__ip must be given in CIDR form, for example 192.168.0.10/24 (got '%{value}').
76
+ network_name_missing: |-
77
+ 'terraform__network_name' must be set for each private network.
78
+ container_no_network: |-
79
+ A container needs at least one private network, for example:
80
+ config.vm.network :private_network, :terraform__network_name => "vmbr0"
81
+ Its first private network becomes eth0, which Vagrant uses to reach the container.
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: vagrant-terraform
3
3
  version: !ruby/object:Gem::Version
4
- version: '0.4'
4
+ version: 0.5.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Mika Båtsman
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-04-27 00:00:00.000000000 Z
11
+ date: 2026-11-20 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: filesize
@@ -41,8 +41,10 @@ files:
41
41
  - example_box/Vagrantfile
42
42
  - example_box/dummy.box
43
43
  - example_box/metadata.json
44
+ - examples/Vagrantfile.lxc
44
45
  - lib/vagrant-terraform.rb
45
46
  - lib/vagrant-terraform/action.rb
47
+ - lib/vagrant-terraform/action/create_container.rb
46
48
  - lib/vagrant-terraform/action/create_vm.rb
47
49
  - lib/vagrant-terraform/action/destroy_vm.rb
48
50
  - lib/vagrant-terraform/action/halt_vm.rb
@@ -52,16 +54,21 @@ files:
52
54
  - lib/vagrant-terraform/action/read_state.rb
53
55
  - lib/vagrant-terraform/action/setup_terraform.rb
54
56
  - lib/vagrant-terraform/action/start_vm.rb
57
+ - lib/vagrant-terraform/action/update_index_state.rb
55
58
  - lib/vagrant-terraform/action/wait_for_vm_up.rb
56
59
  - lib/vagrant-terraform/config.rb
57
60
  - lib/vagrant-terraform/errors.rb
58
61
  - lib/vagrant-terraform/plugin.rb
59
62
  - lib/vagrant-terraform/provider.rb
60
63
  - lib/vagrant-terraform/util.rb
64
+ - lib/vagrant-terraform/util/container_ssh.rb
61
65
  - lib/vagrant-terraform/util/machine_names.rb
66
+ - lib/vagrant-terraform/util/proxmox_api.rb
62
67
  - lib/vagrant-terraform/util/terraform_execute.rb
68
+ - lib/vagrant-terraform/util/terraform_state.rb
63
69
  - lib/vagrant-terraform/util/timer.rb
64
70
  - lib/vagrant-terraform/util/update_vm_state.rb
71
+ - lib/vagrant-terraform/util/vmid_conflict.rb
65
72
  - lib/vagrant-terraform/version.rb
66
73
  - locales/en.yml
67
74
  - vagrant-terraform.gemspec