github.com/koding/terraform@v0.6.4-0.20170608090606-5d7e0339779d/builtin/providers/gitlab/resource_gitlab_deploy_key.go (about) 1 package gitlab 2 3 import ( 4 "fmt" 5 "log" 6 "strconv" 7 8 "github.com/hashicorp/terraform/helper/schema" 9 gitlab "github.com/xanzy/go-gitlab" 10 ) 11 12 func resourceGitlabDeployKey() *schema.Resource { 13 return &schema.Resource{ 14 Create: resourceGitlabDeployKeyCreate, 15 Read: resourceGitlabDeployKeyRead, 16 Delete: resourceGitlabDeployKeyDelete, 17 18 Schema: map[string]*schema.Schema{ 19 "project": { 20 Type: schema.TypeString, 21 Required: true, 22 ForceNew: true, 23 }, 24 "title": { 25 Type: schema.TypeString, 26 Required: true, 27 ForceNew: true, 28 }, 29 "key": { 30 Type: schema.TypeString, 31 Required: true, 32 ForceNew: true, 33 }, 34 "can_push": { 35 Type: schema.TypeBool, 36 Optional: true, 37 Default: false, 38 ForceNew: true, 39 }, 40 }, 41 } 42 } 43 44 func resourceGitlabDeployKeyCreate(d *schema.ResourceData, meta interface{}) error { 45 client := meta.(*gitlab.Client) 46 project := d.Get("project").(string) 47 options := &gitlab.AddDeployKeyOptions{ 48 Title: gitlab.String(d.Get("title").(string)), 49 Key: gitlab.String(d.Get("key").(string)), 50 CanPush: gitlab.Bool(d.Get("can_push").(bool)), 51 } 52 53 log.Printf("[DEBUG] create gitlab deployment key %s", *options.Title) 54 55 deployKey, _, err := client.DeployKeys.AddDeployKey(project, options) 56 if err != nil { 57 return err 58 } 59 60 d.SetId(fmt.Sprintf("%d", deployKey.ID)) 61 62 return resourceGitlabDeployKeyRead(d, meta) 63 } 64 65 func resourceGitlabDeployKeyRead(d *schema.ResourceData, meta interface{}) error { 66 client := meta.(*gitlab.Client) 67 project := d.Get("project").(string) 68 deployKeyID, err := strconv.Atoi(d.Id()) 69 if err != nil { 70 return err 71 } 72 log.Printf("[DEBUG] read gitlab deploy key %s/%d", project, deployKeyID) 73 74 deployKey, response, err := client.DeployKeys.GetDeployKey(project, deployKeyID) 75 if err != nil { 76 if response.StatusCode == 404 { 77 log.Printf("[WARN] removing deploy key %d from state because it no longer exists in gitlab", deployKeyID) 78 d.SetId("") 79 return nil 80 } 81 82 return err 83 } 84 85 d.Set("title", deployKey.Title) 86 d.Set("key", deployKey.Key) 87 d.Set("can_push", deployKey.CanPush) 88 return nil 89 } 90 91 func resourceGitlabDeployKeyDelete(d *schema.ResourceData, meta interface{}) error { 92 client := meta.(*gitlab.Client) 93 project := d.Get("project").(string) 94 deployKeyID, err := strconv.Atoi(d.Id()) 95 if err != nil { 96 return err 97 } 98 log.Printf("[DEBUG] Delete gitlab deploy key %s", d.Id()) 99 100 response, err := client.DeployKeys.DeleteDeployKey(project, deployKeyID) 101 102 // HTTP 204 is success with no body 103 if response.StatusCode == 204 { 104 return nil 105 } 106 return err 107 }