-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.go
115 lines (91 loc) · 2.5 KB
/
main.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
package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"github.com/rodaine/hclencoder"
"github.com/juliogreff/datadog-to-terraform/pkg/types"
)
const (
ddUrl = "https://api.datadoghq.com"
dashboardResource = "dashboard"
monitorResource = "monitor"
)
func request(method, url string, headers map[string]string) (*http.Response, error) {
client := &http.Client{}
req, err := http.NewRequestWithContext(context.Background(), method, url, nil)
if err != nil {
return nil, err
}
for k, v := range headers {
req.Header.Add(k, v)
}
return client.Do(req)
}
func main() {
args := os.Args[1:]
apiKey := os.Getenv("DD_API_KEY")
appKey := os.Getenv("DD_APP_KEY")
if len(args) != 2 {
fail("usage: dd2hcl [dashboard|monitor] [id]")
}
if len(apiKey) < 1 {
fail("DD_API_KEY environment variable is required but was not set")
}
if len(appKey) < 1 {
fail("DD_APP_KEY environment variable is required but was not set")
}
resourceType := args[0]
resourceId := args[1]
path := fmt.Sprintf("%s/api/v1/%s/%s", ddUrl, resourceType, resourceId)
headers := map[string]string{
"Content-Type": "application/json",
"DD-API-KEY": apiKey,
"DD-APPLICATION-KEY": appKey,
}
resp, err := request(http.MethodGet, path, headers)
if err != nil {
fail("%s %s: unable to get resource: %s", resourceType, resourceId, err)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fail("%s %s: unable to read response body: %s", resourceType, resourceId, err)
}
if resp.StatusCode != http.StatusOK {
fail("%s %s: %s: %s", resourceType, resourceId, resp.Status, body)
}
resource := types.Resource{Name: resourceId}
switch resourceType {
case dashboardResource:
var dashboard *types.Board
err = json.Unmarshal(body, &dashboard)
if err != nil {
fail("%s %s: unable to parse JSON: %s", resourceType, resourceId, err)
}
resource.Type = "datadog_dashboard"
resource.Board = dashboard
case monitorResource:
var monitor *types.Monitor
err = json.Unmarshal(body, &monitor)
if err != nil {
fail("%s %s: unable to parse JSON: %s", resourceType, resourceId, err)
}
resource.Type = "datadog_monitor"
resource.Monitor = monitor
}
hcl, err := hclencoder.Encode(types.ResourceWrapper{
Resource: resource,
})
if err != nil {
fail("%s %s: unable to encode hcl: %s", resourceType, resourceId, err)
}
fmt.Println(string(hcl))
}
func fail(format string, a ...interface{}) {
fmt.Fprintf(os.Stderr, format, a...)
fmt.Fprintln(os.Stderr)
os.Exit(1)
}