Skip to content

Commit e84e782

Browse files
committed
Deploy Var use BB client + tests
1 parent 2721673 commit e84e782

File tree

5 files changed

+139
-112
lines changed

5 files changed

+139
-112
lines changed
Lines changed: 91 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,31 @@
11
package bitbucket
22

33
import (
4-
"bytes"
5-
"encoding/json"
64
"fmt"
7-
"io/ioutil"
85
"log"
96
"net/http"
10-
"net/url"
117
"strings"
128
"time"
139

10+
"github.com/DrFaust92/bitbucket-go-client"
1411
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
1512
)
1613

17-
// DeploymentVariable structure for handling key info
18-
type DeploymentVariable struct {
19-
Key string `json:"key"`
20-
Value string `json:"value"`
21-
UUID string `json:"uuid,omitempty"`
22-
Secured bool `json:"secured"`
23-
}
14+
// // DeploymentVariable structure for handling key info
15+
// type DeploymentVariable struct {
16+
// Key string `json:"key"`
17+
// Value string `json:"value"`
18+
// UUID string `json:"uuid,omitempty"`
19+
// Secured bool `json:"secured"`
20+
// }
2421

2522
// PaginatedReviewers is a paginated list that the bitbucket api returns
26-
type PaginatedDeploymentVariables struct {
27-
Values []DeploymentVariable `json:"values,omitempty"`
28-
Page int `json:"page,omitempty"`
29-
Size int `json:"size,omitempty"`
30-
Next string `json:"next,omitempty"`
31-
}
23+
// type PaginatedDeploymentVariables struct {
24+
// Values []bitbucket.DeploymentVariable `json:"values,omitempty"`
25+
// Page int `json:"page,omitempty"`
26+
// Size int `json:"size,omitempty"`
27+
// Next string `json:"next,omitempty"`
28+
// }
3229

3330
func resourceDeploymentVariable() *schema.Resource {
3431
return &schema.Resource{
@@ -64,8 +61,8 @@ func resourceDeploymentVariable() *schema.Resource {
6461
}
6562
}
6663

67-
func newDeploymentVariableFromResource(d *schema.ResourceData) *DeploymentVariable {
68-
dk := &DeploymentVariable{
64+
func newDeploymentVariableFromResource(d *schema.ResourceData) *bitbucket.DeploymentVariable {
65+
dk := &bitbucket.DeploymentVariable{
6966
Key: d.Get("key").(string),
7067
Value: d.Get("value").(string),
7168
Secured: d.Get("secured").(bool),
@@ -79,129 +76,127 @@ func parseDeploymentId(str string) (repository string, deployment string) {
7976
}
8077

8178
func resourceDeploymentVariableCreate(d *schema.ResourceData, m interface{}) error {
82-
83-
client := m.(Clients).httpClient
79+
c := m.(Clients).genClient
80+
pipeApi := c.ApiClient.PipelinesApi
8481
rvcr := newDeploymentVariableFromResource(d)
85-
bytedata, err := json.Marshal(rvcr)
8682

87-
if err != nil {
88-
return err
89-
}
9083
repository, deployment := parseDeploymentId(d.Get("deployment").(string))
91-
req, err := client.Post(fmt.Sprintf("2.0/repositories/%s/deployments_config/environments/%s/variables",
92-
repository,
93-
deployment,
94-
), bytes.NewBuffer(bytedata))
95-
84+
workspace, repoSlug, err := deployVarId(repository)
9685
if err != nil {
9786
return err
9887
}
9988

100-
var rv DeploymentVariable
89+
rvRes, _, err := pipeApi.CreateDeploymentVariable(c.AuthContext, *rvcr, workspace, repoSlug, deployment)
10190

102-
body, readerr := ioutil.ReadAll(req.Body)
103-
if readerr != nil {
104-
return readerr
91+
if err != nil {
92+
return fmt.Errorf("error creating Deployment Variable (%s): %w", d.Get("deployment").(string), err)
10593
}
10694

107-
decodeerr := json.Unmarshal(body, &rv)
108-
if decodeerr != nil {
109-
return decodeerr
110-
}
111-
d.Set("uuid", rv.UUID)
112-
d.SetId(rv.UUID)
95+
d.Set("uuid", rvRes.Uuid)
96+
d.SetId(rvRes.Uuid)
11397

11498
time.Sleep(5000 * time.Millisecond) // sleep for a while, to allow BitBucket cache to catch up
11599
return resourceDeploymentVariableRead(d, m)
116100
}
117101

118102
func resourceDeploymentVariableRead(d *schema.ResourceData, m interface{}) error {
103+
c := m.(Clients).genClient
104+
pipeApi := c.ApiClient.PipelinesApi
119105

120106
repository, deployment := parseDeploymentId(d.Get("deployment").(string))
121-
client := m.(Clients).httpClient
122-
rvReq, _ := client.Get(fmt.Sprintf("2.0/repositories/%s/deployments_config/environments/%s/variables?pagelen=100",
123-
repository,
124-
deployment,
125-
))
126-
127-
log.Printf("ID: %s", url.PathEscape(d.Id()))
128-
129-
if rvReq.StatusCode == 200 {
130-
var prv PaginatedDeploymentVariables
131-
body, readerr := ioutil.ReadAll(rvReq.Body)
132-
if readerr != nil {
133-
return readerr
134-
}
107+
workspace, repoSlug, err := deployVarId(repository)
108+
if err != nil {
109+
return err
110+
}
135111

136-
decodeerr := json.Unmarshal(body, &prv)
137-
if decodeerr != nil {
138-
return decodeerr
139-
}
112+
rvRes, res, err := pipeApi.GetDeploymentVariables(c.AuthContext, workspace, repoSlug, deployment)
113+
if err != nil {
114+
return fmt.Errorf("error reading Deployment Variable (%s): %w", d.Id(), err)
115+
}
140116

141-
if prv.Size < 1 {
142-
d.SetId("")
143-
return nil
144-
}
117+
if res.StatusCode == http.StatusNotFound {
118+
log.Printf("[WARN] Deployment Variable (%s) not found, removing from state", d.Id())
119+
d.SetId("")
120+
return nil
121+
}
145122

146-
for _, rv := range prv.Values {
147-
if rv.UUID == d.Id() {
148-
d.SetId(rv.UUID)
149-
d.Set("key", rv.Key)
150-
d.Set("secured", rv.Secured)
123+
if rvRes.Size < 1 {
124+
log.Printf("[WARN] Deployment Variable (%s) not found, removing from state", d.Id())
125+
d.SetId("")
126+
return nil
127+
}
151128

152-
if !rv.Secured {
153-
d.Set("value", rv.Value)
154-
} else {
155-
d.Set("value", d.Get("value").(string))
156-
}
129+
var deployVar *bitbucket.DeploymentVariable
157130

158-
return nil
159-
}
131+
for _, rv := range rvRes.Values {
132+
if rv.Uuid == d.Id() {
133+
deployVar = &rv
134+
break
160135
}
161-
d.SetId("")
162136
}
163137

164-
if rvReq.StatusCode == http.StatusNotFound {
138+
if deployVar == nil {
139+
log.Printf("[WARN] Deployment Variable (%s) not found, removing from state", d.Id())
165140
d.SetId("")
166141
return nil
167142
}
168143

144+
d.Set("key", deployVar.Key)
145+
d.Set("uuid", deployVar.Uuid)
146+
d.Set("secured", deployVar.Secured)
147+
148+
if !deployVar.Secured {
149+
d.Set("value", deployVar.Value)
150+
} else {
151+
d.Set("value", d.Get("value").(string))
152+
}
153+
169154
return nil
170155
}
171156

172157
func resourceDeploymentVariableUpdate(d *schema.ResourceData, m interface{}) error {
173-
client := m.(Clients).httpClient
158+
c := m.(Clients).genClient
159+
pipeApi := c.ApiClient.PipelinesApi
174160
rvcr := newDeploymentVariableFromResource(d)
175-
bytedata, err := json.Marshal(rvcr)
176161

177-
if err != nil {
178-
return err
179-
}
180162
repository, deployment := parseDeploymentId(d.Get("deployment").(string))
181-
req, err := client.Put(fmt.Sprintf("2.0/repositories/%s/deployments_config/environments/%s/variables/%s",
182-
repository,
183-
deployment,
184-
d.Get("uuid").(string),
185-
), bytes.NewBuffer(bytedata))
186-
163+
workspace, repoSlug, err := deployVarId(repository)
187164
if err != nil {
188165
return err
189166
}
190167

191-
if req.StatusCode != 200 {
192-
return nil
168+
_, _, err = pipeApi.UpdateDeploymentVariable(c.AuthContext, *rvcr, workspace, repoSlug, deployment, d.Get("uuid").(string))
169+
170+
if err != nil {
171+
return fmt.Errorf("error updating Deployment Variable (%s): %w", d.Get("deployment").(string), err)
193172
}
194173

195174
return resourceDeploymentVariableRead(d, m)
196175
}
197176

198177
func resourceDeploymentVariableDelete(d *schema.ResourceData, m interface{}) error {
178+
c := m.(Clients).genClient
179+
pipeApi := c.ApiClient.PipelinesApi
180+
199181
repository, deployment := parseDeploymentId(d.Get("deployment").(string))
200-
client := m.(Clients).httpClient
201-
_, err := client.Delete(fmt.Sprintf("2.0/repositories/%s/deployments_config/environments/%s/variables/%s",
202-
repository,
203-
deployment,
204-
d.Get("uuid").(string),
205-
))
206-
return err
182+
workspace, repoSlug, err := deployVarId(repository)
183+
if err != nil {
184+
return err
185+
}
186+
187+
_, err = pipeApi.DeleteDeploymentVariable(c.AuthContext, workspace, repoSlug, deployment, d.Get("uuid").(string))
188+
if err != nil {
189+
return fmt.Errorf("error deleting Deployment Variable (%s): %w", d.Id(), err)
190+
}
191+
192+
return nil
193+
}
194+
195+
func deployVarId(repo string) (string, string, error) {
196+
idparts := strings.Split(repo, "/")
197+
if len(idparts) == 2 {
198+
return idparts[0], idparts[1], nil
199+
} else {
200+
return "", "", fmt.Errorf("incorrect ID format, should match `owner/key`")
201+
}
207202
}

bitbucket/resource_deployment_variable_test.go

Lines changed: 45 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ func TestAccBitbucketDeploymentVariable_basic(t *testing.T) {
2222
CheckDestroy: testAccCheckBitbucketDeploymentVariableDestroy,
2323
Steps: []resource.TestStep{
2424
{
25-
Config: testAccBitbucketDeploymentVariableConfig(owner, rName, false),
25+
Config: testAccBitbucketDeploymentVariableConfig(owner, rName, "test", false),
2626
Check: resource.ComposeTestCheckFunc(
2727
testAccCheckBitbucketDeploymentVariableExists(resourceName),
2828
resource.TestCheckResourceAttrPair(resourceName, "deployment", "bitbucket_deployment.test", "id"),
@@ -31,6 +31,16 @@ func TestAccBitbucketDeploymentVariable_basic(t *testing.T) {
3131
resource.TestCheckResourceAttr(resourceName, "secured", "false"),
3232
),
3333
},
34+
{
35+
Config: testAccBitbucketDeploymentVariableConfig(owner, rName, "test-2", false),
36+
Check: resource.ComposeTestCheckFunc(
37+
testAccCheckBitbucketDeploymentVariableExists(resourceName),
38+
resource.TestCheckResourceAttrPair(resourceName, "deployment", "bitbucket_deployment.test", "id"),
39+
resource.TestCheckResourceAttr(resourceName, "key", "test"),
40+
resource.TestCheckResourceAttr(resourceName, "value", "test-2"),
41+
resource.TestCheckResourceAttr(resourceName, "secured", "false"),
42+
),
43+
},
3444
},
3545
})
3646
}
@@ -46,7 +56,27 @@ func TestAccBitbucketDeploymentVariable_secure(t *testing.T) {
4656
CheckDestroy: testAccCheckBitbucketDeploymentVariableDestroy,
4757
Steps: []resource.TestStep{
4858
{
49-
Config: testAccBitbucketDeploymentVariableConfig(owner, rName, true),
59+
Config: testAccBitbucketDeploymentVariableConfig(owner, rName, "test", true),
60+
Check: resource.ComposeTestCheckFunc(
61+
testAccCheckBitbucketDeploymentVariableExists(resourceName),
62+
resource.TestCheckResourceAttrPair(resourceName, "deployment", "bitbucket_deployment.test", "id"),
63+
resource.TestCheckResourceAttr(resourceName, "key", "test"),
64+
resource.TestCheckResourceAttr(resourceName, "value", "test"),
65+
resource.TestCheckResourceAttr(resourceName, "secured", "true"),
66+
),
67+
},
68+
{
69+
Config: testAccBitbucketDeploymentVariableConfig(owner, rName, "test", false),
70+
Check: resource.ComposeTestCheckFunc(
71+
testAccCheckBitbucketDeploymentVariableExists(resourceName),
72+
resource.TestCheckResourceAttrPair(resourceName, "deployment", "bitbucket_deployment.test", "id"),
73+
resource.TestCheckResourceAttr(resourceName, "key", "test"),
74+
resource.TestCheckResourceAttr(resourceName, "value", "test"),
75+
resource.TestCheckResourceAttr(resourceName, "secured", "false"),
76+
),
77+
},
78+
{
79+
Config: testAccBitbucketDeploymentVariableConfig(owner, rName, "test", true),
5080
Check: resource.ComposeTestCheckFunc(
5181
testAccCheckBitbucketDeploymentVariableExists(resourceName),
5282
resource.TestCheckResourceAttrPair(resourceName, "deployment", "bitbucket_deployment.test", "id"),
@@ -60,20 +90,26 @@ func TestAccBitbucketDeploymentVariable_secure(t *testing.T) {
6090
}
6191

6292
func testAccCheckBitbucketDeploymentVariableDestroy(s *terraform.State) error {
63-
client := testAccProvider.Meta().(Clients).httpClient
93+
client := testAccProvider.Meta().(Clients).genClient
94+
pipeApi := client.ApiClient.PipelinesApi
6495
for _, rs := range s.RootModule().Resources {
6596
if rs.Type != "bitbucket_deployment_variable" {
6697
continue
6798
}
6899

69100
repository, deployment := parseDeploymentId(rs.Primary.Attributes["deployment"])
70-
response, err := client.Get(fmt.Sprintf("2.0/repositories/%s/deployments_config/environments/%s/variables?pagelen=100", repository, deployment))
101+
workspace, repoSlug, err := deployVarId(repository)
102+
if err != nil {
103+
return err
104+
}
105+
106+
_, res, err := pipeApi.GetDeploymentVariables(client.AuthContext, workspace, repoSlug, deployment)
71107

72108
if err == nil {
73109
return fmt.Errorf("The resource was found should have errored")
74110
}
75111

76-
if response.StatusCode != http.StatusNotFound {
112+
if res.StatusCode != http.StatusNotFound {
77113
return fmt.Errorf("Deployment Variable still exists")
78114
}
79115
}
@@ -92,7 +128,7 @@ func testAccCheckBitbucketDeploymentVariableExists(n string) resource.TestCheckF
92128
}
93129
}
94130

95-
func testAccBitbucketDeploymentVariableConfig(owner, rName string, secure bool) string {
131+
func testAccBitbucketDeploymentVariableConfig(owner, rName, val string, secure bool) string {
96132
return fmt.Sprintf(`
97133
resource "bitbucket_repository" "test" {
98134
owner = %[1]q
@@ -107,9 +143,9 @@ resource "bitbucket_deployment" "test" {
107143
108144
resource "bitbucket_deployment_variable" "test" {
109145
key = "test"
110-
value = "test"
146+
value = %[3]q
111147
deployment = bitbucket_deployment.test.id
112-
secured = %[3]t
148+
secured = %[4]t
113149
}
114-
`, owner, rName, secure)
150+
`, owner, rName, val, secure)
115151
}

bitbucket/resource_repository_variable.go

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -126,10 +126,6 @@ func resourceRepositoryVariableUpdate(d *schema.ResourceData, m interface{}) err
126126
return fmt.Errorf("error updating Repository Variable (%s): %w", d.Id(), err)
127127
}
128128

129-
if err != nil {
130-
return err
131-
}
132-
133129
return resourceRepositoryVariableRead(d, m)
134130
}
135131

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
module github.com/terraform-providers/terraform-provider-bitbucket
22

33
require (
4-
github.com/DrFaust92/bitbucket-go-client v0.0.8
4+
github.com/DrFaust92/bitbucket-go-client v0.0.9
55
github.com/antihax/optional v1.0.0
66
github.com/hashicorp/terraform-plugin-sdk/v2 v2.15.0
77
github.com/satori/go.uuid v1.2.0

0 commit comments

Comments
 (0)