environment-variablesvscode-devcontainercodespacesgithub-codespacesdevcontainer

Using GitHub Codespaces secrets in devcontainer.json


Problem

Some library I use requires the case sensitive environment variable QXToken. When I create a codespaces secret the environment variable is only available in uppercase (QXTOKEN), as the secrets are case insensitive. Therefore I want to copy the secret stored in QXTOKEN to the environment variable QXToken.

I tried to do that in the devcontainer.json:

{
    ...

    "remoteEnv": {
        "QXAuthURL": "https://auth.quantum-computing.ibm.com/api",
        "QXToken": "${secrets.QXTOKEN}"
    },

    "updateContentCommand": "env; export QXToken=$QXTOKEN; env",
    "postCreateCommand": "env; export QXToken=$QXTOKEN; env",
    "postStartCommand": "env; export QXToken=$QXTOKEN; env",
    "postAttachCommand": "env; export QXToken=$QXTOKEN; env"
}

But remoteEnv cannot access the codespaces secrets via ${secrets.QXTOKEN} as one would be able to with GitHub Actions and none of updateContentCommand, postCreateCommand, postStartCommand and postAttachCommand saved the environment variable persistently for the user. Using the command env I see from the logs that the environment variables have been set, but already in the next command they are gone. Even though the postCreateCommand is able to access the codespaces secrets according to the documentation I was not able to set environment variables for later usage.

For now I only see the following environment variables, but I am missing QXToken:

$ env | grep QX
QXAuthURL=https://auth.quantum-computing.ibm.com/api
QXTOKEN=***

Question

Is there a best practice to reuse codespaces secrets inside devcontainer.json and make them available as environment variables in the codespace?


Solution

  • The GitHub Codespaces secrets are available via localEnv which is a special variable used by devcontainer.json which provides access to environment variables on the host machine. Therefore, you can set the environment variable QXToken with ${localEnv:QXTOKEN} inside devcontainer.json.
    Furthermore, if you want to set an environment variable pointing to a path inside your repo you can use ${containerWorkspaceFolder}/path/inside/your/repo.

    "remoteEnv": {
        // Use a GitHub Codespaces secret:
        "QXToken": "${localEnv:QXTOKEN}",
        // Point to a path inside your repo:
        "QISKIT_SETTINGS": "${containerWorkspaceFolder}/.qiskit/settings.conf"
    }
    

    For more details on the available variables in devcontainer.json have a look at the documentation.