-
Notifications
You must be signed in to change notification settings - Fork 950
Expand file tree
/
Copy pathresource_github_user_gpg_key.go
More file actions
109 lines (91 loc) · 2.53 KB
/
resource_github_user_gpg_key.go
File metadata and controls
109 lines (91 loc) · 2.53 KB
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
package github
import (
"context"
"errors"
"log"
"net/http"
"strconv"
"github.com/google/go-github/v82/github"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func resourceGithubUserGpgKey() *schema.Resource {
return &schema.Resource{
Create: resourceGithubUserGpgKeyCreate,
Read: resourceGithubUserGpgKeyRead,
Delete: resourceGithubUserGpgKeyDelete,
Schema: map[string]*schema.Schema{
"armored_public_key": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "Your public GPG key, generated in ASCII-armored format.",
},
"key_id": {
Type: schema.TypeString,
Computed: true,
Description: "The key ID of the GPG key.",
},
"etag": {
Type: schema.TypeString,
Optional: true,
Computed: true,
DiffSuppressFunc: func(k, o, n string, d *schema.ResourceData) bool {
return true
},
DiffSuppressOnRefresh: true,
},
},
}
}
func resourceGithubUserGpgKeyCreate(d *schema.ResourceData, meta any) error {
client := meta.(*Owner).v3client
pubKey := d.Get("armored_public_key").(string)
ctx := context.Background()
key, _, err := client.Users.CreateGPGKey(ctx, pubKey)
if err != nil {
return err
}
d.SetId(strconv.FormatInt(key.GetID(), 10))
return resourceGithubUserGpgKeyRead(d, meta)
}
func resourceGithubUserGpgKeyRead(d *schema.ResourceData, meta any) error {
client := meta.(*Owner).v3client
id, err := strconv.ParseInt(d.Id(), 10, 64)
if err != nil {
return unconvertibleIdErr(d.Id(), err)
}
ctx := context.WithValue(context.Background(), ctxId, d.Id())
if !d.IsNewResource() {
ctx = context.WithValue(ctx, ctxEtag, d.Get("etag").(string))
}
key, _, err := client.Users.GetGPGKey(ctx, id)
if err != nil {
var ghErr *github.ErrorResponse
if errors.As(err, &ghErr) {
if ghErr.Response.StatusCode == http.StatusNotModified {
return nil
}
if ghErr.Response.StatusCode == http.StatusNotFound {
log.Printf("[INFO] Removing user GPG key %s from state because it no longer exists in GitHub",
d.Id())
d.SetId("")
return nil
}
}
return err
}
if err = d.Set("key_id", key.GetKeyID()); err != nil {
return err
}
return nil
}
func resourceGithubUserGpgKeyDelete(d *schema.ResourceData, meta any) error {
client := meta.(*Owner).v3client
id, err := strconv.ParseInt(d.Id(), 10, 64)
if err != nil {
return unconvertibleIdErr(d.Id(), err)
}
ctx := context.WithValue(context.Background(), ctxId, d.Id())
_, err = client.Users.DeleteGPGKey(ctx, id)
return err
}