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