[Solved] Can't assign a Tag to VM


This is the call:


And this the result:

NoMethodError: undefined method `stringify_keys' for 1000000000181:Fixnum


Here the code:

vm_name = "dfghjkoiuyt56789-1"
vm = VmOrTemplate.find_by_name(vm_name)

cloud_id = vm.ems_id
tenant_id = vm.cloud_tenant_id

cloud = EmsOpenstack.find_by_id(cloud_id)

tenant_name = cloud.cloud_tenants.find_by_id(tenant_id).name

correct_tag = (cloud.name + '_' + tenant_name).downcase

if Tag.find_by_classification_name('tenant/'+correct_tag).nil?
  puts "Tag doesn't exist, ignoring."
  tag_defined = 1
  vm.tags.each do |tag|
    if tag.name == '/managed/tenant/' + correct_tag
      tag_defined = 0
  if tag_defined == 1
    tag_id = Tag.find_by_classification_name('/tenant/' + correct_tag)['id']

I don’t think this is the “right” way to tag something. Basically, you should never need to use the Tagging model directly (think private model). The “right” way is to use the tag_add or tag_remove methods on the vm.

cc @gmccullough @gtanzillo Can you verify?

@Fryguy, that’s correct. Those are the methods that should be used for adding and removing tags for an object.

Definitely it looks much better.
I can’t find the input parameters of tag_add and tag_remove. Where I can find that info @gtanzillo?



Page 36

The tag methods are defined here:

Thanks to all.
I’m creating and removing tags now:

vm.tag_add(’/managed/tenant/’+correct_tag, {:ns => nil})
vm.tag_remove(tag.name, {:ns => nil})

Is there any way to delete the tags from the VMDB? The customer has many extraneous tags that at one time were tagged on an object, but that object has since been deleted. However, the tags are still in the VMDB. I can’t seem to find the method to do this. Thanks.

To completely delete the tags from VMDB use the Classification model:

# Delete single tag
tag = Classification.find_by_name("test_category/test_tag")

# Delete entire tag category
category = Classification.find_by_name("test_category")

What is the difference between tag_add vs tag_assign and tag_remove vs tag_unassign?

In page 18 of this doc:
and Chapter 2.3 of this doc:

it references tag_assign , add_tag ,tag_unassign, and clear_tag only. In automate (CFME version ), vm.tag_add and vm.tag_remove results in the following errors :

NoMethodError: undefined method `tag_add' for #<MiqAeMethodService::MiqAeServiceVmRedhat:0x000000091c1a70>


NoMethodError: undefined method `tag_remove' for #<MiqAeMethodService::MiqAeServiceVmRedhat:0x000000015a4bb8>

Both the tag_assign and tag_unassign methods defined in
miq_ae_service_model_base.rb does work in adding/removing tags to
an MiqAeService* object.

The methods discussed in this thread are being called from a Rails runner script which is directly accessing the active_record models. These methods are not directly exposed to automate.

When writing automate methods you want to utilize the tag methods defined in the guides you referenced.