/
helmfile.go
286 lines (238 loc) 路 8.87 KB
/
helmfile.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
// https://github.com/roboll/helmfile#cli-reference
package exec
import (
"fmt"
"os"
"path"
"github.com/pkg/errors"
"github.com/spf13/cobra"
tuiUtils "github.com/cloudposse/atmos/internal/tui/utils"
cfg "github.com/cloudposse/atmos/pkg/config"
"github.com/cloudposse/atmos/pkg/schema"
u "github.com/cloudposse/atmos/pkg/utils"
)
// ExecuteHelmfileCmd parses the provided arguments and flags and executes helmfile commands
func ExecuteHelmfileCmd(cmd *cobra.Command, args []string, additionalArgsAndFlags []string) error {
info, err := processCommandLineArgs("helmfile", cmd, args, additionalArgsAndFlags)
if err != nil {
return err
}
return ExecuteHelmfile(info)
}
// ExecuteHelmfile executes helmfile commands
func ExecuteHelmfile(info schema.ConfigAndStacksInfo) error {
cliConfig, err := cfg.InitCliConfig(info, true)
if err != nil {
return err
}
if info.NeedHelp {
return nil
}
// If the user just types `atmos helmfile`, print Atmos logo and show helmfile help
if info.SubCommand == "" {
fmt.Println()
err = tuiUtils.PrintStyledText("ATMOS")
if err != nil {
return err
}
err = processHelp("helmfile", "")
if err != nil {
return err
}
fmt.Println()
return nil
}
info, err = ProcessStacks(cliConfig, info, true)
if err != nil {
return err
}
if len(info.Stack) < 1 {
return errors.New("stack must be specified")
}
err = checkHelmfileConfig(cliConfig)
if err != nil {
return err
}
// Check if the component exists as a helmfile component
componentPath := path.Join(cliConfig.HelmfileDirAbsolutePath, info.ComponentFolderPrefix, info.FinalComponent)
componentPathExists, err := u.IsDirectory(componentPath)
if err != nil || !componentPathExists {
return fmt.Errorf("'%s' points to the Helmfile component '%s', but it does not exist in '%s'",
info.ComponentFromArg,
info.FinalComponent,
path.Join(cliConfig.Components.Helmfile.BasePath, info.ComponentFolderPrefix),
)
}
// Check if the component is allowed to be provisioned (`metadata.type` attribute)
if (info.SubCommand == "sync" || info.SubCommand == "apply" || info.SubCommand == "deploy") && info.ComponentIsAbstract {
return fmt.Errorf("abstract component '%s' cannot be provisioned since it's explicitly prohibited from being deployed "+
"by 'metadata.type: abstract' attribute", path.Join(info.ComponentFolderPrefix, info.Component))
}
// Print component variables
u.LogDebug(cliConfig, fmt.Sprintf("\nVariables for the component '%s' in the stack '%s':", info.ComponentFromArg, info.Stack))
if cliConfig.Logs.Level == u.LogLevelTrace || cliConfig.Logs.Level == u.LogLevelDebug {
err = u.PrintAsYAML(info.ComponentVarsSection)
if err != nil {
return err
}
}
// Check if component 'settings.validation' section is specified and validate the component
valid, err := ValidateComponent(cliConfig, info.ComponentFromArg, info.ComponentSection, "", "", nil, 0)
if err != nil {
return err
}
if !valid {
return fmt.Errorf("\nComponent '%s' did not pass the validation policies.\n", info.ComponentFromArg)
}
// Write variables to a file
varFile := constructHelmfileComponentVarfileName(info)
varFilePath := constructHelmfileComponentVarfilePath(cliConfig, info)
u.LogDebug(cliConfig, "Writing the variables to file:")
u.LogDebug(cliConfig, varFilePath)
if !info.DryRun {
err = u.WriteToFileAsYAML(varFilePath, info.ComponentVarsSection, 0644)
if err != nil {
return err
}
}
// Handle `helmfile deploy` custom command
if info.SubCommand == "deploy" {
info.SubCommand = "sync"
}
context := cfg.GetContextFromVars(info.ComponentVarsSection)
envVarsEKS := []string{}
if cliConfig.Components.Helmfile.UseEKS {
// Prepare AWS profile
helmAwsProfile := cfg.ReplaceContextTokens(context, cliConfig.Components.Helmfile.HelmAwsProfilePattern)
u.LogDebug(cliConfig, fmt.Sprintf("\nUsing AWS_PROFILE=%s\n\n", helmAwsProfile))
// Download kubeconfig by running `aws eks update-kubeconfig`
kubeconfigPath := fmt.Sprintf("%s/%s-kubecfg", cliConfig.Components.Helmfile.KubeconfigPath, info.ContextPrefix)
clusterName := cfg.ReplaceContextTokens(context, cliConfig.Components.Helmfile.ClusterNamePattern)
u.LogDebug(cliConfig, fmt.Sprintf("Downloading kubeconfig from the cluster '%s' and saving it to %s\n\n", clusterName, kubeconfigPath))
err = ExecuteShellCommand(
cliConfig,
"aws",
[]string{
"--profile",
helmAwsProfile,
"eks",
"update-kubeconfig",
fmt.Sprintf("--name=%s", clusterName),
fmt.Sprintf("--region=%s", context.Region),
fmt.Sprintf("--kubeconfig=%s", kubeconfigPath),
},
componentPath,
nil,
info.DryRun,
info.RedirectStdErr,
)
if err != nil {
return err
}
envVarsEKS = append(envVarsEKS, []string{
fmt.Sprintf("AWS_PROFILE=%s", helmAwsProfile),
fmt.Sprintf("KUBECONFIG=%s", kubeconfigPath),
}...)
}
// Print command info
u.LogDebug(cliConfig, "\nCommand info:")
u.LogDebug(cliConfig, "Helmfile binary: "+info.Command)
u.LogDebug(cliConfig, "Helmfile command: "+info.SubCommand)
// https://github.com/roboll/helmfile#cli-reference
// atmos helmfile diff echo-server -s tenant1-ue2-dev --global-options "--no-color --namespace=test"
// atmos helmfile diff echo-server -s tenant1-ue2-dev --global-options "--no-color --namespace test"
// atmos helmfile diff echo-server -s tenant1-ue2-dev --global-options="--no-color --namespace=test"
// atmos helmfile diff echo-server -s tenant1-ue2-dev --global-options="--no-color --namespace test"
u.LogDebug(cliConfig, fmt.Sprintf("Global options: %v", info.GlobalOptions))
u.LogDebug(cliConfig, fmt.Sprintf("Arguments and flags: %v", info.AdditionalArgsAndFlags))
u.LogDebug(cliConfig, "Component: "+info.ComponentFromArg)
if len(info.BaseComponent) > 0 {
u.LogDebug(cliConfig, "Helmfile component: "+info.BaseComponent)
}
if info.Stack == info.StackFromArg {
u.LogDebug(cliConfig, "Stack: "+info.StackFromArg)
} else {
u.LogDebug(cliConfig, "Stack: "+info.StackFromArg)
u.LogDebug(cliConfig, "Stack path: "+path.Join(cliConfig.BasePath, cliConfig.Stacks.BasePath, info.Stack))
}
workingDir := constructHelmfileComponentWorkingDir(cliConfig, info)
u.LogDebug(cliConfig, fmt.Sprintf("Working dir: %s\n\n", workingDir))
// Prepare arguments and flags
allArgsAndFlags := []string{"--state-values-file", varFile}
if info.GlobalOptions != nil && len(info.GlobalOptions) > 0 {
allArgsAndFlags = append(allArgsAndFlags, info.GlobalOptions...)
}
allArgsAndFlags = append(allArgsAndFlags, info.SubCommand)
allArgsAndFlags = append(allArgsAndFlags, info.AdditionalArgsAndFlags...)
// Prepare ENV vars
envVars := append(info.ComponentEnvList, []string{
fmt.Sprintf("STACK=%s", info.Stack),
}...)
// Append the context ENV vars (first check if they are not set by the caller)
env := os.Getenv("NAMESPACE")
if env == "" {
envVars = append(envVars, fmt.Sprintf("NAMESPACE=%s", context.Namespace))
}
env = os.Getenv("TENANT")
if env == "" {
envVars = append(envVars, fmt.Sprintf("TENANT=%s", context.Tenant))
}
env = os.Getenv("ENVIRONMENT")
if env == "" {
envVars = append(envVars, fmt.Sprintf("ENVIRONMENT=%s", context.Environment))
}
env = os.Getenv("STAGE")
if env == "" {
envVars = append(envVars, fmt.Sprintf("STAGE=%s", context.Stage))
}
env = os.Getenv("REGION")
if env == "" {
envVars = append(envVars, fmt.Sprintf("REGION=%s", context.Region))
}
if cliConfig.Components.Helmfile.UseEKS {
envVars = append(envVars, envVarsEKS...)
}
u.LogTrace(cliConfig, "Using ENV vars:")
for _, v := range envVars {
u.LogTrace(cliConfig, v)
}
err = ExecuteShellCommand(
cliConfig,
info.Command,
allArgsAndFlags,
componentPath,
envVars,
info.DryRun,
info.RedirectStdErr,
)
if err != nil {
return err
}
// Cleanup
err = os.Remove(varFilePath)
if err != nil {
u.LogWarning(cliConfig, err.Error())
}
return nil
}
func checkHelmfileConfig(cliConfig schema.CliConfiguration) error {
if len(cliConfig.Components.Helmfile.BasePath) < 1 {
return errors.New("Base path to helmfile components must be provided in 'components.helmfile.base_path' config or " +
"'ATMOS_COMPONENTS_HELMFILE_BASE_PATH' ENV variable")
}
if cliConfig.Components.Helmfile.UseEKS {
if len(cliConfig.Components.Helmfile.KubeconfigPath) < 1 {
return errors.New("Kubeconfig path must be provided in 'components.helmfile.kubeconfig_path' config or " +
"'ATMOS_COMPONENTS_HELMFILE_KUBECONFIG_PATH' ENV variable")
}
if len(cliConfig.Components.Helmfile.HelmAwsProfilePattern) < 1 {
return errors.New("Helm AWS profile pattern must be provided in 'components.helmfile.helm_aws_profile_pattern' config or " +
"'ATMOS_COMPONENTS_HELMFILE_HELM_AWS_PROFILE_PATTERN' ENV variable")
}
if len(cliConfig.Components.Helmfile.ClusterNamePattern) < 1 {
return errors.New("Cluster name pattern must be provided in 'components.helmfile.cluster_name_pattern' config or " +
"'ATMOS_COMPONENTS_HELMFILE_CLUSTER_NAME_PATTERN' ENV variable")
}
}
return nil
}