Class: VagrantPlugins::TerraformProvider::Action::ReadState
- Inherits:
-
Object
- Object
- VagrantPlugins::TerraformProvider::Action::ReadState
- Includes:
- Util::MachineNames, Util::TerraformExecute
- Defined in:
- lib/vagrant-terraform/action/read_state.rb
Overview
This action reads the state of the machine and puts it in the ‘:machine_state_id` key in the environment.
Constant Summary
Constants included from Util::MachineNames
Util::MachineNames::DEFAULT_NAME
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app, env) ⇒ ReadState
constructor
A new instance of ReadState.
- #read_state(env) ⇒ Object
Methods included from Util::MachineNames
machine_hostname, machine_vmname
Methods included from Util::TerraformExecute
Constructor Details
#initialize(app, env) ⇒ ReadState
Returns a new instance of ReadState.
16 17 18 19 |
# File 'lib/vagrant-terraform/action/read_state.rb', line 16 def initialize(app, env) @app = app @logger = Log4r::Logger.new("vagrant_terraform::action::read_state") end |
Instance Method Details
#call(env) ⇒ Object
21 22 23 24 |
# File 'lib/vagrant-terraform/action/read_state.rb', line 21 def call(env) env[:machine_state_id] = read_state(env) @app.call(env) end |
#read_state(env) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/vagrant-terraform/action/read_state.rb', line 26 def read_state(env) env[:machine_tf_dir] = ".vagrant/terraform/#{machine_vmname(env[:machine])}" terraform_state_file = "#{env[:machine_tf_dir]}/terraform.tfstate" if File.exist?(env[:machine_tf_dir]) && File.exist?(terraform_state_file) # read_state might get called several times. Avoid refreshing 5 times in a row # for example during "vagrant up" for no obvious reason. if $terraform_refreshed.nil? terraform_execute(env, 'terraform refresh') $terraform_refreshed = true end json_data = File.read(terraform_state_file) data = JSON.parse(json_data) # Navigate to the "vm_state" value resources = data["resources"] return :not_created if resources.nil? || resources.empty? first_resource = resources.first # TODO: find by name instances = first_resource["instances"] return :not_created if instances.nil? || instances.empty? attributes = instances.first["attributes"] return :not_created if attributes.nil? return :not_created if attributes["vm_state"].nil? ip_addr = attributes["default_ipv4_address"] unless ip_addr.nil? env[:ip_address] = ip_addr end return attributes["vm_state"].to_sym else return :not_created end end |