-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
target.go
209 lines (167 loc) · 5.22 KB
/
target.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
/*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package terraform
import (
"fmt"
"io/ioutil"
"os"
"path"
"strconv"
"strings"
"sync"
"k8s.io/klog/v2"
"k8s.io/kops/pkg/apis/kops"
"k8s.io/kops/pkg/featureflag"
"k8s.io/kops/upup/pkg/fi"
)
type TerraformTarget struct {
Cloud fi.Cloud
Project string
ClusterName string
outDir string
// mutex protects the following items (resources & files)
mutex sync.Mutex
// resources is a list of TF items that should be created
resources []*terraformResource
// outputs is a list of our TF output variables
outputs map[string]*terraformOutputVariable
// files is a map of TF resource files that should be created
files map[string][]byte
// extra config to add to the provider block
clusterSpecTarget *kops.TargetSpec
}
func NewTerraformTarget(cloud fi.Cloud, project string, outDir string, clusterSpecTarget *kops.TargetSpec) *TerraformTarget {
return &TerraformTarget{
Cloud: cloud,
Project: project,
outDir: outDir,
files: make(map[string][]byte),
outputs: make(map[string]*terraformOutputVariable),
clusterSpecTarget: clusterSpecTarget,
}
}
var _ fi.Target = &TerraformTarget{}
type terraformResource struct {
ResourceType string
ResourceName string
Item interface{}
}
type byTypeAndName []*terraformResource
func (a byTypeAndName) Len() int { return len(a) }
func (a byTypeAndName) Less(i, j int) bool {
return a[i].ResourceType+a[i].ResourceName < a[j].ResourceType+a[j].ResourceName
}
func (a byTypeAndName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
type terraformOutputVariable struct {
Key string
Value *Literal
ValueArray []*Literal
}
// A TF name can't have dots in it (if we want to refer to it from a literal),
// so we replace them
func tfSanitize(name string) string {
if _, err := strconv.Atoi(string(name[0])); err == nil {
panic(fmt.Sprintf("Terraform resource names cannot start with a digit. This is a bug in Kops, please report this in a GitHub Issue. Name: %v", name))
}
return strings.NewReplacer(".", "-", "/", "--", ":", "_").Replace(name)
}
func (t *TerraformTarget) AddFile(resourceType string, resourceName string, key string, r fi.Resource, base64 bool) (*Literal, error) {
id := resourceType + "_" + resourceName + "_" + key
d, err := fi.ResourceAsBytes(r)
if err != nil {
return nil, fmt.Errorf("error rending resource %s %v", id, err)
}
t.mutex.Lock()
defer t.mutex.Unlock()
p := path.Join("data", id)
t.files[p] = d
modulePath := path.Join("${path.module}", p)
l := LiteralFileExpression(modulePath, base64)
return l, nil
}
func (t *TerraformTarget) ProcessDeletions() bool {
// Terraform tracks & performs deletions itself
return false
}
func (t *TerraformTarget) RenderResource(resourceType string, resourceName string, e interface{}) error {
res := &terraformResource{
ResourceType: resourceType,
ResourceName: resourceName,
Item: e,
}
t.mutex.Lock()
defer t.mutex.Unlock()
t.resources = append(t.resources, res)
return nil
}
func (t *TerraformTarget) AddOutputVariable(key string, literal *Literal) error {
v := &terraformOutputVariable{
Key: key,
Value: literal,
}
t.mutex.Lock()
defer t.mutex.Unlock()
if t.outputs[key] != nil {
return fmt.Errorf("duplicate variable: %q", key)
}
t.outputs[key] = v
return nil
}
func (t *TerraformTarget) AddOutputVariableArray(key string, literal *Literal) error {
t.mutex.Lock()
defer t.mutex.Unlock()
if t.outputs[key] == nil {
v := &terraformOutputVariable{
Key: key,
}
t.outputs[key] = v
}
if t.outputs[key].Value != nil {
return fmt.Errorf("variable %q is both an array and a scalar", key)
}
t.outputs[key].ValueArray = append(t.outputs[key].ValueArray, literal)
return nil
}
// tfGetProviderExtraConfig is a helper function to get extra config with safety checks on the pointers.
func tfGetProviderExtraConfig(c *kops.TargetSpec) map[string]string {
if c != nil &&
c.Terraform != nil &&
c.Terraform.ProviderExtraConfig != nil {
return *c.Terraform.ProviderExtraConfig
}
return nil
}
func (t *TerraformTarget) Finish(taskMap map[string]fi.Task) error {
var err error
if featureflag.TerraformJSON.Enabled() {
err = t.finishJSON(taskMap)
} else {
err = t.finishHCL2(taskMap)
}
if err != nil {
return err
}
for relativePath, contents := range t.files {
p := path.Join(t.outDir, relativePath)
err = os.MkdirAll(path.Dir(p), os.FileMode(0755))
if err != nil {
return fmt.Errorf("error creating output directory %q: %v", path.Dir(p), err)
}
err = ioutil.WriteFile(p, contents, os.FileMode(0644))
if err != nil {
return fmt.Errorf("error writing terraform data to output file %q: %v", p, err)
}
}
klog.Infof("Terraform output is in %s", t.outDir)
return nil
}