Skip to content

Commit 99d5b9f

Browse files
authored
Merge pull request #68 from DrFaust92/deploy-var-use-bb-client
Deploy Var use BB client + tests
2 parents 2721673 + ebdb971 commit 99d5b9f

File tree

5 files changed

+126
-115
lines changed

5 files changed

+126
-115
lines changed
Lines changed: 78 additions & 99 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,16 @@
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-
}
24-
25-
// 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-
}
32-
3314
func resourceDeploymentVariable() *schema.Resource {
3415
return &schema.Resource{
3516
Create: resourceDeploymentVariableCreate,
@@ -64,8 +45,8 @@ func resourceDeploymentVariable() *schema.Resource {
6445
}
6546
}
6647

67-
func newDeploymentVariableFromResource(d *schema.ResourceData) *DeploymentVariable {
68-
dk := &DeploymentVariable{
48+
func newDeploymentVariableFromResource(d *schema.ResourceData) *bitbucket.DeploymentVariable {
49+
dk := &bitbucket.DeploymentVariable{
6950
Key: d.Get("key").(string),
7051
Value: d.Get("value").(string),
7152
Secured: d.Get("secured").(bool),
@@ -79,129 +60,127 @@ func parseDeploymentId(str string) (repository string, deployment string) {
7960
}
8061

8162
func resourceDeploymentVariableCreate(d *schema.ResourceData, m interface{}) error {
82-
83-
client := m.(Clients).httpClient
63+
c := m.(Clients).genClient
64+
pipeApi := c.ApiClient.PipelinesApi
8465
rvcr := newDeploymentVariableFromResource(d)
85-
bytedata, err := json.Marshal(rvcr)
8666

87-
if err != nil {
88-
return err
89-
}
9067
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-
68+
workspace, repoSlug, err := deployVarId(repository)
9669
if err != nil {
9770
return err
9871
}
9972

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

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

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)
79+
d.Set("uuid", rvRes.Uuid)
80+
d.SetId(rvRes.Uuid)
11381

11482
time.Sleep(5000 * time.Millisecond) // sleep for a while, to allow BitBucket cache to catch up
11583
return resourceDeploymentVariableRead(d, m)
11684
}
11785

11886
func resourceDeploymentVariableRead(d *schema.ResourceData, m interface{}) error {
87+
c := m.(Clients).genClient
88+
pipeApi := c.ApiClient.PipelinesApi
11989

12090
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-
}
91+
workspace, repoSlug, err := deployVarId(repository)
92+
if err != nil {
93+
return err
94+
}
13595

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

141-
if prv.Size < 1 {
142-
d.SetId("")
143-
return nil
144-
}
101+
if res.StatusCode == http.StatusNotFound {
102+
log.Printf("[WARN] Deployment Variable (%s) not found, removing from state", d.Id())
103+
d.SetId("")
104+
return nil
105+
}
145106

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)
107+
if rvRes.Size < 1 {
108+
log.Printf("[WARN] Deployment Variable (%s) not found, removing from state", d.Id())
109+
d.SetId("")
110+
return nil
111+
}
151112

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

158-
return nil
159-
}
115+
for _, rv := range rvRes.Values {
116+
if rv.Uuid == d.Id() {
117+
deployVar = &rv
118+
break
160119
}
161-
d.SetId("")
162120
}
163121

164-
if rvReq.StatusCode == http.StatusNotFound {
122+
if deployVar == nil {
123+
log.Printf("[WARN] Deployment Variable (%s) not found, removing from state", d.Id())
165124
d.SetId("")
166125
return nil
167126
}
168127

128+
d.Set("key", deployVar.Key)
129+
d.Set("uuid", deployVar.Uuid)
130+
d.Set("secured", deployVar.Secured)
131+
132+
if !deployVar.Secured {
133+
d.Set("value", deployVar.Value)
134+
} else {
135+
d.Set("value", d.Get("value").(string))
136+
}
137+
169138
return nil
170139
}
171140

172141
func resourceDeploymentVariableUpdate(d *schema.ResourceData, m interface{}) error {
173-
client := m.(Clients).httpClient
142+
c := m.(Clients).genClient
143+
pipeApi := c.ApiClient.PipelinesApi
174144
rvcr := newDeploymentVariableFromResource(d)
175-
bytedata, err := json.Marshal(rvcr)
176145

177-
if err != nil {
178-
return err
179-
}
180146
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-
147+
workspace, repoSlug, err := deployVarId(repository)
187148
if err != nil {
188149
return err
189150
}
190151

191-
if req.StatusCode != 200 {
192-
return nil
152+
_, _, err = pipeApi.UpdateDeploymentVariable(c.AuthContext, *rvcr, workspace, repoSlug, deployment, d.Get("uuid").(string))
153+
154+
if err != nil {
155+
return fmt.Errorf("error updating Deployment Variable (%s): %w", d.Get("deployment").(string), err)
193156
}
194157

195158
return resourceDeploymentVariableRead(d, m)
196159
}
197160

198161
func resourceDeploymentVariableDelete(d *schema.ResourceData, m interface{}) error {
162+
c := m.(Clients).genClient
163+
pipeApi := c.ApiClient.PipelinesApi
164+
199165
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
166+
workspace, repoSlug, err := deployVarId(repository)
167+
if err != nil {
168+
return err
169+
}
170+
171+
_, err = pipeApi.DeleteDeploymentVariable(c.AuthContext, workspace, repoSlug, deployment, d.Get("uuid").(string))
172+
if err != nil {
173+
return fmt.Errorf("error deleting Deployment Variable (%s): %w", d.Id(), err)
174+
}
175+
176+
return nil
177+
}
178+
179+
func deployVarId(repo string) (string, string, error) {
180+
idparts := strings.Split(repo, "/")
181+
if len(idparts) == 2 {
182+
return idparts[0], idparts[1], nil
183+
} else {
184+
return "", "", fmt.Errorf("incorrect ID format, should match `owner/key`")
185+
}
207186
}

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

go.sum

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@ cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9
3333
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
3434
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
3535
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
36-
github.com/DrFaust92/bitbucket-go-client v0.0.8 h1:sU4J6d+uXPpRAjGb00upd6ZaGEh4TGQuWhfilANDQoM=
37-
github.com/DrFaust92/bitbucket-go-client v0.0.8/go.mod h1:3UJtT6PmlsB7MCc1MbegmGlT2waRlIMIHtaQLTcd794=
36+
github.com/DrFaust92/bitbucket-go-client v0.0.9 h1:pcIPTEC3gdMhs89CgMODBIAKd6MrWHOwnJ/rJ9mBgVg=
37+
github.com/DrFaust92/bitbucket-go-client v0.0.9/go.mod h1:3UJtT6PmlsB7MCc1MbegmGlT2waRlIMIHtaQLTcd794=
3838
github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA=
3939
github.com/Microsoft/go-winio v0.4.16 h1:FtSW/jqD+l4ba5iPBj9CODVtgfYAD8w2wS923g/cFDk=
4040
github.com/Microsoft/go-winio v0.4.16/go.mod h1:XB6nPKklQyQ7GC9LdcBEcBl8PF76WugXOPRXwdLnMv0=

0 commit comments

Comments
 (0)