This repository was archived by the owner on Nov 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathtfc_output.go
More file actions
192 lines (182 loc) · 4.78 KB
/
tfc_output.go
File metadata and controls
192 lines (182 loc) · 4.78 KB
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
package workspacehelper
import (
"bytes"
"context"
"fmt"
"sort"
"strings"
"github.com/hashicorp/terraform-k8s/api/v1alpha1"
"github.com/hashicorp/terraform/states/statefile"
"github.com/zclconf/go-cty/cty"
ctyjson "github.com/zclconf/go-cty/cty/json"
)
// GetStateVersionDownloadURL retrieves download URL for state file
func (t *TerraformCloudClient) GetStateVersionDownloadURL(workspaceID string) (string, error) {
stateVersion, err := t.Client.StateVersions.Current(context.TODO(), workspaceID)
if err != nil {
return "", fmt.Errorf("could not get current state version, WorkspaceID, %s, Error, %v", workspaceID, err)
}
return stateVersion.DownloadURL, nil
}
func convertValueToString(val cty.Value) string {
if val.IsNull() {
return "null"
}
ty := val.Type()
switch {
case ty.IsPrimitiveType():
switch ty {
case cty.String:
{
// Special behavior for JSON strings containing array or object
src := []byte(val.AsString())
ty, err := ctyjson.ImpliedType(src)
// check for the special case of "null", which decodes to nil,
// and just allow it to be printed out directly
if err == nil && !ty.IsPrimitiveType() && strings.TrimSpace(val.AsString()) != "null" {
jv, err := ctyjson.Unmarshal(src, ty)
if err != nil {
return ""
}
return convertValueToString(jv)
}
}
return `"` + val.AsString() + `"`
case cty.Bool:
if val.True() {
return "true"
}
return "false"
case cty.Number:
bf := val.AsBigFloat()
return bf.Text('f', -1)
default:
return fmt.Sprintf("%#v", val)
}
case ty.IsListType() || ty.IsSetType() || ty.IsTupleType():
var b bytes.Buffer
i := 0
for it := val.ElementIterator(); it.Next(); {
_, value := it.Element()
b.WriteString(convertValueToString(value))
if i < (val.LengthInt() - 1) {
b.WriteString(",")
}
i++
}
if b.Len() == 0 {
return ""
}
return "[" + b.String() + "]"
case ty.IsMapType():
var b bytes.Buffer
i := 0
valLen := val.LengthInt()
for it := val.ElementIterator(); it.Next(); {
key, value := it.Element()
k := convertValueToString(key)
v := convertValueToString(value)
if k == "" || v == "" {
valLen--
continue
}
b.WriteString(k)
b.WriteString(":")
b.WriteString(v)
if i < (valLen - 1) {
b.WriteString(",")
}
i++
}
if b.Len() == 0 {
return ""
}
return "{" + b.String() + "}"
case ty.IsObjectType():
atys := ty.AttributeTypes()
attrNames := make([]string, 0, len(atys))
nameLen := 0
for attrName := range atys {
attrNames = append(attrNames, attrName)
if len(attrName) > nameLen {
nameLen = len(attrName)
}
}
sort.Strings(attrNames)
var b bytes.Buffer
i := 0
atysLen := len(atys)
for _, attr := range attrNames {
val := val.GetAttr(attr)
v := convertValueToString(val)
if v == "" {
atysLen--
continue
}
b.WriteString(`"`)
b.WriteString(attr)
b.WriteString(`"`)
b.WriteString(":")
b.WriteString(v)
if i < (atysLen - 1) {
b.WriteString(",")
}
i++
}
if b.Len() == 0 {
return ""
}
return "{" + b.String() + "}"
}
return ""
}
// GetOutputsFromState gets list of outputs from state file
func (t *TerraformCloudClient) GetOutputsFromState(stateDownloadURL string) ([]*v1alpha1.OutputStatus, error) {
if stateDownloadURL == "" {
return nil, fmt.Errorf("could not download blank state")
}
data, err := t.Client.StateVersions.Download(context.TODO(), stateDownloadURL)
if err != nil {
return nil, fmt.Errorf("could not download state, Error, %v", err)
}
reader := bytes.NewReader(data)
file, err := statefile.Read(reader)
if err != nil {
return nil, fmt.Errorf("could not read state file, Error, %v", err)
}
outputValues := file.State.Modules[""].OutputValues
outputs := []*v1alpha1.OutputStatus{}
for key, value := range outputValues {
if !value.Sensitive {
if err != nil {
return outputs, fmt.Errorf("output value could not be converted to string, Error, %v", err)
}
statusValue := convertValueToString(value.Value)
if statusValue != "" {
outputs = append(outputs, &v1alpha1.OutputStatus{Key: key, Value: statusValue})
}
}
}
return outputs, nil
}
// CheckOutputs retrieves outputs for a run.
func (t *TerraformCloudClient) CheckOutputs(workspaceID string, runID string) ([]*v1alpha1.OutputStatus, error) {
outputs := []*v1alpha1.OutputStatus{}
if runID == "" {
return outputs, nil
}
stateDownloadURL, err := t.GetStateVersionDownloadURL(workspaceID)
if err != nil {
return outputs, err
}
outputs, err = t.GetOutputsFromState(stateDownloadURL)
if err != nil {
return outputs, err
}
// The outputs don't always return in the same order
// so we're sorting them before we return.
sort.Slice(outputs, func(i, j int) bool {
return outputs[i].Key < outputs[j].Key
})
return outputs, nil
}