-
Notifications
You must be signed in to change notification settings - Fork 658
/
data_source_ibm_kp_key.go
109 lines (94 loc) · 2.37 KB
/
data_source_ibm_kp_key.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
// Copyright IBM Corp. 2017, 2021 All Rights Reserved.
// Licensed under the Mozilla Public License v2.0
package kms
import (
"context"
"fmt"
"github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns"
kp "github.com/IBM/keyprotect-go-client"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func DataSourceIBMkey() *schema.Resource {
return &schema.Resource{
Read: dataSourceIBMKeyRead,
Schema: map[string]*schema.Schema{
"key_protect_id": {
Type: schema.TypeString,
Required: true,
},
"key_name": {
Type: schema.TypeString,
Optional: true,
},
"keys": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Computed: true,
},
"crn": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"standard_key": {
Type: schema.TypeBool,
Computed: true,
},
},
},
},
},
}
}
func dataSourceIBMKeyRead(d *schema.ResourceData, meta interface{}) error {
api, err := meta.(conns.ClientSession).KeyProtectAPI()
if err != nil {
return err
}
instanceID := d.Get("key_protect_id").(string)
api.Config.InstanceID = instanceID
keys, err := api.GetKeys(context.Background(), 100, 0)
if err != nil {
return fmt.Errorf(
"Get Keys failed with error: %s", err)
}
retreivedKeys := keys.Keys
if len(retreivedKeys) == 0 {
return fmt.Errorf("No keys in instance %s", instanceID)
}
var keyName string
var matchKeys []kp.Key
if v, ok := d.GetOk("key_name"); ok {
keyName = v.(string)
for _, keyData := range retreivedKeys {
if keyData.Name == keyName {
matchKeys = append(matchKeys, keyData)
}
}
} else {
matchKeys = retreivedKeys
}
if len(matchKeys) == 0 {
return fmt.Errorf("No keys with name %s in instance %s", keyName, instanceID)
}
keyMap := make([]map[string]interface{}, 0, len(matchKeys))
for _, key := range matchKeys {
keyInstance := make(map[string]interface{})
keyInstance["id"] = key.ID
keyInstance["name"] = key.Name
keyInstance["crn"] = key.CRN
keyInstance["standard_key"] = key.Extractable
keyMap = append(keyMap, keyInstance)
}
d.SetId(instanceID)
d.Set("keys", keyMap)
d.Set("key_protect_id", instanceID)
return nil
}