ansible generated inventory: deal with orphan VMs

env.active_machines can potentiall return 'invalid' machines:
- Ignore machines that are not declared in current Vagrantfile
- Warn when machines are missing (it usually occurs when the VM is
  removed without `vagrant destroy` and some orphan metadata remains
  in .vagrant/machines/...)
This commit is contained in:
Gilles Cornu 2014-02-02 22:32:22 +01:00
parent 3bf5032d4b
commit 84308964e2
1 changed files with 18 additions and 3 deletions

View File

@ -2,6 +2,7 @@ module VagrantPlugins
module Ansible
class Provisioner < Vagrant.plugin("2", :provisioner)
def provision
@logger = Log4r::Logger.new("vagrant::provisioners::ansible")
ssh = @machine.ssh_info
# Connect with Vagrant user (unless --user or --private-key are
@ -71,6 +72,9 @@ module VagrantPlugins
ssh = @machine.ssh_info
# Managed machines
inventory_machines = []
generated_inventory_file =
@machine.env.root_path.join("vagrant_ansible_inventory")
@ -78,8 +82,19 @@ module VagrantPlugins
file.write("# Generated by Vagrant\n\n")
@machine.env.active_machines.each do |am|
m = @machine.env.machine(*am)
file.write("#{m.name} ansible_ssh_host=#{m.ssh_info[:host]} ansible_ssh_port=#{m.ssh_info[:port]}\n")
begin
m = @machine.env.machine(*am)
if !m.ssh_info.nil?
file.write("#{m.name} ansible_ssh_host=#{m.ssh_info[:host]} ansible_ssh_port=#{m.ssh_info[:port]}\n")
inventory_machines << m
else
@logger.error("Auto-generated inventory: Impossible to get SSH information for machine '#{m.name} (#{m.provider_name})'. This machine should be recreated.")
# Let a note about this missing machine
file.write("# MISSING: '#{m.name}' machine was probably removed without using Vagrant. This machine should be recreated.\n")
end
rescue Vagrant::Errors::MachineNotFound => e
@logger.info("Auto-generated inventory: Skip machine '#{am[0]} (#{am[1]})', which is not configured for this Vagrant environment.")
end
end
# Write out groups information. Only includes groups and
@ -95,7 +110,7 @@ module VagrantPlugins
included_groups << gname
file.write("\n[#{gname}]\n")
gmembers.each do |gm|
file.write("#{gm}\n") if @machine.env.active_machines.map { |m| m[0] }.include?(gm.to_sym)
file.write("#{gm}\n") if inventory_machines.map { |m| m.name }.include?(gm.to_sym)
end
end
end