Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#
# 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
tenant_id = vm.tenant_id
tenant = $evm.vmdb('tenant').find_by_id(tenant_id)
if tenant.source_type.nil? || tenant.source_type.to_s != 'CloudTenant'
cloud_tenant = $evm.vmdb('cloud_tenant').find_by_id(cloud_tenant_id)
cloud_tenant_name = cloud_tenant.name
tenant = $evm.vmdb('tenant').where(:source_type => 'CloudTenant', :name => cloud_tenant_name).first
end
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)
$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)
$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