-
Notifications
You must be signed in to change notification settings - Fork 2
/
redis.go
263 lines (235 loc) · 7.92 KB
/
redis.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
package awsservices
import (
"fmt"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"tenant-terraform-generator/duplosdk"
"tenant-terraform-generator/tf-generator/common"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/hashicorp/hcl/v2/hclwrite"
"github.com/zclconf/go-cty/cty"
)
const REDIS_VAR_PREFIX = "redis_"
type Redis struct {
}
func (r *Redis) Generate(config *common.Config, client *duplosdk.Client) (*common.TFContext, error) {
workingDir := filepath.Join(config.TFCodePath, config.AwsServicesProject)
list, clientErr := client.EcacheInstanceList(config.TenantId)
//Get tenant from duplo
if clientErr != nil {
fmt.Println(clientErr)
return nil, clientErr
}
tfContext := common.TFContext{}
importConfigs := []common.ImportConfig{}
if list != nil {
log.Println("[TRACE] <====== Redis TF generation started. =====>")
kms, kmsClientErr := client.TenantGetTenantKmsKey(config.TenantId)
for _, redis := range *list {
shortName := redis.Identifier[len("duplo-"):len(redis.Identifier)]
resourceName := common.GetResourceName(shortName)
log.Printf("[TRACE] Generating terraform config for duplo Redis Instance : %s", redis.Identifier)
varFullPrefix := REDIS_VAR_PREFIX + resourceName + "_"
inputVars := generateRedisVars(redis, varFullPrefix)
tfContext.InputVars = append(tfContext.InputVars, inputVars...)
// create new empty hcl file object
hclFile := hclwrite.NewEmptyFile()
// create new file on system
path := filepath.Join(workingDir, "redis-"+shortName+".tf")
tfFile, err := os.Create(path)
if err != nil {
fmt.Println(err)
return nil, err
}
// initialize the body of the new file object
rootBody := hclFile.Body()
// Add duplocloud_ecache_instance resource
redisBlock := rootBody.AppendNewBlock("resource",
[]string{"duplocloud_ecache_instance",
resourceName})
redisBody := redisBlock.Body()
redisBody.SetAttributeTraversal("tenant_id", hcl.Traversal{
hcl.TraverseRoot{
Name: "local",
},
hcl.TraverseAttr{
Name: "tenant_id",
},
})
// redisBody.SetAttributeValue("tenant_id",
// cty.StringVal(config.TenantId))
name := shortName + "-${local.tenant_name}"
redisNameTokens := hclwrite.Tokens{
{Type: hclsyntax.TokenOQuote, Bytes: []byte(`"`)},
{Type: hclsyntax.TokenIdent, Bytes: []byte(name)},
{Type: hclsyntax.TokenCQuote, Bytes: []byte(`"`)},
}
// redisBody.SetAttributeValue("name",
// cty.StringVal(shortName+"-"+config.TenantName))
redisBody.SetAttributeRaw("name", redisNameTokens)
redisBody.SetAttributeValue("cache_type",
cty.NumberIntVal(int64(0)))
redisBody.SetAttributeTraversal("replicas", hcl.Traversal{
hcl.TraverseRoot{
Name: "var",
},
hcl.TraverseAttr{
Name: varFullPrefix + "replicas",
},
})
redisBody.SetAttributeTraversal("size", hcl.Traversal{
hcl.TraverseRoot{
Name: "var",
},
hcl.TraverseAttr{
Name: varFullPrefix + "size",
},
})
redisBody.SetAttributeValue("encryption_at_rest",
cty.BoolVal(redis.EncryptionAtRest))
redisBody.SetAttributeValue("encryption_in_transit",
cty.BoolVal(redis.EncryptionInTransit))
if len(redis.AuthToken) > 0 {
redisBody.SetAttributeValue("auth_token",
cty.StringVal(redis.AuthToken))
}
if len(redis.EngineVersion) > 0 {
redisBody.SetAttributeTraversal("engine_version", hcl.Traversal{
hcl.TraverseRoot{
Name: "var",
},
hcl.TraverseAttr{
Name: varFullPrefix + "engine_version",
},
})
lifecycleBody := redisBody.AppendNewBlock("lifecycle", nil).Body()
lifecycle := common.StringSliceToListVal([]string{"engine_version"})
lifecycleBody.SetAttributeValue("ignore_changes", cty.ListVal(lifecycle))
}
if len(redis.ParameterGroupName) > 0 {
redisBody.SetAttributeValue("parameter_group_name",
cty.StringVal(redis.ParameterGroupName))
}
if len(redis.KMSKeyID) > 0 {
if kms != nil && kmsClientErr == nil && (redis.KMSKeyID == kms.KeyArn || redis.KMSKeyID == kms.KeyID) {
redisBody.SetAttributeTraversal("kms_key_id", hcl.Traversal{
hcl.TraverseRoot{
Name: "data.duplocloud_tenant_aws_kms_key.tenant_kms",
},
hcl.TraverseAttr{
Name: "key_id",
},
})
} else {
redisBody.SetAttributeValue("kms_key_id",
cty.StringVal(redis.KMSKeyID))
}
}
if redis.EnableClusterMode {
redisBody.SetAttributeValue("enable_cluster_mode",
cty.BoolVal(redis.EnableClusterMode))
redisBody.SetAttributeValue("number_of_shards", cty.NumberIntVal(int64(redis.NumberOfShards)))
}
//fmt.Printf("%s", hclFile.Bytes())
_, err = tfFile.Write(hclFile.Bytes())
if err != nil {
fmt.Println(err)
return nil, err
}
log.Printf("[TRACE] Terraform config is generated for duplo redis instance : %s", redis.Identifier)
outVars := generateRedisOutputVars(varFullPrefix, resourceName)
tfContext.OutputVars = append(tfContext.OutputVars, outVars...)
// Import all created resources.
if config.GenerateTfState {
importConfigs = append(importConfigs, common.ImportConfig{
ResourceAddress: "duplocloud_ecache_instance." + resourceName,
ResourceId: "v2/subscriptions/" + config.TenantId + "/ECacheDBInstance/" + shortName,
WorkingDir: workingDir,
})
tfContext.ImportConfigs = importConfigs
}
}
log.Println("[TRACE] <====== redis TF generation done. =====>")
}
return &tfContext, nil
}
func generateRedisVars(duplo duplosdk.DuploEcacheInstance, prefix string) []common.VarConfig {
varConfigs := make(map[string]common.VarConfig)
var1 := common.VarConfig{
Name: prefix + "replicas",
DefaultVal: strconv.Itoa(duplo.Replicas),
TypeVal: "number",
}
varConfigs["replicas"] = var1
var2 := common.VarConfig{
Name: prefix + "size",
DefaultVal: duplo.Size,
TypeVal: "string",
}
varConfigs["size"] = var2
ver := duplo.EngineVersion
if duplo.CacheType == 0 {
verSplit := strings.Split(duplo.EngineVersion, ".")
if verSplit[1] == "0" || verSplit[2] == "0" {
ver = verSplit[0] + "." + verSplit[1]
}
}
var3 := common.VarConfig{
Name: prefix + "engine_version",
DefaultVal: ver,
TypeVal: "string",
}
varConfigs["engine_version"] = var3
vars := make([]common.VarConfig, len(varConfigs))
for _, v := range varConfigs {
vars = append(vars, v)
}
return vars
}
func generateRedisOutputVars(prefix, resourceName string) []common.OutputVarConfig {
outVarConfigs := make(map[string]common.OutputVarConfig)
var1 := common.OutputVarConfig{
Name: prefix + "fullname",
ActualVal: "duplocloud_ecache_instance." + resourceName + ".identifier",
DescVal: "The full name of the elasticache instance.",
RootTraversal: true,
}
outVarConfigs["fullname"] = var1
var2 := common.OutputVarConfig{
Name: prefix + "arn",
ActualVal: "duplocloud_ecache_instance." + resourceName + ".arn",
DescVal: "The ARN of the elasticache instance.",
RootTraversal: true,
}
outVarConfigs["arn"] = var2
var3 := common.OutputVarConfig{
Name: prefix + "endpoint",
ActualVal: "duplocloud_ecache_instance." + resourceName + ".endpoint",
DescVal: "The endpoint of the elasticache instance.",
RootTraversal: true,
}
outVarConfigs["endpoint"] = var3
var4 := common.OutputVarConfig{
Name: prefix + "host",
ActualVal: "duplocloud_ecache_instance." + resourceName + ".host",
DescVal: "The DNS hostname of the elasticache instance.",
RootTraversal: true,
}
outVarConfigs["host"] = var4
var5 := common.OutputVarConfig{
Name: prefix + "port",
ActualVal: "duplocloud_ecache_instance." + resourceName + ".port",
DescVal: "The listening port of the elasticache instance.",
RootTraversal: true,
}
outVarConfigs["port"] = var5
outVars := make([]common.OutputVarConfig, len(outVarConfigs))
for _, v := range outVarConfigs {
outVars = append(outVars, v)
}
return outVars
}