github.com/daveadams/terraform@v0.6.4-0.20160830094355-13ce74975936/builtin/providers/mysql/resource_user.go (about) 1 package mysql 2 3 import ( 4 "fmt" 5 "log" 6 7 "github.com/hashicorp/terraform/helper/schema" 8 ) 9 10 func resourceUser() *schema.Resource { 11 return &schema.Resource{ 12 Create: CreateUser, 13 Update: UpdateUser, 14 Read: ReadUser, 15 Delete: DeleteUser, 16 17 Schema: map[string]*schema.Schema{ 18 "user": &schema.Schema{ 19 Type: schema.TypeString, 20 Required: true, 21 ForceNew: true, 22 }, 23 24 "host": &schema.Schema{ 25 Type: schema.TypeString, 26 Optional: true, 27 ForceNew: true, 28 Default: "localhost", 29 }, 30 31 "password": &schema.Schema{ 32 Type: schema.TypeString, 33 Optional: true, 34 Sensitive: true, 35 }, 36 }, 37 } 38 } 39 40 func CreateUser(d *schema.ResourceData, meta interface{}) error { 41 conn := meta.(*providerConfiguration).Conn 42 43 stmtSQL := fmt.Sprintf("CREATE USER '%s'@'%s'", 44 d.Get("user").(string), 45 d.Get("host").(string)) 46 47 password := d.Get("password").(string) 48 if password != "" { 49 stmtSQL = stmtSQL + fmt.Sprintf(" IDENTIFIED BY '%s'", password) 50 } 51 52 log.Println("Executing statement:", stmtSQL) 53 _, _, err := conn.Query(stmtSQL) 54 if err != nil { 55 return err 56 } 57 58 user := fmt.Sprintf("%s@%s", d.Get("user").(string), d.Get("host").(string)) 59 d.SetId(user) 60 61 return nil 62 } 63 64 func UpdateUser(d *schema.ResourceData, meta interface{}) error { 65 conf := meta.(*providerConfiguration) 66 67 if d.HasChange("password") { 68 _, newpw := d.GetChange("password") 69 var stmtSQL string 70 71 /* ALTER USER syntax introduced in MySQL 5.7.6 deprecates SET PASSWORD (GH-8230) */ 72 if conf.VersionMajor > 5 || 73 (conf.VersionMajor == 5 && conf.VersionMinor > 7) || 74 (conf.VersionMajor == 5 && conf.VersionMinor == 7 && conf.VersionPatch >= 6) { 75 stmtSQL = fmt.Sprintf("ALTER USER '%s'@'%s' IDENTIFIED BY '%s'", 76 d.Get("user").(string), 77 d.Get("host").(string), 78 newpw.(string)) 79 } else { 80 stmtSQL = fmt.Sprintf("SET PASSWORD FOR '%s'@'%s' = PASSWORD('%s')", 81 d.Get("user").(string), 82 d.Get("host").(string), 83 newpw.(string)) 84 } 85 86 log.Println("Executing query:", stmtSQL) 87 _, _, err := conf.Conn.Query(stmtSQL) 88 if err != nil { 89 return err 90 } 91 } 92 93 return nil 94 } 95 96 func ReadUser(d *schema.ResourceData, meta interface{}) error { 97 // At this time, all attributes are supplied by the user 98 return nil 99 } 100 101 func DeleteUser(d *schema.ResourceData, meta interface{}) error { 102 conn := meta.(*providerConfiguration).Conn 103 104 stmtSQL := fmt.Sprintf("DROP USER '%s'@'%s'", 105 d.Get("user").(string), 106 d.Get("host").(string)) 107 108 log.Println("Executing statement:", stmtSQL) 109 110 _, _, err := conn.Query(stmtSQL) 111 if err == nil { 112 d.SetId("") 113 } 114 return err 115 }