forked from hashicorp/terraform-provider-aws
/
resource_aws_athena_database.go
265 lines (228 loc) · 7.04 KB
/
resource_aws_athena_database.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
package aws
import (
"fmt"
"regexp"
"strings"
"time"
"github.com/hashicorp/terraform/helper/validation"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/athena"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceAwsAthenaDatabase() *schema.Resource {
return &schema.Resource{
Create: resourceAwsAthenaDatabaseCreate,
Read: resourceAwsAthenaDatabaseRead,
Update: resourceAwsAthenaDatabaseUpdate,
Delete: resourceAwsAthenaDatabaseDelete,
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile("^[_a-z0-9]+$"), "see https://docs.aws.amazon.com/athena/latest/ug/tables-databases-columns-names.html"),
},
"bucket": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"force_destroy": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"encryption_configuration": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"kms_key": {
Type: schema.TypeString,
Optional: true,
},
"encryption_option": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
athena.EncryptionOptionCseKms,
athena.EncryptionOptionSseKms,
athena.EncryptionOptionSseS3,
}, false),
},
},
},
},
},
}
}
func expandAthenaResultConfiguration(bucket string, encryptionConfigurationList []interface{}) (*athena.ResultConfiguration, error) {
resultConfig := athena.ResultConfiguration{
OutputLocation: aws.String("s3://" + bucket),
}
if len(encryptionConfigurationList) <= 0 {
return &resultConfig, nil
}
data := encryptionConfigurationList[0].(map[string]interface{})
keyType := data["encryption_option"].(string)
keyID := data["kms_key"].(string)
encryptionConfig := athena.EncryptionConfiguration{
EncryptionOption: aws.String(keyType),
}
if len(keyID) > 0 {
encryptionConfig.KmsKey = aws.String(keyID)
}
resultConfig.EncryptionConfiguration = &encryptionConfig
return &resultConfig, nil
}
func resourceAwsAthenaDatabaseCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).athenaconn
resultConfig, err := expandAthenaResultConfiguration(d.Get("bucket").(string), d.Get("encryption_configuration").([]interface{}))
if err != nil {
return err
}
input := &athena.StartQueryExecutionInput{
QueryString: aws.String(fmt.Sprintf("create database `%s`;", d.Get("name").(string))),
ResultConfiguration: resultConfig,
}
resp, err := conn.StartQueryExecution(input)
if err != nil {
return err
}
if err := executeAndExpectNoRowsWhenCreate(*resp.QueryExecutionId, conn); err != nil {
return err
}
d.SetId(d.Get("name").(string))
return resourceAwsAthenaDatabaseRead(d, meta)
}
func resourceAwsAthenaDatabaseRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).athenaconn
resultConfig, err := expandAthenaResultConfiguration(d.Get("bucket").(string), d.Get("encryption_configuration").([]interface{}))
if err != nil {
return err
}
input := &athena.StartQueryExecutionInput{
QueryString: aws.String(fmt.Sprint("show databases;")),
ResultConfiguration: resultConfig,
}
resp, err := conn.StartQueryExecution(input)
if err != nil {
return err
}
if err := executeAndExpectMatchingRow(*resp.QueryExecutionId, d.Get("name").(string), conn); err != nil {
return err
}
return nil
}
func resourceAwsAthenaDatabaseUpdate(d *schema.ResourceData, meta interface{}) error {
return resourceAwsAthenaDatabaseRead(d, meta)
}
func resourceAwsAthenaDatabaseDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).athenaconn
resultConfig, err := expandAthenaResultConfiguration(d.Get("bucket").(string), d.Get("encryption_configuration").([]interface{}))
if err != nil {
return err
}
name := d.Get("name").(string)
queryString := fmt.Sprintf("drop database `%s`", name)
if d.Get("force_destroy").(bool) {
queryString += " cascade"
}
queryString += ";"
input := &athena.StartQueryExecutionInput{
QueryString: aws.String(queryString),
ResultConfiguration: resultConfig,
}
resp, err := conn.StartQueryExecution(input)
if err != nil {
return err
}
if err := executeAndExpectNoRowsWhenDrop(*resp.QueryExecutionId, conn); err != nil {
return err
}
return nil
}
func executeAndExpectNoRowsWhenCreate(qeid string, conn *athena.Athena) error {
rs, err := queryExecutionResult(qeid, conn)
if err != nil {
return err
}
if len(rs.Rows) != 0 {
return fmt.Errorf("Athena create database, unexpected query result: %s", flattenAthenaResultSet(rs))
}
return nil
}
func executeAndExpectMatchingRow(qeid string, dbName string, conn *athena.Athena) error {
rs, err := queryExecutionResult(qeid, conn)
if err != nil {
return err
}
for _, row := range rs.Rows {
for _, datum := range row.Data {
if *datum.VarCharValue == dbName {
return nil
}
}
}
return fmt.Errorf("Athena not found database: %s, query result: %s", dbName, flattenAthenaResultSet(rs))
}
func executeAndExpectNoRowsWhenDrop(qeid string, conn *athena.Athena) error {
rs, err := queryExecutionResult(qeid, conn)
if err != nil {
return err
}
if len(rs.Rows) != 0 {
return fmt.Errorf("Athena drop database, unexpected query result: %s", flattenAthenaResultSet(rs))
}
return nil
}
func queryExecutionResult(qeid string, conn *athena.Athena) (*athena.ResultSet, error) {
executionStateConf := &resource.StateChangeConf{
Pending: []string{athena.QueryExecutionStateQueued, athena.QueryExecutionStateRunning},
Target: []string{athena.QueryExecutionStateSucceeded},
Refresh: queryExecutionStateRefreshFunc(qeid, conn),
Timeout: 10 * time.Minute,
Delay: 3 * time.Second,
MinTimeout: 3 * time.Second,
}
_, err := executionStateConf.WaitForState()
if err != nil {
return nil, err
}
qrinput := &athena.GetQueryResultsInput{
QueryExecutionId: aws.String(qeid),
}
resp, err := conn.GetQueryResults(qrinput)
if err != nil {
return nil, err
}
return resp.ResultSet, nil
}
func queryExecutionStateRefreshFunc(qeid string, conn *athena.Athena) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
input := &athena.GetQueryExecutionInput{
QueryExecutionId: aws.String(qeid),
}
out, err := conn.GetQueryExecution(input)
if err != nil {
return nil, "failed", err
}
status := out.QueryExecution.Status
if *status.State == athena.QueryExecutionStateFailed &&
status.StateChangeReason != nil {
err = fmt.Errorf("reason: %s", *status.StateChangeReason)
}
return out, *out.QueryExecution.Status.State, err
}
}
func flattenAthenaResultSet(rs *athena.ResultSet) string {
ss := make([]string, 0)
for _, row := range rs.Rows {
for _, datum := range row.Data {
ss = append(ss, *datum.VarCharValue)
}
}
return strings.Join(ss, "\n")
}