Skip to content

Commit

Permalink
Add mysql_user importer
Browse files Browse the repository at this point in the history
  • Loading branch information
winebarrel committed Feb 20, 2020
1 parent 74708bb commit 4f14e3f
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions mysql/resource_user.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package mysql
import (
"fmt"
"log"
"strings"

"errors"

Expand All @@ -16,6 +17,9 @@ func resourceUser() *schema.Resource {
Update: UpdateUser,
Read: ReadUser,
Delete: DeleteUser,
Importer: &schema.ResourceImporter{
State: ImportUser,
},

Schema: map[string]*schema.Schema{
"user": {
Expand Down Expand Up @@ -246,3 +250,36 @@ func DeleteUser(d *schema.ResourceData, meta interface{}) error {
}
return err
}

func ImportUser(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
userHost := strings.SplitN(d.Id(), "@", 2)
user := userHost[0]
host := "localhost"

if len(userHost) == 2 {
host = userHost[1]
}

db, err := connectToMySQL(meta.(*MySQLConfiguration))

if err != nil {
return nil, err
}

var count int
err = db.QueryRow("SELECT COUNT(1) FROM mysql.user WHERE user = ? AND host = ?", user, host).Scan(&count)

if err != nil {
return nil, err
}

if count == 0 {
return nil, fmt.Errorf("user '%s' not found", d.Id())
}

d.Set("user", user)
d.Set("host", host)
d.Set("tls_option", "NONE")

return []*schema.ResourceData{d}, nil
}

0 comments on commit 4f14e3f

Please sign in to comment.