Skip to content

Commit afa7a18

Browse files
ianc769CopilotsureshanapartiPearl1594dependabot[bot]
authored
Add cloudstack_project resource (#167)
* Add CloudStack project resource * Add test for empty display_text defaulting to name value * Uncomment and implement tests for accountid and userid in project resource * Minor README Fix * Update display_text to required for API compatibility and adjust documentation * Clean up tests for 4.20.1.0 * fix: include domain ID when looking up projects by ID Fix issue where getProjectByID() would always return "id not found" while getProjectByName() could find the same project. CloudStack projects are only unique within a domain context, so we now include domain ID in lookups. - Modified getProjectByID() to accept optional domain parameter - Updated all calls to include domain when available - Updated test functions accordingly - Updated documentation to clarify domain requirement for project imports * feat: add cloudstack_project data source and corresponding tests * remove rogue testing script * Update cloudstack/resource_cloudstack_project.go Co-authored-by: Copilot <[email protected]> * adding domain validation to ensure projects are only reused within the intended scope Co-authored-by: Copilot <[email protected]> * Updated cloudstack go sdk to v2.17.1 (#193) * Fix creation of firewall & Egress firewall rules when created in a project * chore(deps): bump github.com/cloudflare/circl from 1.3.7 to 1.6.1 Bumps [github.com/cloudflare/circl](https://github.com/cloudflare/circl) from 1.3.7 to 1.6.1. - [Release notes](https://github.com/cloudflare/circl/releases) - [Commits](cloudflare/circl@v1.3.7...v1.6.1) --- updated-dependencies: - dependency-name: github.com/cloudflare/circl dependency-version: 1.6.1 dependency-type: indirect ... Signed-off-by: dependabot[bot] <[email protected]> * resolve retrieveError issue * Update cloudstack/resource_cloudstack_project.go Co-authored-by: Copilot <[email protected]> * Update cloudstack/resource_cloudstack_project.go Co-authored-by: Copilot <[email protected]> * Change display_text field from required to optional in resourceCloudStackProject * Pin github actions version for opentofu * rat + excludes and add licenses to other files (#200) * readme: add specific test instruction in readme (#211) Add instructions for specific test execution * data: get vpc in project by project name (#209) * Support additional parameters for cloudstack_nic resource (#210) * serviceoffering: add params for custom offering, storage tags, encryptroot (#212) * Support desc and ruleId in create_network_acl_rule * fix review comment * change rule_id -> rule_number and add doc * add params in unit tests * verify description and rule_number in unit test * use fields defined in schema * fix test verification sequence * handle review comments * Add support for additional optional parameters for creating network offerings (#205) * Add disk_offering & override_disk_offering to instance resource * Update website/docs/r/instance.html.markdown Co-authored-by: Copilot <[email protected]> * Allow specifying private end port & public end port for port forward rules * Update tests * Add `cloudstack_physicalnetwork` and some underlying additional resources (#201) * feat: add cidrlist parameter to loadbalancer rule (#147) * feat: add cloudstack_project resource to provider * fix: update display_text to displaytext in project resource and tests. fix: update lookup to use getAccountNameByID helper function * fix: rename display_text to displaytext in project resource and tests --------- Signed-off-by: dependabot[bot] <[email protected]> Co-authored-by: Copilot <[email protected]> Co-authored-by: Suresh Kumar Anaparti <[email protected]> Co-authored-by: Pearl Dsilva <[email protected]> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: vishesh92 <[email protected]> Co-authored-by: dahn <[email protected]> Co-authored-by: Manoj Kumar <[email protected]> Co-authored-by: Wei Zhou <[email protected]> Co-authored-by: Abhishek Kumar <[email protected]> Co-authored-by: ABW <[email protected]>
1 parent 5191290 commit afa7a18

10 files changed

+1609
-2
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ When Docker started the container you can go to http://localhost:8080/client and
142142
Once the login page is shown and you can login, you need to provision a simulated data-center:
143143

144144
```sh
145-
docker exec -it cloudstack-simulator python /root/tools/marvin/marvin/deployDataCenter.py -i /root/setup/dev/advanced.cfg
145+
docker exec -it simulator python /root/tools/marvin/marvin/deployDataCenter.py -i /root/setup/dev/advanced.cfg
146146
```
147147

148148
If you refresh the client or login again, you will now get passed the initial welcome screen and be able to go to your account details and retrieve the API key and secret. Export those together with the URL:
@@ -206,7 +206,7 @@ Check and ensure TF provider passes builds, GA and run this for local checks:
206206
goreleaser release --snapshot --clean
207207
```
208208

209-
Next, create a personalised Github token: https://github.com/settings/tokens/new?scopes=repo,write:packages
209+
Next, create a personalised Github token: https://github.com/settings/tokens/new?scopes=repo,write:packages
210210

211211
```
212212
export GITHUB_TOKEN="YOUR_GH_TOKEN"
Lines changed: 215 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,215 @@
1+
//
2+
// Licensed to the Apache Software Foundation (ASF) under one
3+
// or more contributor license agreements. See the NOTICE file
4+
// distributed with this work for additional information
5+
// regarding copyright ownership. The ASF licenses this file
6+
// to you under the Apache License, Version 2.0 (the
7+
// "License"); you may not use this file except in compliance
8+
// with the License. You may obtain a copy of the License at
9+
//
10+
// http://www.apache.org/licenses/LICENSE-2.0
11+
//
12+
// Unless required by applicable law or agreed to in writing,
13+
// software distributed under the License is distributed on an
14+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
// KIND, either express or implied. See the License for the
16+
// specific language governing permissions and limitations
17+
// under the License.
18+
//
19+
20+
package cloudstack
21+
22+
import (
23+
"encoding/json"
24+
"fmt"
25+
"log"
26+
"regexp"
27+
"strings"
28+
"time"
29+
30+
"github.com/apache/cloudstack-go/v2/cloudstack"
31+
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
32+
)
33+
34+
func dataSourceCloudstackProject() *schema.Resource {
35+
return &schema.Resource{
36+
Read: datasourceCloudStackProjectRead,
37+
Schema: map[string]*schema.Schema{
38+
"filter": dataSourceFiltersSchema(),
39+
40+
// Computed values
41+
"name": {
42+
Type: schema.TypeString,
43+
Computed: true,
44+
},
45+
46+
"displaytext": {
47+
Type: schema.TypeString,
48+
Computed: true,
49+
},
50+
51+
"domain": {
52+
Type: schema.TypeString,
53+
Computed: true,
54+
},
55+
56+
"account": {
57+
Type: schema.TypeString,
58+
Computed: true,
59+
},
60+
61+
"state": {
62+
Type: schema.TypeString,
63+
Computed: true,
64+
},
65+
66+
"tags": tagsSchema(),
67+
},
68+
}
69+
}
70+
71+
func datasourceCloudStackProjectRead(d *schema.ResourceData, meta interface{}) error {
72+
cs := meta.(*cloudstack.CloudStackClient)
73+
p := cs.Project.NewListProjectsParams()
74+
csProjects, err := cs.Project.ListProjects(p)
75+
76+
if err != nil {
77+
return fmt.Errorf("failed to list projects: %s", err)
78+
}
79+
80+
filters := d.Get("filter")
81+
var projects []*cloudstack.Project
82+
83+
for _, v := range csProjects.Projects {
84+
match, err := applyProjectFilters(v, filters.(*schema.Set))
85+
if err != nil {
86+
return err
87+
}
88+
if match {
89+
projects = append(projects, v)
90+
}
91+
}
92+
93+
if len(projects) == 0 {
94+
return fmt.Errorf("no project matches the specified filters")
95+
}
96+
97+
// Return the latest project from the list of filtered projects according
98+
// to its creation date
99+
project, err := latestProject(projects)
100+
if err != nil {
101+
return err
102+
}
103+
log.Printf("[DEBUG] Selected project: %s\n", project.Name)
104+
105+
return projectDescriptionAttributes(d, project)
106+
}
107+
108+
func projectDescriptionAttributes(d *schema.ResourceData, project *cloudstack.Project) error {
109+
d.SetId(project.Id)
110+
d.Set("name", project.Name)
111+
d.Set("displaytext", project.Displaytext)
112+
d.Set("domain", project.Domain)
113+
d.Set("state", project.State)
114+
115+
// Handle account information safely
116+
if len(project.Owner) > 0 {
117+
for _, owner := range project.Owner {
118+
if account, ok := owner["account"]; ok {
119+
d.Set("account", account)
120+
break
121+
}
122+
}
123+
}
124+
125+
d.Set("tags", tagsToMap(project.Tags))
126+
127+
return nil
128+
}
129+
130+
func latestProject(projects []*cloudstack.Project) (*cloudstack.Project, error) {
131+
var latest time.Time
132+
var project *cloudstack.Project
133+
134+
for _, v := range projects {
135+
created, err := time.Parse("2006-01-02T15:04:05-0700", v.Created)
136+
if err != nil {
137+
return nil, fmt.Errorf("failed to parse creation date of a project: %s", err)
138+
}
139+
140+
if created.After(latest) {
141+
latest = created
142+
project = v
143+
}
144+
}
145+
146+
return project, nil
147+
}
148+
149+
func applyProjectFilters(project *cloudstack.Project, filters *schema.Set) (bool, error) {
150+
var projectJSON map[string]interface{}
151+
k, _ := json.Marshal(project)
152+
err := json.Unmarshal(k, &projectJSON)
153+
if err != nil {
154+
return false, err
155+
}
156+
157+
for _, f := range filters.List() {
158+
m := f.(map[string]interface{})
159+
r, err := regexp.Compile(m["value"].(string))
160+
if err != nil {
161+
return false, fmt.Errorf("invalid regex: %s", err)
162+
}
163+
164+
// Handle special case for owner/account
165+
if m["name"].(string) == "account" {
166+
if len(project.Owner) == 0 {
167+
return false, nil
168+
}
169+
170+
found := false
171+
for _, owner := range project.Owner {
172+
if account, ok := owner["account"]; ok {
173+
if r.MatchString(fmt.Sprintf("%v", account)) {
174+
found = true
175+
break
176+
}
177+
}
178+
}
179+
180+
if !found {
181+
return false, nil
182+
}
183+
continue
184+
}
185+
186+
updatedName := strings.ReplaceAll(m["name"].(string), "_", "")
187+
188+
// Handle fields that might not exist in the JSON
189+
fieldValue, exists := projectJSON[updatedName]
190+
if !exists {
191+
return false, nil
192+
}
193+
194+
// Handle different types of fields
195+
switch v := fieldValue.(type) {
196+
case string:
197+
if !r.MatchString(v) {
198+
return false, nil
199+
}
200+
case float64:
201+
if !r.MatchString(fmt.Sprintf("%v", v)) {
202+
return false, nil
203+
}
204+
case bool:
205+
if !r.MatchString(fmt.Sprintf("%v", v)) {
206+
return false, nil
207+
}
208+
default:
209+
// Skip fields that aren't simple types
210+
continue
211+
}
212+
}
213+
214+
return true, nil
215+
}
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
//
2+
// Licensed to the Apache Software Foundation (ASF) under one
3+
// or more contributor license agreements. See the NOTICE file
4+
// distributed with this work for additional information
5+
// regarding copyright ownership. The ASF licenses this file
6+
// to you under the Apache License, Version 2.0 (the
7+
// "License"); you may not use this file except in compliance
8+
// with the License. You may obtain a copy of the License at
9+
//
10+
// http://www.apache.org/licenses/LICENSE-2.0
11+
//
12+
// Unless required by applicable law or agreed to in writing,
13+
// software distributed under the License is distributed on an
14+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
// KIND, either express or implied. See the License for the
16+
// specific language governing permissions and limitations
17+
// under the License.
18+
//
19+
20+
package cloudstack
21+
22+
import (
23+
"testing"
24+
25+
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
26+
)
27+
28+
func TestAccProjectDataSource_basic(t *testing.T) {
29+
resourceName := "cloudstack_project.project-resource"
30+
datasourceName := "data.cloudstack_project.project-data-source"
31+
32+
resource.Test(t, resource.TestCase{
33+
PreCheck: func() { testAccPreCheck(t) },
34+
Providers: testAccProviders,
35+
Steps: []resource.TestStep{
36+
{
37+
Config: testProjectDataSourceConfig_basic,
38+
Check: resource.ComposeTestCheckFunc(
39+
resource.TestCheckResourceAttrPair(datasourceName, "name", resourceName, "name"),
40+
resource.TestCheckResourceAttrPair(datasourceName, "displaytext", resourceName, "displaytext"),
41+
resource.TestCheckResourceAttrPair(datasourceName, "domain", resourceName, "domain"),
42+
),
43+
},
44+
},
45+
})
46+
}
47+
48+
func TestAccProjectDataSource_withAccount(t *testing.T) {
49+
resourceName := "cloudstack_project.project-account-resource"
50+
datasourceName := "data.cloudstack_project.project-account-data-source"
51+
52+
resource.Test(t, resource.TestCase{
53+
PreCheck: func() { testAccPreCheck(t) },
54+
Providers: testAccProviders,
55+
Steps: []resource.TestStep{
56+
{
57+
Config: testProjectDataSourceConfig_withAccount,
58+
Check: resource.ComposeTestCheckFunc(
59+
resource.TestCheckResourceAttrPair(datasourceName, "name", resourceName, "name"),
60+
resource.TestCheckResourceAttrPair(datasourceName, "displaytext", resourceName, "displaytext"),
61+
resource.TestCheckResourceAttrPair(datasourceName, "domain", resourceName, "domain"),
62+
resource.TestCheckResourceAttrPair(datasourceName, "account", resourceName, "account"),
63+
),
64+
},
65+
},
66+
})
67+
}
68+
69+
const testProjectDataSourceConfig_basic = `
70+
resource "cloudstack_project" "project-resource" {
71+
name = "test-project-datasource"
72+
displaytext = "Test Project for Data Source"
73+
}
74+
75+
data "cloudstack_project" "project-data-source" {
76+
filter {
77+
name = "name"
78+
value = "test-project-datasource"
79+
}
80+
depends_on = [
81+
cloudstack_project.project-resource
82+
]
83+
}
84+
85+
output "project-output" {
86+
value = data.cloudstack_project.project-data-source
87+
}
88+
`
89+
90+
const testProjectDataSourceConfig_withAccount = `
91+
resource "cloudstack_project" "project-account-resource" {
92+
name = "test-project-account-datasource"
93+
displaytext = "Test Project with Account for Data Source"
94+
account = "admin"
95+
domain = "ROOT"
96+
}
97+
98+
data "cloudstack_project" "project-account-data-source" {
99+
filter {
100+
name = "name"
101+
value = "test-project-account-datasource"
102+
}
103+
filter {
104+
name = "account"
105+
value = "admin"
106+
}
107+
depends_on = [
108+
cloudstack_project.project-account-resource
109+
]
110+
}
111+
112+
output "project-account-output" {
113+
value = data.cloudstack_project.project-account-data-source
114+
}
115+
`

cloudstack/provider.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ func Provider() *schema.Provider {
9191
"cloudstack_vpn_connection": dataSourceCloudstackVPNConnection(),
9292
"cloudstack_pod": dataSourceCloudstackPod(),
9393
"cloudstack_domain": dataSourceCloudstackDomain(),
94+
"cloudstack_project": dataSourceCloudstackProject(),
9495
"cloudstack_physical_network": dataSourceCloudStackPhysicalNetwork(),
9596
"cloudstack_role": dataSourceCloudstackRole(),
9697
"cloudstack_cluster": dataSourceCloudstackCluster(),
@@ -141,6 +142,7 @@ func Provider() *schema.Provider {
141142
"cloudstack_zone": resourceCloudStackZone(),
142143
"cloudstack_service_offering": resourceCloudStackServiceOffering(),
143144
"cloudstack_account": resourceCloudStackAccount(),
145+
"cloudstack_project": resourceCloudStackProject(),
144146
"cloudstack_user": resourceCloudStackUser(),
145147
"cloudstack_domain": resourceCloudStackDomain(),
146148
"cloudstack_network_service_provider": resourceCloudStackNetworkServiceProvider(),

0 commit comments

Comments
 (0)