@@ -58,26 +58,66 @@ func dataSourceCloudstackDomainRead(d *schema.ResourceData, meta interface{}) er
5858
5959 cs := meta .(* cloudstack.CloudStackClient )
6060 p := cs .Domain .NewListDomainsParams ()
61- csDomains , err := cs .Domain .ListDomains (p )
6261
62+ var filterName , filterValue string
63+ var filterByName , filterByID bool
64+
65+ // Apply filters if provided
66+ if filters , filtersOk := d .GetOk ("filter" ); filtersOk {
67+ for _ , f := range filters .(* schema.Set ).List () {
68+ m := f .(map [string ]interface {})
69+ name := m ["name" ].(string )
70+ value := m ["value" ].(string )
71+
72+ switch name {
73+ case "name" :
74+ p .SetName (value )
75+ filterName = value
76+ filterByName = true
77+ log .Printf ("[DEBUG] Filtering by name: %s" , value )
78+ case "id" :
79+ p .SetId (value )
80+ filterValue = value
81+ filterByID = true
82+ log .Printf ("[DEBUG] Filtering by ID: %s" , value )
83+ }
84+ }
85+ }
86+
87+ csDomains , err := cs .Domain .ListDomains (p )
6388 if err != nil {
6489 return fmt .Errorf ("failed to list domains: %s" , err )
6590 }
6691
92+ log .Printf ("[DEBUG] Found %d domains from CloudStack API" , len (csDomains .Domains ))
93+
6794 var domain * cloudstack.Domain
6895
69- for _ , d := range csDomains .Domains {
70- if d .Name == "ROOT" {
71- domain = d
72- break
96+ // If we have results from the API call, select the appropriate domain
97+ if len (csDomains .Domains ) > 0 {
98+ // If we filtered by ID or name through the API, we should have a specific result
99+ if filterByID || filterByName {
100+ // Since we used API filtering, the first result should be our match
101+ domain = csDomains .Domains [0 ]
102+ log .Printf ("[DEBUG] Using API-filtered domain: %s" , domain .Name )
103+ } else {
104+ // If no filters were applied, we need to handle this case
105+ // This shouldn't happen with the current schema as filters are required
106+ return fmt .Errorf ("no filter criteria specified" )
73107 }
74108 }
75109
76110 if domain == nil {
77- return fmt .Errorf ("no domain is matching with the specified name" )
111+ if filterByName {
112+ return fmt .Errorf ("no domain found with name: %s" , filterName )
113+ } else if filterByID {
114+ return fmt .Errorf ("no domain found with ID: %s" , filterValue )
115+ } else {
116+ return fmt .Errorf ("no domain found matching the specified criteria" )
117+ }
78118 }
79119
80- log .Printf ("[DEBUG] Selected domain: %s\n " , domain .Name )
120+ log .Printf ("[DEBUG] Selected domain: %s (ID: %s) " , domain .Name , domain . Id )
81121
82122 return domainDescriptionAttributes (d , domain )
83123}
0 commit comments