-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathdata_current_account_user.go
86 lines (69 loc) · 2.38 KB
/
data_current_account_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
package codefresh
import (
"fmt"
"github.com/codefresh-io/terraform-provider-codefresh/codefresh/cfclient"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func dataSourceCurrentAccountUser() *schema.Resource {
return &schema.Resource{
Description: "Returns a user the current Codefresh account by name or email.",
Read: dataSourceCurrentAccountUserRead,
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
ExactlyOneOf: []string{"name", "email"},
Optional: true,
},
"email": {
Type: schema.TypeString,
ExactlyOneOf: []string{"name", "email"},
Optional: true,
},
},
}
}
func dataSourceCurrentAccountUserRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*cfclient.Client)
var currentAccount *cfclient.CurrentAccount
var err error
currentAccount, err = client.GetCurrentAccount()
if err != nil {
return err
}
if currentAccount == nil {
return fmt.Errorf("data.codefresh_current_account - failed to get current_account")
}
var (
userAttributeName string
userAttributeValue string
)
if _email, _emailOk := d.GetOk("email"); _emailOk {
userAttributeName = "email"
userAttributeValue = _email.(string)
} else if _name, _nameOk := d.GetOk("name"); _nameOk {
userAttributeName = "name"
userAttributeValue = _name.(string)
} else {
return fmt.Errorf("data.codefresh_current_account_user - must specify name or email")
}
return mapDataCurrentAccountUserToResource(currentAccount, d, userAttributeName, userAttributeValue)
}
func mapDataCurrentAccountUserToResource(currentAccount *cfclient.CurrentAccount, d *schema.ResourceData, userAttributeName string, userAttributeValue string) error {
if currentAccount == nil || currentAccount.ID == "" {
return fmt.Errorf("data.codefresh_current_account - failed to mapDataCurrentAccountUserToResource no id for current account set")
}
isFound := false
for _, user := range currentAccount.Users {
if (userAttributeName == "name" && user.UserName == userAttributeValue) || (userAttributeName == "email" && user.Email == userAttributeValue) {
isFound = true
d.SetId(user.ID)
d.Set("name", user.UserName)
d.Set("email", user.Email)
break
}
}
if !isFound {
return fmt.Errorf("data.codefresh_current_account_user - cannot find user with %s %s", userAttributeName, userAttributeValue)
}
return nil
}