Managing Associations Between Generic Objects from Ansible
One of the things that makes CloudForms generic objects very versatile is the ability to add associations to other object classes (including other generic objects) in the generic object definition. These associations can be be implemented as one-to-one (has_one in Rails-speak) or one-to-many (has_many in Rails-speak).
Note
Associations between generic objects are always has_many, even though we may wish to logically implement them as has_one
The previous example used generic object classes to represent firewall groups and their components. The firewall software uses the concept of a firewall group that contains one or more port groups, network groups and address groups, and so the generic object definitions included the following associations:
A firewall_group has_many port_groups, network_groups and address_groups
A port_group, network_groups and address_groups each has_one firewall_group
Implementing generic object associations from Ruby is straightforward. The has_one association is a simple assignment, as follows:
Implementing the has_many association from Ruby is a matter of adding the new association to an existing association list, as follows:
Associations from Ansible
Generic object associations can also be created from Ansible. The following playbook snippets show an alternative way of linking a newly created NetworkGroup object to its parent FirewallGroup object.
Implementing a has_one rule from an Ansible playbook is fairly straightforward. The playbook first creates the new network group generic object, with a single association back to the firewall group:
Adding the new network group to the list of has_many associations for the firewall group is less straightforward though. Just POSTing the new association will overwrite any existing associations. The existing associations must first be read, the new association appended to the list, and then the updated list POSTed back.
A typical json extract of the network_groups association list from the registered associations
variable might be as follows:
We need to extract the existing association hrefs into their own list...
Add the new association href to the list:
Now POST the updated list back to the generic object:
The generic object classes now appear linked together as expected in the WebUI.
Summary
This chapter has shown how generic objects can be created and linked together in associations, from an Ansible playbook. The full scripts are available here
Further Reading
Last updated