From 84308964e243f7f1bc6629c96211d0c49c29df91 Mon Sep 17 00:00:00 2001 From: Gilles Cornu Date: Sun, 2 Feb 2014 22:32:22 +0100 Subject: [PATCH] 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/...) --- plugins/provisioners/ansible/provisioner.rb | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/plugins/provisioners/ansible/provisioner.rb b/plugins/provisioners/ansible/provisioner.rb index 9a27ae3ca..d5c28f454 100644 --- a/plugins/provisioners/ansible/provisioner.rb +++ b/plugins/provisioners/ansible/provisioner.rb @@ -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