blob: 1333f28ef087473114e29617a2a2b23dfa721432 [file] [log] [blame]
Giorgi Lekveishvili46743d42023-12-10 15:47:23 +04001package tasks
2
3import (
4 "bytes"
5 "embed"
6 "encoding/base64"
7 "fmt"
8 "path"
9 "strings"
10 "text/template"
Giorgi Lekveishvili46743d42023-12-10 15:47:23 +040011)
12
13//go:embed env-tmpl
14var filesTmpls embed.FS
15
Giorgi Lekveishvili46743d42023-12-10 15:47:23 +040016func NewActivateEnvTask(env Env, st *state) Task {
Giorgi Lekveishvili378ea882023-12-12 13:59:18 +040017 return newSequentialParentTask(
Giorgi Lekveishvili5c1b06e2024-03-28 15:19:44 +040018 "Activate GitOps",
19 false,
Giorgi Lekveishvili378ea882023-12-12 13:59:18 +040020 AddNewEnvTask(env, st),
21 // TODO(gio): sync dodo-flux
22 )
23}
24
25func AddNewEnvTask(env Env, st *state) Task {
26 t := newLeafTask("Commit initial configuration", func() error {
Giorgi Lekveishvili77ee2dc2023-12-11 16:51:10 +040027 ssPublicKeys, err := st.ssClient.GetPublicKeys()
Giorgi Lekveishvili46743d42023-12-10 15:47:23 +040028 if err != nil {
29 return err
30 }
Giorgi Lekveishvili77ee2dc2023-12-11 16:51:10 +040031 repoHost := strings.Split(st.ssClient.Addr, ":")[0]
32 kust, err := st.repo.ReadKustomization("environments/kustomization.yaml")
33 if err != nil {
Giorgi Lekveishvili46743d42023-12-10 15:47:23 +040034 return err
35 }
Giorgi Lekveishvili77ee2dc2023-12-11 16:51:10 +040036 kust.AddResources(env.Name)
37 tmpls, err := template.ParseFS(filesTmpls, "env-tmpl/*.yaml")
38 if err != nil {
39 return err
40 }
41 var knownHosts bytes.Buffer
42 for _, key := range ssPublicKeys {
43 fmt.Fprintf(&knownHosts, "%s %s\n", repoHost, key)
44 }
Giorgi Lekveishvilie009a5d2024-01-05 14:10:11 +040045 for _, tmpl := range tmpls.Templates() { // TODO(gio): migrate to cue
Giorgi Lekveishvili77ee2dc2023-12-11 16:51:10 +040046 dstPath := path.Join("environments", env.Name, tmpl.Name())
47 dst, err := st.repo.Writer(dstPath)
48 if err != nil {
49 return err
50 }
51 defer dst.Close()
52
53 if err := tmpl.Execute(dst, map[string]string{
54 "Name": env.Name,
55 "PrivateKey": base64.StdEncoding.EncodeToString(st.keys.RawPrivateKey()),
56 "PublicKey": base64.StdEncoding.EncodeToString(st.keys.RawAuthorizedKey()),
57 "RepoHost": repoHost,
58 "RepoName": "config",
59 "KnownHosts": base64.StdEncoding.EncodeToString(knownHosts.Bytes()),
60 }); err != nil {
61 return err
62 }
63 }
64 if err := st.repo.WriteKustomization("environments/kustomization.yaml", *kust); err != nil {
65 return err
66 }
67 if err := st.repo.CommitAndPush(fmt.Sprintf("%s: initialize environment", env.Name)); err != nil {
68 return err
69 }
70 return nil
71 })
72 return &t
Giorgi Lekveishvili46743d42023-12-10 15:47:23 +040073}