Skip to content

Commit 0e3b80d

Browse files
feat(corebuild): embed terraform definitions
1 parent 9493426 commit 0e3b80d

File tree

4 files changed

+70
-30
lines changed

4 files changed

+70
-30
lines changed

cmd/copsctl/main.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import (
99

1010
func main() {
1111
defer errorhandler()
12-
hq := hq.NewQuiet("copsctl", "0.12.0", "copsctl.log")
12+
hq := hq.NewQuiet("copsctl", "0.12.1", "copsctl.log")
1313
createCommands(hq)
1414

1515
error_handling.PanicOnAnyError = true

internal/adapters/kubernetes/commands.go

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package kubernetes
22

33
import (
44
"encoding/json"
5+
"github.com/conplementAG/copsctl/internal/common"
56
"github.com/conplementAG/copsctl/internal/common/file_processing"
67
"github.com/conplementag/cops-hq/v2/pkg/commands"
78
"github.com/sirupsen/logrus"
@@ -58,14 +59,20 @@ func Delete(executor commands.Executor, filepath string) (string, error) {
5859

5960
func ApplyString(executor commands.Executor, content string) (string, error) {
6061
temporaryDirectory, temporaryFile := file_processing.WriteStringToTemporaryFile(content, "resource.yaml")
61-
defer file_processing.DeletePath(temporaryDirectory)
62+
defer func() {
63+
err := file_processing.DeletePath(temporaryDirectory)
64+
common.FatalOnError(err)
65+
}()
6266

6367
return Apply(executor, temporaryFile)
6468
}
6569

6670
func DeleteString(executor commands.Executor, content string) (string, error) {
6771
temporaryDirectory, temporaryFile := file_processing.WriteStringToTemporaryFile(content, "resource.yaml")
68-
defer file_processing.DeletePath(temporaryDirectory)
72+
defer func() {
73+
err := file_processing.DeletePath(temporaryDirectory)
74+
common.FatalOnError(err)
75+
}()
6976

7077
return Delete(executor, temporaryFile)
7178
}

internal/common/file_processing/file_processing.go

Lines changed: 25 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,11 @@ import (
55
"fmt"
66
"github.com/conplementAG/copsctl/internal/common"
77
"github.com/conplementAG/copsctl/internal/corebuild/security"
8+
"github.com/rs/xid"
89
"gopkg.in/yaml.v3"
9-
"io"
10+
"io/fs"
1011
"os"
1112
"path/filepath"
12-
"strings"
13-
14-
"github.com/rs/xid"
1513
)
1614

1715
// WriteStringToTemporaryFile writes the file contents into a file on a temporary disk location
@@ -26,36 +24,37 @@ func WriteStringToTemporaryFile(fileContents string, filePath string) (outputFol
2624
}
2725

2826
// DeletePath deletes the file from the disk
29-
func DeletePath(filePath string) {
30-
err := os.RemoveAll(filePath)
31-
common.FatalOnError(err)
27+
func DeletePath(filePath string) error {
28+
return os.RemoveAll(filePath)
3229
}
3330

34-
// InterpolateStaticFiles loads all the files in given embed FS path.
31+
// CreateTempDirectory loads all the files in given embed FS path.
3532
// It depends on resource embedding, set by go:embed directive
36-
// Replaces the variables based on the given dictionary,
37-
// and returns the path to the generated directory where the results are stored
38-
func InterpolateStaticFiles(inputPathFs embed.FS, inputPathRootFolderName string, variables map[string]string) string {
39-
directory, readDirError := inputPathFs.ReadDir(inputPathRootFolderName)
40-
common.FatalOnError(readDirError)
33+
// Returns the path to the generated directory where the results are stored
34+
func CreateTempDirectory(inputPathFs embed.FS, inputPathRootFolderName string) (string, error) {
4135

4236
uniqueOutputFolder := createUniqueDirectory()
4337

44-
for _, file := range directory {
45-
f, err := inputPathFs.Open(inputPathRootFolderName + "/" + file.Name())
46-
common.FatalOnError(err)
47-
filesContent, err := io.ReadAll(f)
48-
common.FatalOnError(err)
49-
fileContentString := string(filesContent)
50-
for key, value := range variables {
51-
fileContentString = strings.Replace(fileContentString, key, value, -1)
38+
err := fs.WalkDir(inputPathFs, inputPathRootFolderName, func(path string, entry fs.DirEntry, err error) error {
39+
if err != nil {
40+
return err
5241
}
42+
relPath, err := filepath.Rel(inputPathRootFolderName, path)
43+
if err != nil {
44+
return err
45+
}
46+
destPath := filepath.Join(uniqueOutputFolder, relPath)
47+
if entry.IsDir() {
48+
return os.MkdirAll(destPath, 0755)
49+
}
50+
fileContent, err := inputPathFs.ReadFile(path)
51+
if err != nil {
52+
return err
53+
}
54+
return os.WriteFile(destPath, fileContent, 0644)
55+
})
5356

54-
err = os.WriteFile(filepath.Join(uniqueOutputFolder, file.Name()), []byte(fileContentString), 0644)
55-
common.FatalOnError(err)
56-
}
57-
58-
return uniqueOutputFolder
57+
return uniqueOutputFolder, err
5958
}
6059

6160
func LoadEncryptedFile[T interface{}](filename string, cryptographer security.Cryptographer) (*T, error) {

internal/corebuild/orchestrator.go

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package corebuild
22

33
import (
4+
"embed"
5+
"errors"
46
"fmt"
57
"github.com/conplementAG/copsctl/internal/adapters/azure"
68
"github.com/conplementAG/copsctl/internal/cmd/flags"
@@ -20,6 +22,9 @@ import (
2022
"path/filepath"
2123
)
2224

25+
//go:embed terraform/*
26+
var terraformDirectory embed.FS
27+
2328
type Orchestrator struct {
2429
hq hq.HQ
2530
executor commands.Executor
@@ -28,6 +33,7 @@ type Orchestrator struct {
2833
longNamingService naming.Service
2934
resourceGroupName string
3035
autoApprove bool
36+
cleanupActions []func() error
3137
}
3238

3339
func New(hq hq.HQ) (*Orchestrator, error) {
@@ -90,6 +96,9 @@ func (o *Orchestrator) CreateInfrastructure() {
9096
managedIdentityName, err := tf.Output(common.ToPtr("managed_identity_name"))
9197
common.FatalOnError(err)
9298

99+
err = o.runCleanupActions()
100+
common.FatalOnError(err)
101+
93102
logrus.Info("================== Build agent pool created ====================")
94103
logrus.Infof("Make sure you add public egress ip %s to all resources firewall access lists build agent needs access", publicEgressIp)
95104
logrus.Infof("Make sure you add build agent managed identity %s to all resources permissions needed", managedIdentityName)
@@ -112,6 +121,9 @@ func (o *Orchestrator) DestroyInfrastructure() {
112121
err = o.cleanup()
113122
common.FatalOnError(err)
114123

124+
err = o.runCleanupActions()
125+
common.FatalOnError(err)
126+
115127
logrus.Info("================== Build agent pool destroyed ====================")
116128
}
117129

@@ -148,13 +160,19 @@ func (o *Orchestrator) initializeTerraform() (terraform.Terraform, error) {
148160
return nil, err
149161
}
150162

163+
tempDir, err := file_processing.CreateTempDirectory(terraformDirectory, "terraform")
164+
o.cleanupActions = append(o.cleanupActions, func() error { return file_processing.DeletePath(tempDir) })
165+
if err != nil {
166+
return nil, err
167+
}
168+
151169
tf := terraform.New(o.executor, "core-build",
152170
o.config.Environment.SubscriptionID,
153171
o.config.Environment.TenantID,
154172
o.config.Environment.Region,
155173
o.resourceGroupName,
156174
terraformStorageAccountName,
157-
filepath.Join(hq.ProjectBasePath, "internal", "corebuild", "terraform"),
175+
tempDir,
158176
backendStorageSettings,
159177
terraform.DefaultDeploymentSettings)
160178
err = tf.Init()
@@ -225,6 +243,22 @@ func (o *Orchestrator) cleanup() error {
225243
return azureAdapter.RemoveResourceGroup(o.resourceGroupName)
226244
}
227245

246+
func (o *Orchestrator) runCleanupActions() error {
247+
var errs []string
248+
249+
for _, f := range o.cleanupActions {
250+
if err := f(); err != nil {
251+
errs = append(errs, err.Error())
252+
}
253+
}
254+
255+
if len(errs) > 0 {
256+
return errors.New("combined error: " + fmt.Sprint(errs))
257+
}
258+
259+
return nil
260+
}
261+
228262
type roleAssignment struct {
229263
Scope string `mapstructure:"scope" json:"scope" yaml:"scope"`
230264
RoleDefinitionName string `mapstructure:"role_definition_name" json:"role_definition_name" yaml:"role_definition_name"`

0 commit comments

Comments
 (0)