forked from hashicorp/terraform-provider-azurerm
/
data_source_management_group.go
106 lines (84 loc) · 2.52 KB
/
data_source_management_group.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
package azurerm
import (
"fmt"
"github.com/Azure/azure-sdk-for-go/services/preview/resources/mgmt/2018-03-01-preview/managementgroups"
"github.com/hashicorp/terraform/helper/schema"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)
func dataSourceArmManagementGroup() *schema.Resource {
return &schema.Resource{
Read: dataSourceArmManagementGroupRead,
Schema: map[string]*schema.Schema{
"group_id": {
Type: schema.TypeString,
Required: true,
},
"display_name": {
Type: schema.TypeString,
Computed: true,
},
"parent_management_group_id": {
Type: schema.TypeString,
Computed: true,
},
"subscription_ids": {
Type: schema.TypeSet,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
},
}
}
func dataSourceArmManagementGroupRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).managementGroupsClient
ctx := meta.(*ArmClient).StopContext
groupId := d.Get("group_id").(string)
recurse := true
resp, err := client.Get(ctx, groupId, "children", &recurse, "", managementGroupCacheControl)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
return fmt.Errorf("Management Group %q was not found", groupId)
}
return fmt.Errorf("Error reading Management Group %q: %+v", d.Id(), err)
}
d.SetId(*resp.ID)
d.Set("group_id", groupId)
if props := resp.Properties; props != nil {
d.Set("display_name", props.DisplayName)
subscriptionIds, err := flattenArmManagementGroupDataSourceSubscriptionIds(props.Children)
if err != nil {
return fmt.Errorf("Error flattening `subscription_ids`: %+v", err)
}
d.Set("subscription_ids", subscriptionIds)
parentId := ""
if details := props.Details; details != nil {
if parent := details.Parent; parent != nil {
if pid := parent.ID; pid != nil {
parentId = *pid
}
}
}
d.Set("parent_management_group_id", parentId)
}
return nil
}
func flattenArmManagementGroupDataSourceSubscriptionIds(input *[]managementgroups.ChildInfo) (*schema.Set, error) {
subscriptionIds := &schema.Set{F: schema.HashString}
if input == nil {
return subscriptionIds, nil
}
for _, child := range *input {
if child.ID == nil {
continue
}
id, err := parseManagementGroupSubscriptionID(*child.ID)
if err != nil {
return nil, fmt.Errorf("Unable to parse child subscription ID %+v", err)
}
if id != nil {
subscriptionIds.Add(id.subscriptionId)
}
}
return subscriptionIds, nil
}