-
Notifications
You must be signed in to change notification settings - Fork 75
/
importers.go
79 lines (71 loc) · 2.09 KB
/
importers.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
package common
import (
"context"
"fmt"
"strings"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func ImportAsManaged(_ context.Context, d *schema.ResourceData, _ interface{}) ([]*schema.ResourceData, error) {
_ = d.Set("shared", false)
return []*schema.ResourceData{d}, nil
}
// SetComplexID setting ID from multiple attributes by names
//
// SetComplexID(d, "provider", "protocol")
//
// will set ID from components:
//
// "<provider>/<protocol>"
func SetComplexID(d *schema.ResourceData, attributes ...string) error {
parts := make([]string, len(attributes))
for i, name := range attributes {
v, ok := d.Get(name).(string)
if !ok {
return fmt.Errorf("all ID components must be strings, but %s is not", name)
}
parts[i] = v
}
d.SetId(strings.Join(parts, "/"))
return nil
}
// SetIDComponents setting attributes from complex ID, e.g.:
//
// SetIDComponents(d, "provider", "protocol")
//
// will set fields from ID formatted as
//
// <provider>/<protocol>
func SetIDComponents(d *schema.ResourceData, attributes ...string) error {
id := d.Id()
parts := strings.SplitN(id, "/", len(attributes))
if len(parts) != len(attributes) {
attrsDescription := strings.Join(attributes, "/")
return fmt.Errorf("resource ID should have format %s, but is %s", attrsDescription, id)
}
mErr := &multierror.Error{}
for i, attr := range attributes {
v := parts[i]
if attr == "id" {
d.SetId(v)
continue
}
mErr = multierror.Append(mErr, d.Set(attr, v))
}
return mErr.ErrorOrNil()
}
// ImportByPath can be used to import resource by complex ID
// (e.g. identity protocol by `<provider>/<identity>` or CCE addon by `<cluster_id>/<addon_id>`)
//
// Usage in schema:
//
// StateContext: common.ImportByPath("provider", "protocol"),
func ImportByPath(attributes ...string) schema.StateContextFunc {
return func(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
err := SetIDComponents(d, attributes...)
if err != nil {
return nil, err
}
return schema.ImportStatePassthroughContext(ctx, d, meta)
}
}