Skip to content

Commit

Permalink
feat: Come up with a standard to pass configuration to the deployed a…
Browse files Browse the repository at this point in the history
…pplication (#115)
  • Loading branch information
spchortis authored Oct 3, 2023
1 parent 2627252 commit f1b3c2b
Show file tree
Hide file tree
Showing 7 changed files with 85 additions and 5 deletions.
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 @@ -26,7 +26,7 @@ func (c *icli) Deploy(cCtx *cli.Context) error {
return err
}

return knative.Apply(cCtx.String(namespaceFlag), commitSha, config, project, c.dockerImage)
return knative.Apply(cCtx.String(namespaceFlag), commitSha, 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: defaults.EnvVarFile,
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.initium
registry-user: null
runtime-version: null
`,
Expand Down
73 changes: 70 additions & 3 deletions src/services/k8s/knative.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
package k8s

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

"github.com/charmbracelet/log"
"github.com/nearform/initium-cli/src/services/docker"
"github.com/nearform/initium-cli/src/services/project"
"github.com/nearform/initium-cli/src/utils/defaults"

corev1 "k8s.io/api/core/v1"
apimachineryErrors "k8s.io/apimachinery/pkg/api/errors"
Expand Down Expand Up @@ -42,7 +46,7 @@ func Config(endpoint string, token string, caCrt []byte) (*rest.Config, error) {
}, nil
}

func loadManifest(namespace string, commitSha string, project *project.Project, dockerImage docker.DockerImage) (*servingv1.Service, error) {
func loadManifest(namespace string, commitSha string, project *project.Project, dockerImage docker.DockerImage, envFile string) (*servingv1.Service, error) {
knativeTemplate := path.Join("assets", "knative", "service.yaml.tmpl")
template, err := template.ParseFS(project.Resources, knativeTemplate)
if err != nil {
Expand Down Expand Up @@ -80,15 +84,78 @@ func loadManifest(namespace string, commitSha string, project *project.Project,
UpdateTimestampAnnotationName: time.Now().Format(time.RFC3339),
}

envVarList, err := loadEnvFile(envFile)
if err != nil {
return nil, err
}

service.Spec.Template.Spec.Containers[0].Env = append(service.Spec.Template.Spec.Containers[0].Env, envVarList...)

return service, nil
}

func Apply(namespace string, commitSha 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)) && (path.Base(envFile) == defaults.EnvVarFile) {
log.Infof("No environment variables file %s to Load!", defaults.EnvVarFile)
} else {
return nil, fmt.Errorf("Error loading %v file: %v", envFile, err)
}
} else {
log.Infof("Environment variables file %s found! Loading..", envFile)
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.Infof("Environment variables file %v content is now loaded!", envFile)
} else {
log.Warnf("Environment file %v is empty, Nothing to load!", envFile)
}
}
return envVarList, nil
}

func Apply(namespace string, commitSha 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()

serviceManifest, err := loadManifest(namespace, commitSha, project, dockerImage)
serviceManifest, err := loadManifest(namespace, commitSha, project, dockerImage, envFile)
if err != nil {
return err
}
Expand Down
3 changes: 2 additions & 1 deletion src/services/k8s/knative_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ func TestLoadManifest(t *testing.T) {
Tag: "v1.1.0",
}

serviceManifest, err := loadManifest(namespace, commitSha, proj, dockerImage)
serviceManifest, err := loadManifest(namespace, commitSha, proj, dockerImage, path.Join(root, "example/.env.sample"))

if err != nil {
t.Fatalf(fmt.Sprintf("Error: %v", err))
Expand All @@ -80,3 +80,4 @@ func TestLoadManifest(t *testing.T) {
assert.Assert(t, annotations[UpdateTimestampAnnotationName] != "", "Missing %s annotation", UpdateTimestampAnnotationName)
assert.Assert(t, annotations[UpdateShaAnnotationName] == commitSha, "Expected %s SHA, got %s", commitSha, annotations[UpdateShaAnnotationName])
}

1 change: 1 addition & 0 deletions src/utils/defaults/defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const (
ConfigFile string = ".initium.yaml"
AppVersion string = "latest"
GeneratedDockerFile string = "Dockerfile.initium"
EnvVarFile string = ".env.initium"
)

// renovate: datasource=docker depName=node
Expand Down

0 comments on commit f1b3c2b

Please sign in to comment.