Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance azd init to auto-detect Dockerfile ARGS and update azure.yaml #4639

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions cli/azd/internal/appdetect/appdetect.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"path/filepath"

"github.com/azure/azure-dev/cli/azd/pkg/exec"
"github.com/azure/azure-dev/cli/azd/pkg/osutil"
"github.com/azure/azure-dev/cli/azd/pkg/tools/dotnet"
"github.com/bmatcuk/doublestar/v4"
)
Expand Down Expand Up @@ -167,8 +168,9 @@ type Port struct {
}

type Docker struct {
Path string
Ports []Port
Path string
Ports []Port
BuildArgs []osutil.ExpandableString
}

type projectDetector interface {
Expand Down
49 changes: 48 additions & 1 deletion cli/azd/internal/repository/app_init.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package repository

import (
"bufio"
"context"
"fmt"
"maps"
Expand Down Expand Up @@ -44,6 +45,34 @@ var dbMap = map[appdetect.DatabaseDep]struct{}{

var featureCompose = alpha.MustFeatureKey("compose")

// parseDockerfileForArgs parses a Dockerfile to extract ARG instructions and returns them as ExpandableString values.
func parseDockerfileForArgs(dockerfilePath string) ([]osutil.ExpandableString, error) {
var buildArgs []osutil.ExpandableString

file, err := os.Open(dockerfilePath)
if err != nil {
return nil, fmt.Errorf("failed to open Dockerfile: %w", err)
}
defer file.Close()

scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(line, "ARG ") {
argLine := strings.TrimPrefix(line, "ARG ")
if len(argLine) > 0 {
buildArgs = append(buildArgs, osutil.NewExpandableString(argLine))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if creating an osutil.ExpandableString here is the right thing? I think that we probably just want to use string (or maybe a structured type that contains the arg name and optional default value). I don't think you'd ever want to call Envsubst or MustEnvsubst on this value since the docker language doesn't think about doing env-var substitution for ARGs.

For the docs, it looks like the ARG directive in a dockerfile could look like this:

ARG foo=${BAR}

Which from my understanding would mean an argument called "foo" with the default value of ${BAR}.

I'm a little worried that when faced with a file like this, we'd end up doing the wrong thing end to end (but I will admit that from the linked issue, I also don't have a great idea of what the expectation is here either).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ellismg The use of the osutil.ExpandableString type to store buildArgs is to populate the buildArgs configuration in the azure.yaml file. Later, when parsing the azure.yaml file, Envsubst() will be used to replace the environment variable of arg in buildArgs.

For the ARG instruction ARG foo=${BAR} in the Dockerfile, the underlying processing flow of Azd is as follows:

  • If the foo arg is not configured in the buildArgs in azure.yaml, the bottom layer finally runs the docker build . command to build the project. Since --build-arg foo is not specified, the value of foo is the defined default value ${BAR}.

  • If the foo arg is configured in buildArgs in azure.yaml:

    • When the value of the arg foo is hardcode, the Azd bottom layer will build the project by running the command docker build . --build-arg foo=xxxxxx.
    • When the value of the arg foo is the environment variable ${AZURE_BAR}, the environment variable is replaced with the corresponding value, and the Azd bottom layer will finally build the project by running docker build . --build-arg foo=xxxxxx.

}
}
}

if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("error reading Dockerfile: %w", err)
}

return buildArgs, nil
}

// InitFromApp initializes the infra directory and project file from the current existing app.
func (i *Initializer) InitFromApp(
ctx context.Context,
Expand Down Expand Up @@ -264,6 +293,23 @@ func (i *Initializer) InitFromApp(
}
}

for idx := range detect.Services {
servicePath := detect.Services[idx].Path
dockerfilePath := filepath.Join(servicePath, "Dockerfile")

if _, err := os.Stat(dockerfilePath); err == nil {

buildArgs, err := parseDockerfileForArgs(dockerfilePath)
if err != nil {
return fmt.Errorf("failed to parse Dockerfile ARGs at %s: %w", dockerfilePath, err)
}

if len(buildArgs) > 0 {
detect.Services[idx].Docker.BuildArgs = buildArgs
}
}
}

tracing.SetUsageAttributes(fields.AppInitLastStep.String("generate"))

title = "Generating " + output.WithHighLightFormat("./"+azdcontext.ProjectFileName)
Expand Down Expand Up @@ -544,7 +590,8 @@ func ServiceFromDetect(
}

svc.Docker = project.DockerProjectOptions{
Path: relDocker,
Path: relDocker,
BuildArgs: prj.Docker.BuildArgs,
}
}

Expand Down
13 changes: 12 additions & 1 deletion cli/azd/internal/repository/app_init_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/azure/azure-dev/cli/azd/internal"
"github.com/azure/azure-dev/cli/azd/internal/appdetect"
"github.com/azure/azure-dev/cli/azd/pkg/input"
"github.com/azure/azure-dev/cli/azd/pkg/osutil"
"github.com/azure/azure-dev/cli/azd/pkg/project"
"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -93,7 +94,13 @@ func TestInitializer_prjConfigFromDetect(t *testing.T) {
{
Language: appdetect.DotNet,
Path: "dotnet",
Docker: &appdetect.Docker{Path: "Dockerfile"},
Docker: &appdetect.Docker{
Path: "Dockerfile",
BuildArgs: []osutil.ExpandableString{
osutil.NewExpandableString("ARG1"),
osutil.NewExpandableString("ARG2"),
},
},
},
},
},
Expand All @@ -112,6 +119,10 @@ func TestInitializer_prjConfigFromDetect(t *testing.T) {
RelativePath: "dotnet",
Docker: project.DockerProjectOptions{
Path: "Dockerfile",
BuildArgs: []osutil.ExpandableString{
osutil.NewExpandableString("ARG1"),
osutil.NewExpandableString("ARG2"),
},
},
},
},
Expand Down
Loading