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

feat: Come up with a standard to pass configuration to the deployed application #115

Merged
merged 13 commits into from
Oct 3, 2023
Merged
1 change: 1 addition & 0 deletions assets/docker/Dockerfile.node.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ RUN npm test
FROM gcr.io/distroless/nodejs20-debian11
COPY --from=build-env /src /src
WORKDIR /src
USER nonroot
CMD ["index.js"]
4 changes: 4 additions & 0 deletions example/.env.sample
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
MOCK1="value1"
MOCK2="value2"
MOCK3:"value3"
MOCK4 "value4"
2 changes: 1 addition & 1 deletion src/cli/deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func (c *icli) Deploy(cCtx *cli.Context) error {
return err
}

return knative.Apply(cCtx.String(namespaceFlag), config, project, c.dockerImage)
return knative.Apply(cCtx.String(namespaceFlag), config, project, c.dockerImage, cCtx.String(envVarFileFlag))
}

func (c icli) DeployCMD() *cli.Command {
Expand Down
6 changes: 6 additions & 0 deletions src/cli/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ const (
namespaceFlag string = "namespace"
stopOnBuildFlag string = "stop-on-build"
stopOnPushFlag string = "stop-on-push"
envVarFileFlag string = "env-var-file"
)

type flags struct {
Expand Down Expand Up @@ -100,6 +101,11 @@ func InitFlags() flags {
Required: true,
Category: "deploy",
},
&cli.StringFlag{
Name: envVarFileFlag,
Value: ".env",
Category: "deploy",
},
},
Registry: []cli.Flag{
&cli.StringFlag{
Expand Down
1 change: 1 addition & 0 deletions src/cli/init_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ cluster-endpoint: null
container-registry: %s
default-branch: main
dockerfile-name: null
env-var-file: .env
registry-user: null
runtime-version: null
`,
Expand Down
64 changes: 63 additions & 1 deletion src/services/k8s/knative.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package k8s

import (
"bufio"
"bytes"
"context"
"fmt"
"os"
"path"
"strings"
"text/template"
"time"

Expand Down Expand Up @@ -71,7 +74,63 @@ func loadManifest(project *project.Project, dockerImage docker.DockerImage) (*se
return service, nil
}

func Apply(namespace string, config *rest.Config, project *project.Project, dockerImage docker.DockerImage) error {
func loadEnvFile(envFile string) ([]corev1.EnvVar, error) {
var envVarList []corev1.EnvVar
if _, err := os.Stat(envFile); err != nil {
if os.IsNotExist(err) {
log.Info("No environment variables file to Load!")
spchortis marked this conversation as resolved.
Show resolved Hide resolved
} else {
return nil, fmt.Errorf("Error checking %v file: %v", envFile, err)
}
} else {
log.Info(fmt.Sprintf("Environment variables file %s found! Loading..", envFile))
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
log.Info(fmt.Sprintf("Environment variables file %s found! Loading..", envFile))
log.Infof("Environment variables file %s found! Loading..", envFile)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I had checked on their page for Infof and couldn't find anything related.. And then they had that for formatting messages with log.Info, that is why I went with it. Since Infof is working, switching to that one..

Copy link
Member

Choose a reason for hiding this comment

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

That's interesting, should we contribute back to their repo and add the Infof?

file, err := os.Open(envFile)
if err != nil {
return nil, fmt.Errorf("Error opening %v file: %v", envFile, err)
}
defer file.Close()

scanner := bufio.NewScanner(file)
envVariables := make(map[string]string)

checkFormat := func(line string) bool {
parts := strings.SplitN(line, "=", 2)
return len(parts) == 2
}

for scanner.Scan() {
line := scanner.Text()
if checkFormat(line) {
parts := strings.SplitN(line, "=", 2)
key := strings.TrimSpace(parts[0])
value := strings.TrimSpace(parts[1])
envVariables[key] = value
} else {
log.Warnf("Environment variables file %v line won't be processed due to invalid format: %s. Accepted: KEY=value", envFile, line)
}
}

if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("Error reading environment variables file %v: %v", envFile, err)
}

if len(envVariables) > 0 {
for key, value := range envVariables {
envVar := corev1.EnvVar{
Name: key,
Value: value,
}
envVarList = append(envVarList, envVar)
}
log.Info(fmt.Sprintf("Environment variables file %v content is now loaded!", envFile))
LucaLanziani marked this conversation as resolved.
Show resolved Hide resolved
} else {
log.Warnf("Environment file %v is empty, Nothing to load!", envFile)
}
}
return envVarList, nil
}

func Apply(namespace string, config *rest.Config, project *project.Project, dockerImage docker.DockerImage, envFile string) error {
log.Info("Deploying Knative service", "host", config.Host, "name", project.Name, "namespace", namespace)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute*5)
defer cancel()
Expand Down Expand Up @@ -105,6 +164,9 @@ func Apply(namespace string, config *rest.Config, project *project.Project, dock
return fmt.Errorf("cannot create namespace %s, failed with %v", serviceManifest.ObjectMeta.Namespace, err)
}

envVarList, err := loadEnvFile(envFile)
serviceManifest.Spec.Template.Spec.Containers[0].Env = append(serviceManifest.Spec.Template.Spec.Containers[0].Env, envVarList...)

service, err := servingClient.Services(serviceManifest.ObjectMeta.Namespace).Get(ctx, serviceManifest.ObjectMeta.Name, metav1.GetOptions{})
var deployedService *servingv1.Service
if err != nil {
Expand Down
17 changes: 17 additions & 0 deletions src/services/k8s/knative_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,20 @@ func TestLoadManifest(t *testing.T) {
}

}

func TestLoadEnvVars(t *testing.T) {

fmt.Println("Testing .env sample with mixed accepted & invalid lines")
_, err := loadEnvFile(path.Join(root, "example/.env.sample"))

if err != nil {
t.Fatalf(fmt.Sprintf("Error: %v", err))
}

fmt.Println("Testing non existing .env sample file")
_, err = loadEnvFile(path.Join(root, "example/.env.non-exist"))

if err != nil {
t.Fatalf(fmt.Sprintf("Error: %v", err))
}
}