/
data_source_subscriptions.go
103 lines (86 loc) · 2.69 KB
/
data_source_subscriptions.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
package azurerm
import (
"fmt"
"strings"
"github.com/hashicorp/terraform/helper/schema"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure"
)
func dataSourceArmSubscriptions() *schema.Resource {
return &schema.Resource{
Read: dataSourceArmSubscriptionsRead,
Schema: map[string]*schema.Schema{
"display_name_prefix": {
Type: schema.TypeString,
Optional: true,
},
"display_name_contains": {
Type: schema.TypeString,
Optional: true,
},
"subscriptions": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: azure.SchemaSubscription(false),
},
},
},
}
}
func dataSourceArmSubscriptionsRead(d *schema.ResourceData, meta interface{}) error {
armClient := meta.(*ArmClient)
subClient := armClient.subscriptionsClient
ctx := armClient.StopContext
displayNamePrefix := strings.ToLower(d.Get("display_name_prefix").(string))
displayNameContains := strings.ToLower(d.Get("display_name_contains").(string))
//ListComplete returns an iterator struct
results, err := subClient.ListComplete(ctx)
if err != nil {
return fmt.Errorf("Error listing subscriptions: %+v", err)
}
//iterate across each subscriptions and append them to slice
subscriptions := make([]map[string]interface{}, 0)
for results.NotDone() {
val := results.Value()
s := make(map[string]interface{})
if v := val.SubscriptionID; v != nil {
s["subscription_id"] = *v
}
if v := val.DisplayName; v != nil {
s["display_name"] = *v
}
s["state"] = string(val.State)
if policies := val.SubscriptionPolicies; policies != nil {
if v := policies.LocationPlacementID; v != nil {
s["location_placement_id"] = *v
}
if v := policies.QuotaID; v != nil {
s["quota_id"] = *v
}
s["spending_limit"] = string(policies.SpendingLimit)
}
if err = results.Next(); err != nil {
return fmt.Errorf("Error going to next subscriptions value: %+v", err)
}
//check if the display name prefix matches the given input
if displayNamePrefix != "" {
if !strings.HasPrefix(strings.ToLower(s["display_name"].(string)), displayNamePrefix) {
//the display name does not match the given prefix
continue
}
}
//check if the display name matches the 'contains' comparison
if displayNameContains != "" {
if !strings.Contains(strings.ToLower(s["display_name"].(string)), displayNameContains) {
//the display name does not match the contains check
continue
}
}
subscriptions = append(subscriptions, s)
}
d.SetId("subscriptions-" + armClient.tenantId)
if err = d.Set("subscriptions", subscriptions); err != nil {
return fmt.Errorf("Error setting `subscriptions`: %+v", err)
}
return nil
}