forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 7
/
resource_template_dir.go
234 lines (196 loc) · 5.46 KB
/
resource_template_dir.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
package template
import (
"archive/tar"
"bytes"
"crypto/sha1"
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"github.com/hashicorp/terraform/helper/pathorcontents"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceDir() *schema.Resource {
return &schema.Resource{
Create: resourceTemplateDirCreate,
Read: resourceTemplateDirRead,
Delete: resourceTemplateDirDelete,
Schema: map[string]*schema.Schema{
"source_dir": {
Type: schema.TypeString,
Description: "Path to the directory where the files to template reside",
Required: true,
ForceNew: true,
},
"vars": {
Type: schema.TypeMap,
Optional: true,
Default: make(map[string]interface{}),
Description: "Variables to substitute",
ValidateFunc: validateVarsAttribute,
ForceNew: true,
},
"destination_dir": {
Type: schema.TypeString,
Description: "Path to the directory where the templated files will be written",
Required: true,
ForceNew: true,
},
},
}
}
func resourceTemplateDirRead(d *schema.ResourceData, meta interface{}) error {
sourceDir := d.Get("source_dir").(string)
destinationDir := d.Get("destination_dir").(string)
// If the output doesn't exist, mark the resource for creation.
if _, err := os.Stat(destinationDir); os.IsNotExist(err) {
d.SetId("")
return nil
}
// If the combined hash of the input and output directories is different from
// the stored one, mark the resource for re-creation.
//
// The output directory is technically enough for the general case, but by
// hashing the input directory as well, we make development much easier: when
// a developer modifies one of the input files, the generation is
// re-triggered.
hash, err := generateID(sourceDir, destinationDir)
if err != nil {
return err
}
if hash != d.Id() {
d.SetId("")
return nil
}
return nil
}
func resourceTemplateDirCreate(d *schema.ResourceData, meta interface{}) error {
sourceDir := d.Get("source_dir").(string)
destinationDir := d.Get("destination_dir").(string)
vars := d.Get("vars").(map[string]interface{})
// Always delete the output first, otherwise files that got deleted from the
// input directory might still be present in the output afterwards.
if err := resourceTemplateDirDelete(d, meta); err != nil {
return err
}
// Create the destination directory and any other intermediate directories
// leading to it.
if _, err := os.Stat(destinationDir); err != nil {
if err := os.MkdirAll(destinationDir, 0777); err != nil {
return err
}
}
// Recursively crawl the input files/directories and generate the output ones.
err := filepath.Walk(sourceDir, func(p string, f os.FileInfo, err error) error {
if err != nil {
return err
}
if f.IsDir() {
return nil
}
relPath, _ := filepath.Rel(sourceDir, p)
return generateDirFile(p, path.Join(destinationDir, relPath), f, vars)
})
if err != nil {
return err
}
// Compute ID.
hash, err := generateID(sourceDir, destinationDir)
if err != nil {
return err
}
d.SetId(hash)
return nil
}
func resourceTemplateDirDelete(d *schema.ResourceData, _ interface{}) error {
d.SetId("")
destinationDir := d.Get("destination_dir").(string)
if _, err := os.Stat(destinationDir); os.IsNotExist(err) {
return nil
}
if err := os.RemoveAll(destinationDir); err != nil {
return fmt.Errorf("could not delete directory %q: %s", destinationDir, err)
}
return nil
}
func generateDirFile(sourceDir, destinationDir string, f os.FileInfo, vars map[string]interface{}) error {
inputContent, _, err := pathorcontents.Read(sourceDir)
if err != nil {
return err
}
outputContent, err := execute(inputContent, vars)
if err != nil {
return templateRenderError(fmt.Errorf("failed to render %v: %v", sourceDir, err))
}
outputDir := path.Dir(destinationDir)
if _, err := os.Stat(outputDir); err != nil {
if err := os.MkdirAll(outputDir, 0777); err != nil {
return err
}
}
err = ioutil.WriteFile(destinationDir, []byte(outputContent), f.Mode())
if err != nil {
return err
}
return nil
}
func generateID(sourceDir, destinationDir string) (string, error) {
inputHash, err := generateDirHash(sourceDir)
if err != nil {
return "", err
}
outputHash, err := generateDirHash(destinationDir)
if err != nil {
return "", err
}
checksum := sha1.Sum([]byte(inputHash + outputHash))
return hex.EncodeToString(checksum[:]), nil
}
func generateDirHash(directoryPath string) (string, error) {
tarData, err := tarDir(directoryPath)
if err != nil {
return "", fmt.Errorf("could not generate output checksum: %s", err)
}
checksum := sha1.Sum(tarData)
return hex.EncodeToString(checksum[:]), nil
}
func tarDir(directoryPath string) ([]byte, error) {
buf := new(bytes.Buffer)
tw := tar.NewWriter(buf)
writeFile := func(p string, f os.FileInfo, err error) error {
if err != nil {
return err
}
var header *tar.Header
var file *os.File
header, err = tar.FileInfoHeader(f, f.Name())
if err != nil {
return err
}
relPath, _ := filepath.Rel(directoryPath, p)
header.Name = relPath
if err := tw.WriteHeader(header); err != nil {
return err
}
if f.IsDir() {
return nil
}
file, err = os.Open(p)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(tw, file)
return err
}
if err := filepath.Walk(directoryPath, writeFile); err != nil {
return []byte{}, err
}
if err := tw.Flush(); err != nil {
return []byte{}, err
}
return buf.Bytes(), nil
}