-
Notifications
You must be signed in to change notification settings - Fork 99
/
resource_artifactory_api_key.go
83 lines (65 loc) · 1.73 KB
/
resource_artifactory_api_key.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
package artifactory
import (
"fmt"
"strconv"
"github.com/go-resty/resty/v2"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
type ApiKey struct {
ApiKey string `json:"apiKey"`
}
const apiKeyEndpoint = "artifactory/api/security/apiKey"
func resourceArtifactoryApiKey() *schema.Resource {
return &schema.Resource{
Create: resourceApiKeyCreate,
Read: resourceApiKeyRead,
Delete: apiKeyRevoke,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"api_key": {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
},
},
}
}
func packApiKey(apiKey string, d *schema.ResourceData) error {
setValue := mkLens(d)
errors := setValue("api_key", apiKey)
if errors != nil && len(errors) > 0 {
return fmt.Errorf("failed to pack api key %q", errors)
}
return nil
}
func resourceApiKeyCreate(d *schema.ResourceData, m interface{}) error {
data := make(map[string]string)
_, err := m.(*resty.Client).R().SetResult(&data).Post(apiKeyEndpoint)
if err != nil {
return err
}
if apiKey, ok := data["apiKey"]; ok {
d.SetId(strconv.Itoa(schema.HashString(apiKey)))
return resourceApiKeyRead(d, m)
}
return fmt.Errorf("received no error when creating apikey, but also got no apikey")
}
func resourceApiKeyRead(d *schema.ResourceData, m interface{}) error {
data := make(map[string]string)
_, err := m.(*resty.Client).R().SetResult(&data).Get(apiKeyEndpoint)
if err != nil {
return err
}
key := data["apiKey"]
if key == "" {
d.SetId("")
return nil
}
return packApiKey(key, d)
}
func apiKeyRevoke(_ *schema.ResourceData, m interface{}) error {
_, err := m.(*resty.Client).R().Delete(apiKeyEndpoint)
return err
}