This repository has been archived by the owner on May 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpuppetdb.go
61 lines (48 loc) · 1.51 KB
/
puppetdb.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
package autosignr
import (
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/pkg/errors"
)
// PuppetDBNode - Returning from the API call to puppetDB
type PuppetDBNode struct {
Certname string `json:"certname"`
}
// FindInactiveNodes Queries PuppetDB and returns the list of nodes found to be inactive, where
// inactive is the last report timestamp is greater than $hours old
func FindInactiveNodes(hours int, host string, protocol string, uri string, ignoreCertErrors bool, includeFilters []string) ([]string, error) {
t := time.Now().Add(time.Hour * time.Duration(hours*-1)).Format(time.RFC3339)
url := fmt.Sprintf("%s://%s%s", protocol, host, uri)
data := fmt.Sprintf(
"{ \"query\": \"nodes[certname]{ report_timestamp < \\\"%s\\\" %s }\"}",
t,
strings.Join(includeFilters, " "),
)
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: ignoreCertErrors},
}
client := &http.Client{Transport: tr}
var list []string
resp, err := client.Post(url, "application/json", strings.NewReader(data))
if err != nil {
return list, errors.Wrap(err, "Post Error: ")
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return list, errors.New(fmt.Sprintf("Unable to download: %d", resp.StatusCode))
}
body, _ := ioutil.ReadAll(resp.Body)
var l []PuppetDBNode
if err := json.Unmarshal(body, &l); err != nil {
return list, errors.Wrap(err, "Unmarshal Error: ")
}
for _, val := range l {
list = append(list, val.Certname)
}
return list, nil
}