Using environmental variables for credentials

Hi All,

Looking for some help/advice on using environmental variables for credentials for a project I’m working on. Here’s what I’ve got:

# Gathering environmental variables and assigning to variables to use throughout code.
env_uname = os.environ['NORNIR_DEFAULT_USERNAME']
env_pword = os.environ['NORNIR_DEFAULT_PASSWORD']

def get_nr():
    """
    This function initialises a Nornir inventory
    #TODO: Fix documentation
    :return InitNornir: An initialised Nornir inventory
    """
    return InitNornir(
        inventory={
            "options": {
                "host_file": "inventory/hosts.yaml",
                "group_file": "inventory/groups.yaml",
                "defaults_file": "inventory/defaults.yaml", 
            }
        }
    )

def get_facts():
    # Initialise Nornir
    nr = get_nr()
    # Set default username and password from environmental variables.
    # TODO: There has to be a better way to replicate this for 
    # every function but it works for now.
    nr.inventory.defaults.username = env_uname
    nr.inventory.defaults.password = env_pword
    r = nr.run(task=napalm_get, getters=["facts"])
   return r

I have numerous functions like get_users which call the get_nr function. Is there an easier way to relocate the nr.inventory.defaults.username = env_uname and nr.inventory.defaults.password = env_pword code into the get_nr function so I don’t have to declare it outside of it every time?

Easiest would be to just move those two lines to get_nr:

def get_nr():
    nr = InitNornir(
        inventory={
            "options": {
                "host_file": "inventory/hosts.yaml",
                "group_file": "inventory/groups.yaml",
                "defaults_file": "inventory/defaults.yaml", 
            }
        }
    nr.inventory.defaults.username = env_uname
    nr.inventory.defaults.password = env_pword
    return nr
    )

Otherwise, look at the transform_function which can be part of the InitNornir arguments

Thanks @dbarrosop. I came up the following below and it worked:

def get_nr():
nr = InitNornir(
    inventory={
        "options": {
            "host_file": "inventory/hosts.yaml",
            "group_file": "inventory/groups.yaml",
            "defaults_file": "inventory/defaults.yaml", 
        }
    }
)
nr.inventory.defaults.username = env_uname
nr.inventory.defaults.password = env_pword
return nr

Appreciate your help :grinning: