|
| 1 | +package provider |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "log" |
| 7 | + "strconv" |
| 8 | + "strings" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" |
| 12 | + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" |
| 13 | + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" |
| 14 | + gitlab "github.com/xanzy/go-gitlab" |
| 15 | +) |
| 16 | + |
| 17 | +var _ = registerResource("gitlab_user_sshkey", func() *schema.Resource { |
| 18 | + return &schema.Resource{ |
| 19 | + Description: `This resource allows to manage GitLab user SSH keys. |
| 20 | +
|
| 21 | +**Upstream API**: [GitLab API docs](https://docs.gitlab.com/ee/api/users.html#single-ssh-key)`, |
| 22 | + |
| 23 | + CreateContext: resourceGitlabUserSSHKeyCreate, |
| 24 | + ReadContext: resourceGitlabUserSSHKeyRead, |
| 25 | + DeleteContext: resourceGitlabUserSSHKeyDelete, |
| 26 | + Importer: &schema.ResourceImporter{ |
| 27 | + StateContext: schema.ImportStatePassthroughContext, |
| 28 | + }, |
| 29 | + |
| 30 | + Schema: map[string]*schema.Schema{ |
| 31 | + "user_id": { |
| 32 | + Description: "The ID of the user to add the ssh key to.", |
| 33 | + Type: schema.TypeInt, |
| 34 | + ForceNew: true, |
| 35 | + Required: true, |
| 36 | + }, |
| 37 | + "title": { |
| 38 | + Description: "The title of the ssh key.", |
| 39 | + Type: schema.TypeString, |
| 40 | + ForceNew: true, |
| 41 | + Required: true, |
| 42 | + }, |
| 43 | + "key": { |
| 44 | + Description: "The ssh key. The SSH key `comment` (trailing part) is optional and ignored for diffing, because GitLab overrides it with the username and GitLab hostname.", |
| 45 | + Type: schema.TypeString, |
| 46 | + ForceNew: true, |
| 47 | + Required: true, |
| 48 | + DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool { |
| 49 | + // NOTE: the ssh keys consist of three parts: `type`, `data`, `comment`, whereas the `comment` is optional |
| 50 | + // and suppressed in the diffing. It's overridden by GitLab with the username and GitLab hostname. |
| 51 | + newParts := strings.SplitN(new, " ", 3) |
| 52 | + oldParts := strings.SplitN(old, " ", 3) |
| 53 | + if len(newParts) < 2 || len(oldParts) < 2 { |
| 54 | + // NOTE: at least one of the keys doesn't have the required two parts, thus we just compare them |
| 55 | + return new == old |
| 56 | + } |
| 57 | + |
| 58 | + // NOTE: both keys have the required two parts, thus we compare the parts separately, ignoring the rest |
| 59 | + return newParts[0] == oldParts[0] && newParts[1] == oldParts[1] |
| 60 | + }, |
| 61 | + }, |
| 62 | + "expires_at": { |
| 63 | + Description: "The expiration date of the SSH key in ISO 8601 format (YYYY-MM-DDTHH:MM:SSZ)", |
| 64 | + Type: schema.TypeString, |
| 65 | + ForceNew: true, |
| 66 | + Optional: true, |
| 67 | + // NOTE: since RFC3339 is pretty much a subset of ISO8601 and actually expected by GitLab, |
| 68 | + // we use it here to avoid having to parse the string ourselves. |
| 69 | + ValidateDiagFunc: validation.ToDiagFunc(validation.IsRFC3339Time), |
| 70 | + }, |
| 71 | + "key_id": { |
| 72 | + Description: "The ID of the ssh key.", |
| 73 | + Type: schema.TypeInt, |
| 74 | + Computed: true, |
| 75 | + }, |
| 76 | + "created_at": { |
| 77 | + Description: "The time when this key was created in GitLab.", |
| 78 | + Type: schema.TypeString, |
| 79 | + Computed: true, |
| 80 | + }, |
| 81 | + }, |
| 82 | + } |
| 83 | +}) |
| 84 | + |
| 85 | +func resourceGitlabUserSSHKeyCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { |
| 86 | + client := meta.(*gitlab.Client) |
| 87 | + userID := d.Get("user_id").(int) |
| 88 | + |
| 89 | + options := &gitlab.AddSSHKeyOptions{ |
| 90 | + Title: gitlab.String(d.Get("title").(string)), |
| 91 | + Key: gitlab.String(d.Get("key").(string)), |
| 92 | + } |
| 93 | + |
| 94 | + if expiresAt, ok := d.GetOk("expires_at"); ok { |
| 95 | + parsedExpiresAt, err := time.Parse(time.RFC3339, expiresAt.(string)) |
| 96 | + if err != nil { |
| 97 | + return diag.Errorf("failed to parse created_at: %s. It must be in valid RFC3339 format.", err) |
| 98 | + } |
| 99 | + gitlabExpiresAt := gitlab.ISOTime(parsedExpiresAt) |
| 100 | + options.ExpiresAt = &gitlabExpiresAt |
| 101 | + } |
| 102 | + |
| 103 | + key, _, err := client.Users.AddSSHKeyForUser(userID, options, gitlab.WithContext(ctx)) |
| 104 | + if err != nil { |
| 105 | + return diag.FromErr(err) |
| 106 | + } |
| 107 | + |
| 108 | + userIDForID := fmt.Sprintf("%d", userID) |
| 109 | + keyIDForID := fmt.Sprintf("%d", key.ID) |
| 110 | + d.SetId(buildTwoPartID(&userIDForID, &keyIDForID)) |
| 111 | + return resourceGitlabUserSSHKeyRead(ctx, d, meta) |
| 112 | +} |
| 113 | + |
| 114 | +func resourceGitlabUserSSHKeyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { |
| 115 | + client := meta.(*gitlab.Client) |
| 116 | + |
| 117 | + userID, keyID, err := resourceGitlabUserSSHKeyParseID(d.Id()) |
| 118 | + if err != nil { |
| 119 | + return diag.Errorf("unable to parse user ssh key resource id: %s: %v", d.Id(), err) |
| 120 | + } |
| 121 | + |
| 122 | + options := &gitlab.ListSSHKeysForUserOptions{ |
| 123 | + Page: 1, |
| 124 | + PerPage: 20, |
| 125 | + } |
| 126 | + |
| 127 | + var key *gitlab.SSHKey |
| 128 | + for options.Page != 0 && key == nil { |
| 129 | + keys, resp, err := client.Users.ListSSHKeysForUser(userID, options, gitlab.WithContext(ctx)) |
| 130 | + if err != nil { |
| 131 | + return diag.FromErr(err) |
| 132 | + } |
| 133 | + |
| 134 | + for _, k := range keys { |
| 135 | + if k.ID == keyID { |
| 136 | + key = k |
| 137 | + break |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + options.Page = resp.NextPage |
| 142 | + } |
| 143 | + |
| 144 | + if key == nil { |
| 145 | + log.Printf("Could not find sshkey %d for user %d", keyID, userID) |
| 146 | + d.SetId("") |
| 147 | + return nil |
| 148 | + } |
| 149 | + |
| 150 | + d.Set("user_id", userID) |
| 151 | + d.Set("key_id", keyID) |
| 152 | + d.Set("title", key.Title) |
| 153 | + d.Set("key", key.Key) |
| 154 | + if key.ExpiresAt != nil { |
| 155 | + d.Set("expires_at", key.ExpiresAt.Format(time.RFC3339)) |
| 156 | + } |
| 157 | + if key.CreatedAt != nil { |
| 158 | + d.Set("created_at", key.CreatedAt.Format(time.RFC3339)) |
| 159 | + } |
| 160 | + return nil |
| 161 | +} |
| 162 | + |
| 163 | +func resourceGitlabUserSSHKeyDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { |
| 164 | + client := meta.(*gitlab.Client) |
| 165 | + |
| 166 | + userID, keyID, err := resourceGitlabUserSSHKeyParseID(d.Id()) |
| 167 | + if err != nil { |
| 168 | + return diag.Errorf("unable to parse user ssh key resource id: %s: %v", d.Id(), err) |
| 169 | + } |
| 170 | + |
| 171 | + if _, err := client.Users.DeleteSSHKeyForUser(userID, keyID, gitlab.WithContext(ctx)); err != nil { |
| 172 | + return diag.FromErr(err) |
| 173 | + } |
| 174 | + |
| 175 | + return nil |
| 176 | +} |
| 177 | + |
| 178 | +func resourceGitlabUserSSHKeyParseID(id string) (int, int, error) { |
| 179 | + userIDFromID, keyIDFromID, err := parseTwoPartID(id) |
| 180 | + if err != nil { |
| 181 | + return 0, 0, err |
| 182 | + } |
| 183 | + userID, err := strconv.Atoi(userIDFromID) |
| 184 | + if err != nil { |
| 185 | + return 0, 0, err |
| 186 | + } |
| 187 | + keyID, err := strconv.Atoi(keyIDFromID) |
| 188 | + if err != nil { |
| 189 | + return 0, 0, err |
| 190 | + } |
| 191 | + |
| 192 | + return userID, keyID, nil |
| 193 | +} |
0 commit comments