Search code examples
pythonsalt-project

Access Environmental Variables with SaltStack Grains


I would like to know how to correctly access Environmental Variables with SaltStack Grains.

I have been following the documentation but have been unable to get it working. Here is the code that I have:

/srv/salt/_grains/env_vars.py

import os

def env_vars():
    return {'T17_SECRET_KEY': os.environ.get('T17_SECRET_KEY','')}

I then run salt '*' saltutil.sync_grains

And I get this response:

salt:
    - grains.env_vars

But when I run salt '*' grains.items it shows:

salt:
    ----------
    SSDs:
    T17_SECRET_KEY:
    # other vars ...

So the key is there, but the value is not. When I run os.environ.get('T17_SECRET_KEY','') from the Python Command Line, the value is there.

What could be causing this?

EDIT

I have changed this:

/srv/salt/_grains/env_vars.py

from salt.modules import environ

def env_vars():
    return {'T17_SECRET_KEY': environ.get('T17_SECRET_KEY','')}

When I execute this function from the Python Command line, it returns the Key:Value, but still when running salt '*' saltutil.sync_grains and salt '*' grains.items I cannot see the Value, only the Key.

I even ran salt '*' state.highstate to reload everything.

Is this possibly being caused by some other configuration?


Solution

  • os.environ accesses the process environment of the (random) Salt minion which happens to execute your code; if you want to access the environment of the current salt process, you need to use this module instead: salt.modules.environ

    The reason for this is that salt can run your code on any of a number of computers. The environment will probably be different for each of them. So unless you can make sure that your code is running on a certain minion and the environment on that minion is correct, your code can't work.

    The module salt.modules.environ gives you access to the virtual process environment which salt builds when you submit a command.

    To properly access the salt.modules.environ use the salt.states.environ by adding the following files:

    /srv/salt/_grains/env_vars.py

    from salt.modules import environ
    
    def env_vars():
        return {'T17_SECRET_KEY': environ.get('T17_SECRET_KEY','')}
    

    /srv/salt/environ/init.sls

    T17_SECRET_KEY:
        environ.setenv:
            - name: T17_SECRET_KEY
            - value: <secret_key_value_here>
            - update_minion: True
    

    Then run this to sync the newly added environmental variable:

    salt '*' state.sls environ
    
    salt '*' saltutil.sync_grains
    

    To verify, this code can be ran:

    salt '*' grains.get T17_SECRET_KEY