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