Search code examples
pythondebiansalt-stack

Unable to access default grains data in custom grains


I have a task to create custom grains in salt (/srv/salt/_grains). I have to access the default grains data for these custom grains to check the ms_minion serial_number. Unfortunately, I can't access the default grains data in custom grains. Can anyone help with this?

I have added a sample code here. I'm using salt 3004.2 in Debian 11

#!/usr/bin/env python3

def gethwtype():
    hw = __grains__["serialnumber"]

    #return __grains__["os"]
    grains = {}

    grains["bm_tag"]= hw
    return grains

Solution

  • yes __grains__ is not passed into the function by the grains loader so will not exist. however there is an argument passed into grain functions called grains. which is all of the grains rendered up to that point.

    this should only be used for looking up core grains within your custom grain. as you can not be sure another custom grain is loaded first.

    def gethwtype(grains):
        hw = grains["serialnumber"]
        grains = {}
        grains["bm_tag"]= hw
        return grains
    

    see the last line in https://docs.saltproject.io/en/latest/topics/grains/index.html#precedence