Using grain data in a custom salt stack grain

saltstack

I would like to write what is effectively a "virtual grain" that determines some value based on the value of other grains, using a custom grain. Specifically, I want to provide a grain values, env, that tells me which virtual environment the host is running in. The options will be aws, or none currently, but in the future will include datacentre and office. I'll be using this information to determine configs like which SMTP relay to use, etc.

My first attempt was to use the __grains__ dict, but it appears to be empty when accessed within the custom grain.

def find_env():
    if __grains__['os'] == 'Amazon':
        return {'env':['aws']}
    return {'env': []}

this results in an exception:

KeyError: 'os'

I realise that I could statically assign the grains on the minion or on the command line, but I feel that any bit of information that can be derived automatically should be.

Is there a way to access existing grain data when writing custom grains, or another way of automatically classifying hosts so that I can target the state to them?

Best Answer

I'd suggest using states to assign grain values as appropriate. For example, something like:

top.sls

base:
  'kernel:Linux':
    - match: grain
    - linux

linux.sls

env:
  grains.present:
    {% if grains ['os'] == 'Amazon' %}
    - value: aws
    {% else %}
    - value: somethingelse
    {% endif %}

There are other cleaner ways of doing this, but this should get you going.

Related Topic