/
atlantis_generate_repo_config.go
275 lines (229 loc) 路 8.74 KB
/
atlantis_generate_repo_config.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
package exec
import (
"fmt"
c "github.com/cloudposse/atmos/pkg/config"
u "github.com/cloudposse/atmos/pkg/utils"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"path"
"path/filepath"
"strings"
)
// ExecuteAtlantisGenerateRepoConfigCmd executes `atlantis generate repo-config` command
func ExecuteAtlantisGenerateRepoConfigCmd(cmd *cobra.Command, args []string) error {
flags := cmd.Flags()
outputPath, err := flags.GetString("output-path")
if err != nil {
return err
}
configTemplateName, err := flags.GetString("config-template")
if err != nil {
return err
}
projectTemplateName, err := flags.GetString("project-template")
if err != nil {
return err
}
workflowTemplateName, err := flags.GetString("workflow-template")
if err != nil {
return err
}
stacksCsv, err := flags.GetString("stacks")
if err != nil {
return err
}
var stacks []string
if stacksCsv != "" {
stacks = strings.Split(stacksCsv, ",")
}
componentsCsv, err := flags.GetString("components")
if err != nil {
return err
}
var components []string
if componentsCsv != "" {
components = strings.Split(componentsCsv, ",")
}
return ExecuteAtlantisGenerateRepoConfig(outputPath, configTemplateName, projectTemplateName, workflowTemplateName, stacks, components)
}
// ExecuteAtlantisGenerateRepoConfig generates repository configuration for Atlantis
func ExecuteAtlantisGenerateRepoConfig(
outputPath string,
configTemplateName string,
projectTemplateName string,
workflowTemplateName string,
stacks []string,
components []string) error {
var configAndStacksInfo c.ConfigAndStacksInfo
stacksMap, err := FindStacksMap(configAndStacksInfo, false)
if err != nil {
return err
}
var configTemplate c.AtlantisRepoConfig
var projectTemplate c.AtlantisProjectConfig
var workflowTemplate any
var ok bool
if configTemplate, ok = c.Config.Integrations.Atlantis.ConfigTemplates[configTemplateName]; !ok {
return errors.Errorf("atlantis config template '%s' is not defined in 'integrations.atlantis.config_templates' in atmos.yaml", configTemplateName)
}
if projectTemplate, ok = c.Config.Integrations.Atlantis.ProjectTemplates[projectTemplateName]; !ok {
return errors.Errorf("atlantis project template '%s' is not defined in 'integrations.atlantis.project_templates' in atmos.yaml", projectTemplateName)
}
if workflowTemplate, ok = c.Config.Integrations.Atlantis.WorkflowTemplates[workflowTemplateName]; !ok {
return errors.Errorf("atlantis workflow template '%s' is not defined in 'integrations.atlantis.workflow_templates' in atmos.yaml", workflowTemplateName)
}
var atlantisProjects []c.AtlantisProjectConfig
var componentsSection map[string]any
var terraformSection map[string]any
var componentSection map[string]any
var varsSection map[any]any
// Iterate over all components in all stacks and generate atlantis projects
// Iterate not over the map itself, but over the sorted map keys since Go iterates over maps in random order
stacksMapSortedKeys := u.StringKeysFromMap(stacksMap)
for _, stackConfigFileName := range stacksMapSortedKeys {
stackSection := stacksMap[stackConfigFileName]
if componentsSection, ok = stackSection.(map[any]any)["components"].(map[string]any); !ok {
continue
}
if terraformSection, ok = componentsSection["terraform"].(map[string]any); !ok {
continue
}
// Iterate not over the map itself, but over the sorted map keys since Go iterates over maps in random order
componentMapSortedKeys := u.StringKeysFromMap(terraformSection)
for _, componentName := range componentMapSortedKeys {
compSection := terraformSection[componentName]
if componentSection, ok = compSection.(map[string]any); !ok {
continue
}
// Check if `components` filter is provided
if len(components) == 0 ||
u.SliceContainsString(components, componentName) {
// Component vars
if varsSection, ok = componentSection["vars"].(map[any]any); !ok {
continue
}
// Component metadata
metadataSection := map[any]any{}
if metadataSection, ok = componentSection["metadata"].(map[any]any); ok {
if componentType, ok := metadataSection["type"].(string); ok {
// Don't include abstract components
if componentType == "abstract" {
continue
}
}
}
// Find the terraform component
// If `component` attribute is present, it's the terraform component
// Otherwise, the YAML component name is the terraform component (by default)
terraformComponent := componentName
if componentAttribute, ok := componentSection["component"].(string); ok {
terraformComponent = componentAttribute
}
// Absolute path to the terraform component
terraformComponentPath := path.Join(
c.Config.BasePath,
c.Config.Components.Terraform.BasePath,
terraformComponent,
)
// Context
context := c.GetContextFromVars(varsSection)
context.Component = strings.Replace(componentName, "/", "-", -1)
context.ComponentPath = terraformComponentPath
contextPrefix, err := c.GetContextPrefix(stackConfigFileName, context, c.Config.Stacks.NamePattern, stackConfigFileName)
if err != nil {
return err
}
// Terraform workspace
workspace, err := BuildTerraformWorkspace(
stackConfigFileName,
c.Config.Stacks.NamePattern,
metadataSection,
context,
)
if err != nil {
return err
}
context.Workspace = workspace
// Check if `stacks` filter is provided
if len(stacks) == 0 ||
// `stacks` filter can contain the names of the top-level stack config files:
// atmos terraform generate varfiles --stacks=orgs/cp/tenant1/staging/us-east-2,orgs/cp/tenant2/dev/us-east-2
u.SliceContainsString(stacks, stackConfigFileName) ||
// `stacks` filter can also contain the logical stack names (derived from the context vars):
// atmos terraform generate varfiles --stacks=tenant1-ue2-staging,tenant1-ue2-prod
u.SliceContainsString(stacks, contextPrefix) {
// Generate an atlantis project for the component in the stack
// Replace the context tokens
var whenModified []string
for _, item := range projectTemplate.Autoplan.WhenModified {
processedItem := c.ReplaceContextTokens(context, item)
whenModified = append(whenModified, processedItem)
}
atlantisProjectAutoplanConfig := c.AtlantisProjectAutoplanConfig{
Enabled: projectTemplate.Autoplan.Enabled,
WhenModified: whenModified,
}
atlantisProjectName := c.ReplaceContextTokens(context, projectTemplate.Name)
atlantisProject := c.AtlantisProjectConfig{
Name: atlantisProjectName,
Workspace: c.ReplaceContextTokens(context, projectTemplate.Workspace),
Workflow: workflowTemplateName,
Dir: c.ReplaceContextTokens(context, projectTemplate.Dir),
TerraformVersion: projectTemplate.TerraformVersion,
DeleteSourceBranchOnMerge: projectTemplate.DeleteSourceBranchOnMerge,
Autoplan: atlantisProjectAutoplanConfig,
ApplyRequirements: projectTemplate.ApplyRequirements,
}
atlantisProjects = append(atlantisProjects, atlantisProject)
}
}
}
}
// Workflows
atlantisWorkflows := map[string]any{
workflowTemplateName: workflowTemplate,
}
// Final atlantis config
atlantisYaml := c.AtlantisConfigOutput{}
atlantisYaml.Version = configTemplate.Version
atlantisYaml.Automerge = configTemplate.Automerge
atlantisYaml.DeleteSourceBranchOnMerge = configTemplate.DeleteSourceBranchOnMerge
atlantisYaml.ParallelPlan = configTemplate.ParallelPlan
atlantisYaml.ParallelApply = configTemplate.ParallelApply
atlantisYaml.AllowedRegexpPrefixes = configTemplate.AllowedRegexpPrefixes
atlantisYaml.Projects = atlantisProjects
atlantisYaml.Workflows = atlantisWorkflows
// Write the atlantis config to a file at the specified path
// Check the command line argument `--output-path` first
// Then check the `atlantis.path` setting in `atmos.yaml`
fileName := outputPath
if fileName == "" {
fileName = c.Config.Integrations.Atlantis.Path
u.PrintInfo(fmt.Sprintf("Using 'atlantis.path: %s' from atmos.yaml", fileName))
} else {
u.PrintInfo(fmt.Sprintf("Using '--output-path %s' command-line argument", fileName))
}
// If the path is empty, dump to `stdout`
if fileName != "" {
u.PrintInfo(fmt.Sprintf("Writing atlantis repo config file to '%s'", fileName))
fileAbsolutePath, err := filepath.Abs(fileName)
if err != nil {
return err
}
// Create all the intermediate subdirectories
err = u.EnsureDir(fileAbsolutePath)
if err != nil {
return err
}
err = u.WriteToFileAsYAML(fileAbsolutePath, atlantisYaml, 0644)
if err != nil {
return err
}
} else {
err = u.PrintAsYAML(atlantisYaml)
if err != nil {
return err
}
}
return nil
}