Skip to content

Commit

Permalink
Merge pull request #56 from cloudfoundry/service_broker_datasource
Browse files Browse the repository at this point in the history
Added service_broker datasource
  • Loading branch information
vipinvkmenon authored Nov 4, 2024
2 parents 2f2d59c + d24da17 commit d1cbbb6
Show file tree
Hide file tree
Showing 10 changed files with 735 additions and 0 deletions.
42 changes: 42 additions & 0 deletions docs/data-sources/service_broker.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
---
page_title: "cloudfoundry_service_broker Data Source - terraform-provider-cloudfoundry"
subcategory: ""
description: |-
Gets information of a Service broker.
---

# cloudfoundry_service_broker (Data Source)

Gets information of a Service broker.

## Example Usage

```terraform
data "cloudfoundry_service_broker" "broker" {
name = "hi"
}
output "se_br" {
value = data.cloudfoundry_service_broker.broker
}
```

<!-- schema generated by tfplugindocs -->
## Schema

### Required

- `name` (String) Name of the service broker

### Optional

- `annotations` (Map of String) The annotations associated with Cloud Foundry resources. Add as described [here](https://docs.cloudfoundry.org/adminguide/metadata.html#-view-metadata-for-an-object).
- `labels` (Map of String) The labels associated with Cloud Foundry resources. Add as described [here](https://docs.cloudfoundry.org/adminguide/metadata.html#-view-metadata-for-an-object).

### Read-Only

- `created_at` (String) The date and time when the resource was created in [RFC3339](https://www.ietf.org/rfc/rfc3339.txt) format.
- `id` (String) The GUID of the object.
- `space` (String) The GUID of the space the service broker is restricted to; omitted for globally available service brokers
- `updated_at` (String) The date and time when the resource was updated in [RFC3339](https://www.ietf.org/rfc/rfc3339.txt) format.
- `url` (String) URL of the service broker
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
data "cloudfoundry_service_broker" "broker" {
name = "hi"
}

output "se_br" {
value = data.cloudfoundry_service_broker.broker
}
104 changes: 104 additions & 0 deletions internal/provider/datasource_service_broker.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
package provider

import (
"context"
"fmt"

cfv3client "github.com/cloudfoundry/go-cfclient/v3/client"
"github.com/cloudfoundry/terraform-provider-cloudfoundry/internal/provider/managers"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
)

func NewServiceBrokerDataSource() datasource.DataSource {
return &ServiceBrokerDataSource{}
}

type ServiceBrokerDataSource struct {
cfClient *cfv3client.Client
}

func (d *ServiceBrokerDataSource) Metadata(ctx context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_service_broker"
}

func (d *ServiceBrokerDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = schema.Schema{
MarkdownDescription: "Gets information of a Service broker.",

Attributes: map[string]schema.Attribute{
"name": schema.StringAttribute{
MarkdownDescription: "Name of the service broker",
Required: true,
},
"url": schema.StringAttribute{
MarkdownDescription: "URL of the service broker",
Computed: true,
},
"space": schema.StringAttribute{
MarkdownDescription: "The GUID of the space the service broker is restricted to; omitted for globally available service brokers",
Computed: true,
},
idKey: guidSchema(),
labelsKey: resourceLabelsSchema(),
annotationsKey: resourceAnnotationsSchema(),
createdAtKey: createdAtSchema(),
updatedAtKey: updatedAtSchema(),
},
}
}

func (d *ServiceBrokerDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
// Prevent panic if the provider has not been configured.
if req.ProviderData == nil {
return
}
session, ok := req.ProviderData.(*managers.Session)
if !ok {
resp.Diagnostics.AddError(
"Unexpected Data Source Configure Type",
fmt.Sprintf("Expected *managers.Session, got: %T. Please report this issue to the provider developers.", req.ProviderData),
)
return
}
d.cfClient = session.CFClient
}

func (d *ServiceBrokerDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {

var data datasourceServiceBrokerType

diags := req.Config.Get(ctx, &data)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}

getOptions := cfv3client.NewServiceBrokerListOptions()
getOptions.Names = cfv3client.Filter{
Values: []string{
data.Name.ValueString(),
},
}

svcBrokers, err := d.cfClient.ServiceBrokers.ListAll(ctx, getOptions)
if err != nil {
resp.Diagnostics.AddError(
"API Error in fetching service broker data.",
fmt.Sprintf("Request failed with %s.", err.Error()),
)
return
}
if len(svcBrokers) == 0 {
resp.Diagnostics.AddError(
"Unable to find service broker in list",
fmt.Sprintf("Given name %s not in the list of service brokers.", data.Name.ValueString()),
)
return
}

dataValue, diags := mapServiceBrokerValuesToType(ctx, svcBrokers[0])
resp.Diagnostics.Append(diags...)
data = dataValue.Reduce()
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}
60 changes: 60 additions & 0 deletions internal/provider/datasource_service_broker_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package provider

import (
"regexp"
"testing"

"github.com/hashicorp/terraform-plugin-testing/helper/resource"
)

func TestServiceBrokerDataSource(t *testing.T) {
t.Parallel()
serviceBrokerName := "hi"
t.Run("happy path - read service broker", func(t *testing.T) {
cfg := getCFHomeConf()
dataSourceName := "data.cloudfoundry_service_broker.ds"
rec := cfg.SetupVCR(t, "fixtures/datasource_service_broker")
defer stopQuietly(rec)
resource.Test(t, resource.TestCase{
IsUnitTest: true,
ProtoV6ProviderFactories: getProviders(rec.GetDefaultClient()),
Steps: []resource.TestStep{
{
Config: hclProvider(nil) + hclServiceBroker(&ServiceBrokerModelPtr{
HclType: hclObjectDataSource,
HclObjectName: "ds",
Name: &serviceBrokerName,
}),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestMatchResourceAttr(dataSourceName, "id", regexpValidUUID),
resource.TestMatchResourceAttr(dataSourceName, "space", regexpValidUUID),
resource.TestCheckResourceAttr(dataSourceName, "name", serviceBrokerName),
resource.TestMatchResourceAttr(dataSourceName, "created_at", regexpValidRFC3999Format),
resource.TestMatchResourceAttr(dataSourceName, "updated_at", regexpValidRFC3999Format),
),
},
},
})
})
t.Run("error path - get unavailable service broker", func(t *testing.T) {
cfg := getCFHomeConf()
rec := cfg.SetupVCR(t, "fixtures/datasource_service_broker_invalid")
defer stopQuietly(rec)
// Create a Terraform configuration that uses the data source
// and run `terraform apply`. The data source should not be found.
resource.UnitTest(t, resource.TestCase{
IsUnitTest: true,
ProtoV6ProviderFactories: getProviders(rec.GetDefaultClient()),
Steps: []resource.TestStep{
{
Config: hclProvider(nil) + hclServiceBroker(&ServiceBrokerModelPtr{
HclType: hclObjectDataSource,
HclObjectName: "ds",
Name: strtostrptr("invalid-service-instance-name"),
}),
ExpectError: regexp.MustCompile(`Unable to find service broker in list`),
},
},
})
})
}
Loading

0 comments on commit d1cbbb6

Please sign in to comment.