Search code examples
chef-infrachef-recipe

How do I sort nodes from a Chef search?


I have a list of nodes returned from a chef search, which will be used to create a configuration file. These nodes need to be ordered because

  1. The software the configuration file is for needs these nodes to be in order
  2. Chef does not always return nodes in the same order, and so the file will be rewritten each time chef runs even though the configuration remains the same.

Solution

  • To create a list of nodes sorted by attribute, you would do something like this, which sorts the nodes by their domain name:

    nodes = search(:node, "fqdn:*")
    nodes.sort_by!{ |n| n[:fqdn] }
    

    To return a list of only these attributes, this could be extended with:

    nodes.map!{ |n| n[:fqdn] }
    

    On more recent versions of Chef, :filter_result can be used to only fetch the node attributes that will be used:

    nodes = search(:node, "fqdn:*", filter_result: { fqdn: [:fqdn] })
    nodes.map! { |node| node[:fqdn] }
    nodes.sort!