Trying to pass authenticated userid to DockerSpawner.environment

Hello! I’m trying to pass the authenticated user’s uid to the container’s environment using DockerSpawner.environment and a pre_spawn_hook. This isn’t working, and I’m guessing its might be because DockerSpawner.environment is set before the pre_spawn_hook? If I hardcode the NB_UID in the DockerSpawner.environment dict it works fine.

Is there a better way to pass the uid to the container env instead of using the pre_spawn_hook?

c.DockerSpawner.environment = {
    'GRANT_SUDO': '1',
    #'NB_UID':1234,
    #'NB_GID':10001,
    }

c.JupyterHub.spawner_class = 'dockerspawner.DockerSpawner'

def my_hook(spawner):
    username = spawner.user.name
    uid = getpwnam(username)[2]
    c.DockerSpawner.environment['NB_UID'] = uid
    print(c.DockerSpawner.environment)

c.DockerSpawner.pre_spawn_hook = my_hook

c.JupyterHub.authenticator_class = 'jupyterhub.auth.PAMAuthenticator'

Thanks!

Your hook must be:

def my_hook(spawner):
    username = spawner.user.name
    uid = getpwnam(username)[2]
    spawner.environment['NB_UID'] = uid
    print(spawner.environment)

The argument spawner to my_hook is the actual spawner object created for the current spawn. So you need to set attributes on that spawner object.

2 Likes

This worked perfectly, thank you!

1 Like