forked from integrations/terraform-provider-github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresource_github_user_gpg_key.go
More file actions
99 lines (81 loc) · 2.39 KB
/
resource_github_user_gpg_key.go
File metadata and controls
99 lines (81 loc) · 2.39 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
package github
import (
"context"
"errors"
"log"
"net/http"
"strconv"
"github.com/google/go-github/v84/github"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func resourceGithubUserGpgKey() *schema.Resource {
return &schema.Resource{
CreateContext: resourceGithubUserGpgKeyCreate,
ReadContext: resourceGithubUserGpgKeyRead,
DeleteContext: 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,
Computed: true,
},
},
}
}
func resourceGithubUserGpgKeyCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
client := meta.(*Owner).v3client
pubKey := d.Get("armored_public_key").(string)
key, _, err := client.Users.CreateGPGKey(ctx, pubKey)
if err != nil {
return diag.FromErr(err)
}
d.SetId(strconv.FormatInt(key.GetID(), 10))
return resourceGithubUserGpgKeyRead(ctx, d, meta)
}
func resourceGithubUserGpgKeyRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
client := meta.(*Owner).v3client
id, err := strconv.ParseInt(d.Id(), 10, 64)
if err != nil {
return diag.FromErr(unconvertibleIdErr(d.Id(), err))
}
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 diag.FromErr(err)
}
if err = d.Set("key_id", key.GetKeyID()); err != nil {
return diag.FromErr(err)
}
return nil
}
func resourceGithubUserGpgKeyDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
client := meta.(*Owner).v3client
id, err := strconv.ParseInt(d.Id(), 10, 64)
if err != nil {
return diag.FromErr(unconvertibleIdErr(d.Id(), err))
}
_, err = client.Users.DeleteGPGKey(ctx, id)
return diag.FromErr(err)
}