Skip to content

Instantly share code, notes, and snippets.

Created October 4, 2017 19:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/2d506c46ddc1f23ec94c0dcfcb41f1c6 to your computer and use it in GitHub Desktop.
Save anonymous/2d506c46ddc1f23ec94c0dcfcb41f1c6 to your computer and use it in GitHub Desktop.
#
# Description: Assign unowned vms to group's service
#
vms = $evm.vmdb('vm').where(:template => false)
vms.each do |vm|
if vm.cloud
created_on = vm.created_on
current = Time.now
drift = current - created_on
#$evm.log(:info, "#{vm.name} drift is #{drift.to_f / 3600} hours.")
next if drift < 1.hour
if vm.retired
retires_on = vm.retires_on
drift = current - retires_on
next if drift < 1.hour
vm.remove_from_vmdb
next
elsif vm.archived
if vm.previous_state == 'ERROR'
vm.remove_from_vmdb
next
else
updated_on = vm.updated_on
drift = current - updated_on
next if drift < 1.hour
vm.remove_from_vmdb
next
end
end
prov = nil
request = nil
prov = vm.miq_provision
request = prov.miq_provision_request unless prov.nil?
unless prov.nil? && request.nil?
next unless (prov.state == 'finished' && request.request_state == 'finished')
end
next unless vm.direct_service.nil?
next unless vm.service.nil?
cloud_tenant_id = vm.cloud_tenant_id
cloud_tenant = $evm.vmdb('cloud_tenant', cloud_tenant_id)
tenant = $evm.vmdb('tenant').where(:source_type => 'CloudTenant', :name => cloud_tenant.name).first
group = $evm.vmdb('miq_group').where(:group_type => 'user', :tenant_id => tenant.id).first
unless $evm.vmdb('service').where(:name => tenant.name).any?
new_service = $evm.vmdb('service').create(:name => tenant.name)
new_service.group = group
new_service.display = true
end
service = $evm.vmdb('service').where(:name => tenant.name).first
tag = "tenant/#{tenant.name.to_s.downcase}"
unless service.tagged_with?('tenant', tenant.name.to_s.downcase)
$evm.log(:info, "Assign tag #{tag} to service #{service.name}")
service.tag_assign(tag)
$evm.log(:info, "Related tags for service #{service.name} -- #{service.tags}")
end
vm.add_to_service(service) rescue $evm.log(:warn, "Vm #{vm.name} is already connected to a service.")
vm.group = group
unless vm.tagged_with?('tenant', tenant.name.to_s.downcase)
$evm.log(:info, "Assign tag #{tag} to vm #{vm.name}")
vm.tag_assign(tag)
$evm.log(:info, "Related tags for vm #{vm.name} -- #{vm.tags}")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment