microsoft / vscode-docker

Docker Extension for Visual Studio Code
https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-docker
Other
1.19k stars 508 forks source link

docker-build could not take .env file when build #4191

Closed duchuyvp closed 5 months ago

duchuyvp commented 6 months ago

First, here is my .vscode/tasks.json:

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "docker-build",
            "label": "docker-build",
            "platform": "python",
            "dockerBuild": {
                "tag": "service:latest",
                "dockerfile": "${workspaceFolder}/Dockerfile",
                "context": "${workspaceFolder}",
                "buildArgs": {
                    // "GITHUB_TOKEN": "${GITHUB_TOKEN}" not working
                    "GITHUB_TOKEN": "ghp_sometoken", // this works obviously
                },
                "pull": true
            }
        }
    ]
}

I want to pass GITHUB_TOKEN with --build-arg to install a private module when running the build, but it seems not to read the .env file.

When I set "GITHUB_TOKEN": "${GITHUB_TOKEN}", the executed command is:

docker image build --pull --file 'workspaceFolder/Dockerfile' --tag 'service:latest' --label 'com.microsoft.created-by=visual-studio-code' --build-arg 'GITHUB_TOKEN=${GITHUB_TOKEN}' 'workspaceFolder'

And when I set "GITHUB_TOKEN": "${env:GITHUB_TOKEN}", the executed command is:

docker image build --pull --file 'workspaceFolder/Dockerfile' --tag 'service:latest' --label 'com.microsoft.created-by=visual-studio-code' --build-arg 'GITHUB_TOKEN=' 'workspaceFolder' (GITHUB_TOKEN is an empty string)

I think it's not an issue; it may not be supported yet. So, is there an alternative way to build with arguments from the .env file?

bwateratmsft commented 6 months ago

A couple of thoughts:

  1. env files don't get picked up for build, that is intentional.
  2. Be sure that you aren't stamping your GitHub token into the image. It's OK to use it as a build-time secret but don't set it as an environment variable (or similar) in the image, because images should be considered public even if they are ultimately stored in a private registry.
  3. You should be able to make this scenario work by using ${env:GITHUB_TOKEN} and launching VSCode with that environment variable set (i.e. set it as a system environment variable or launch from a terminal with that environment variable set). I guess we don't have ${env:FOO} replacement implemented for our tasks, I thought we did.
bwateratmsft commented 4 months ago

This has been released in Docker extension version 1.29.0.