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?


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


    - match: grain
    - linux


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

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

| improve this answer | |
  • Thanks @MikeyB, I just wanted to see if I missed something here, because this looks like it should be in top.sls, but I get errors putting it there: Improperly formatted top file matcher in environment OrderedDict... What I ended up doing was to create an 'env' directory in my states, and created a state for each of the environments that sets the appropriate grain, and then in the top.sls I put something like: 'os:Amazon': - match: grain - env.aws – Nigel Sep 30 '14 at 8:29
  • top.sls and other top-level sls files are actually a different format than everything else. – MikeyB Sep 30 '14 at 20:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.