github.com/vtorhonen/terraform@v0.9.0-beta2.0.20170307220345-5d894e4ffda7/builtin/providers/mysql/resource_grant.go (about) 1 package mysql 2 3 import ( 4 "fmt" 5 "log" 6 "strings" 7 8 "github.com/hashicorp/terraform/helper/schema" 9 ) 10 11 func resourceGrant() *schema.Resource { 12 return &schema.Resource{ 13 Create: CreateGrant, 14 Update: nil, 15 Read: ReadGrant, 16 Delete: DeleteGrant, 17 18 Schema: map[string]*schema.Schema{ 19 "user": &schema.Schema{ 20 Type: schema.TypeString, 21 Required: true, 22 ForceNew: true, 23 }, 24 25 "host": &schema.Schema{ 26 Type: schema.TypeString, 27 Optional: true, 28 ForceNew: true, 29 Default: "localhost", 30 }, 31 32 "database": &schema.Schema{ 33 Type: schema.TypeString, 34 Required: true, 35 ForceNew: true, 36 }, 37 38 "privileges": &schema.Schema{ 39 Type: schema.TypeSet, 40 Required: true, 41 ForceNew: true, 42 Elem: &schema.Schema{Type: schema.TypeString}, 43 Set: schema.HashString, 44 }, 45 46 "grant": &schema.Schema{ 47 Type: schema.TypeBool, 48 Optional: true, 49 ForceNew: true, 50 Default: false, 51 }, 52 }, 53 } 54 } 55 56 func CreateGrant(d *schema.ResourceData, meta interface{}) error { 57 conn := meta.(*providerConfiguration).Conn 58 59 // create a comma-delimited string of privileges 60 var privileges string 61 var privilegesList []string 62 vL := d.Get("privileges").(*schema.Set).List() 63 for _, v := range vL { 64 privilegesList = append(privilegesList, v.(string)) 65 } 66 privileges = strings.Join(privilegesList, ",") 67 68 stmtSQL := fmt.Sprintf("GRANT %s on %s.* TO '%s'@'%s'", 69 privileges, 70 d.Get("database").(string), 71 d.Get("user").(string), 72 d.Get("host").(string)) 73 74 if d.Get("grant").(bool) { 75 stmtSQL = " WITH GRANT OPTION" 76 } 77 78 log.Println("Executing statement:", stmtSQL) 79 _, _, err := conn.Query(stmtSQL) 80 if err != nil { 81 return err 82 } 83 84 user := fmt.Sprintf("%s@%s:%s", d.Get("user").(string), d.Get("host").(string), d.Get("database")) 85 d.SetId(user) 86 87 return ReadGrant(d, meta) 88 } 89 90 func ReadGrant(d *schema.ResourceData, meta interface{}) error { 91 // At this time, all attributes are supplied by the user 92 return nil 93 } 94 95 func DeleteGrant(d *schema.ResourceData, meta interface{}) error { 96 conn := meta.(*providerConfiguration).Conn 97 98 stmtSQL := fmt.Sprintf("REVOKE GRANT OPTION ON %s.* FROM '%s'@'%s'", 99 d.Get("database").(string), 100 d.Get("user").(string), 101 d.Get("host").(string)) 102 103 log.Println("Executing statement:", stmtSQL) 104 _, _, err := conn.Query(stmtSQL) 105 if err != nil { 106 return err 107 } 108 109 stmtSQL = fmt.Sprintf("REVOKE ALL ON %s.* FROM '%s'@'%s'", 110 d.Get("database").(string), 111 d.Get("user").(string), 112 d.Get("host").(string)) 113 114 log.Println("Executing statement:", stmtSQL) 115 _, _, err = conn.Query(stmtSQL) 116 if err != nil { 117 return err 118 } 119 120 return nil 121 }