forked from mirrors/terraform-provider-binarylane
Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3a64bf2482 | |||
| 5978c20f99 | |||
| 3e90a4506a | |||
| a197444c4e | |||
| c1acb29c8c | |||
| 093c2e022a | |||
| a9c133e73c | |||
| f659cfcd25 | |||
| 3ed14bdae3 | |||
| 00b6fae313 |
@@ -35,9 +35,16 @@ steps:
|
||||
- |
|
||||
VERSION=$$(echo ${CI_COMMIT_TAG} | sed 's/^v//')
|
||||
FILE="terraform-provider-binarylane_$${VERSION}_linux_amd64.zip"
|
||||
set -o pipefail
|
||||
VAULT="https://vault.service.consul:8200"
|
||||
AUTH=$$(mktemp)
|
||||
VT=$$(jq -n --rawfile jwt /var/run/secrets/kubernetes.io/serviceaccount/token '{role:"woodpecker_artifactapi_writer",jwt:$$jwt}' \
|
||||
| curl -sf -d @- "$$VAULT/v1/auth/k8s/au/syd1/login" | jq -er .auth.client_token) || exit 1
|
||||
printf 'X-Vault-Token: %s\n' "$$VT" | curl -sf -H @- "$$VAULT/v1/identity/oidc/token/artifactapi-writer" \
|
||||
| jq -er '"Authorization: Bearer " + .data.token' > "$$AUTH" || exit 1
|
||||
curl -f -X PUT \
|
||||
"https://artifactapi.k8s.syd1.au.unkin.net/api/v2/remotes/terraform-unkin/files/unkin/binarylane/$${FILE}" \
|
||||
-H "Content-Type: application/zip" \
|
||||
-H "Content-Type: application/zip" -H @"$$AUTH" \
|
||||
--data-binary @"$${FILE}"
|
||||
depends_on: [package]
|
||||
backend_options:
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ Based on [this example from the terraform docs](https://developer.hashicorp.com/
|
||||
provider_installation {
|
||||
dev_overrides {
|
||||
# Example GOBIN path, will need to be replaced with your own GOBIN path. Default is $GOPATH/bin
|
||||
"git.unkin.net/unkin/binarylane" = "/path/to/terraform-provider-binarylane/bin"
|
||||
"IUCLabs/binarylane" = "/path/to/terraform-provider-binarylane/bin"
|
||||
}
|
||||
|
||||
direct {}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
.PHONY: build install test lint fmt clean tidy package pre-commit patch minor major check-go
|
||||
.PHONY: build install test lint fmt clean tidy package pre-commit patch minor major check-go docs
|
||||
|
||||
BINARY := terraform-provider-binarylane
|
||||
VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo "0.0.0-dev")
|
||||
OS_ARCH := linux_amd64
|
||||
INSTALL_VERSION := $(shell echo $(VERSION) | sed 's/^v//')
|
||||
INSTALL_DIR := ~/.terraform.d/plugins/git.unkin.net/unkin/binarylane/$(INSTALL_VERSION)/$(OS_ARCH)
|
||||
INSTALL_DIR := ~/.terraform.d/plugins/registry.terraform.io/iuclabs/binarylane/$(INSTALL_VERSION)/$(OS_ARCH)
|
||||
ZIP := $(BINARY)_$(INSTALL_VERSION)_$(OS_ARCH).zip
|
||||
|
||||
GO_VERSION_REQUIRED := 1.25
|
||||
@@ -36,6 +36,9 @@ package: build
|
||||
python3 -c "import zipfile,sys; z=zipfile.ZipFile(sys.argv[1],'w',zipfile.ZIP_DEFLATED); z.write(sys.argv[2]); z.close()" $(ZIP) $(BINARY)_v$(INSTALL_VERSION)
|
||||
rm $(BINARY)_v$(INSTALL_VERSION)
|
||||
|
||||
docs:
|
||||
go run github.com/hashicorp/terraform-plugin-docs/cmd/tfplugindocs generate --provider-name binarylane --rendered-provider-name terraform-provider-binarylane
|
||||
|
||||
pre-commit:
|
||||
uvx pre-commit run --all-files
|
||||
|
||||
|
||||
@@ -1,8 +1,29 @@
|
||||
# terraform-provider-binarylane
|
||||
# Terraform Provider for BinaryLane
|
||||
|
||||
See the [documentation on the Terraform Registry](https://registry.terraform.io/providers/oscarhermoso/binarylane/latest), or see [examples in the `examples` directory](./examples/README.md).
|
||||
A Terraform provider for managing [BinaryLane](https://www.binarylane.com.au/) cloud resources: servers, firewall rules, reverse DNS, SSH keys, VPCs and load balancers.
|
||||
|
||||
This is a fork of [oscarhermoso/terraform-provider-binarylane](https://github.com/oscarhermoso/terraform-provider-binarylane). It tracks upstream and adds:
|
||||
|
||||
- `binarylane_server_reverse_name` resource for managing IPv4 PTR records
|
||||
- omitting `destination_ports` on `binarylane_server_firewall_rules` (e.g. for ICMP rules) resolves to null after apply instead of leaving it unknown
|
||||
- server action waits are bounded by a timeout instead of polling forever
|
||||
|
||||
## Quick start
|
||||
|
||||
```terraform
|
||||
terraform {
|
||||
required_providers {
|
||||
binarylane = {
|
||||
source = "IUCLabs/binarylane"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
provider "binarylane" {
|
||||
# Or set BINARYLANE_API_TOKEN
|
||||
api_token = var.binarylane_api_token
|
||||
}
|
||||
|
||||
resource "binarylane_server" "example" {
|
||||
region = "per"
|
||||
image = "ubuntu-24.04"
|
||||
@@ -11,140 +32,28 @@ resource "binarylane_server" "example" {
|
||||
}
|
||||
```
|
||||
|
||||
## Progress
|
||||
More complete configurations live in [`examples/`](./examples/README.md).
|
||||
|
||||
Planned features:
|
||||
## Requirements
|
||||
|
||||
- [x] Servers
|
||||
- [x] Firewall Rules
|
||||
- [x] Cloud Init
|
||||
- [x] Updating server properties
|
||||
- [x] "Advanced Features"
|
||||
- [x] IPV6
|
||||
- [ ] Customised Backups
|
||||
- [ ] Software
|
||||
- [ ] Alerts
|
||||
- [x] SSH Keys
|
||||
- [x] Virtual Private Cloud
|
||||
- [x] Load Balancers
|
||||
- [ ] Images
|
||||
- [ ] DNS
|
||||
- [x] Docs
|
||||
- [x] Generated docs
|
||||
- [ ] Review & fill out remaining descriptions
|
||||
- [ ] Include examples in docs
|
||||
- [x] Examples
|
||||
- [x] Basic
|
||||
- [x] Cloud Init
|
||||
- [x] K3s
|
||||
- [ ] NixOS
|
||||
- [ ] Virtual Private Cloud
|
||||
- [Terraform](https://developer.hashicorp.com/terraform/downloads) >= 1.0 (plugin protocol 6)
|
||||
- [Go](https://go.dev/doc/install) >= 1.25 to build the provider
|
||||
- A BinaryLane API token
|
||||
|
||||
## Server parameters
|
||||
## Documentation
|
||||
|
||||
### Regions
|
||||
Provider and resource documentation is in [`docs/`](./docs/index.md), in the Terraform Registry layout. Regenerate it with `make docs` after changing a schema.
|
||||
|
||||
<details>
|
||||
<summary>curl for regions</summary>
|
||||
## Developing
|
||||
|
||||
```sh
|
||||
curl -X GET "https://api.binarylane.com.au/v2/regions" \
|
||||
-H "Authorization: Bearer $BINARYLANE_API_TOKEN" > tmp/regions.json
|
||||
|
||||
jq '[ .regions[] | .slug ] | sort' tmp/regions.json
|
||||
```
|
||||
</details>
|
||||
|
||||
```json
|
||||
[
|
||||
"adl",
|
||||
"bne",
|
||||
"mel",
|
||||
"per",
|
||||
"sin",
|
||||
"syd"
|
||||
]
|
||||
make build # build the provider binary
|
||||
make test # unit tests
|
||||
make docs # regenerate docs/
|
||||
```
|
||||
|
||||
### Images
|
||||
Acceptance tests run against the live BinaryLane API and need `TF_ACC=1` and `BINARYLANE_API_TOKEN`. See [CONTRIBUTING.md](./CONTRIBUTING.md) for local development overrides.
|
||||
|
||||
<details>
|
||||
<summary>curl for images</summary>
|
||||
## License
|
||||
|
||||
```sh
|
||||
curl -X GET "https://api.binarylane.com.au/v2/images?type=distribution&&page=1&per_page=200" \
|
||||
-H "Authorization: Bearer $BINARYLANE_API_TOKEN" > tmp/images.json
|
||||
|
||||
jq '[ .images[] | .slug ] | sort' tmp/images.json
|
||||
```
|
||||
</details>
|
||||
|
||||
```json
|
||||
[
|
||||
"alma-10",
|
||||
"alma-8",
|
||||
"alma-9",
|
||||
"byo-os",
|
||||
"byo-os-uefi",
|
||||
"byo-os-virtio-disabled",
|
||||
"cpanel-plus-whm",
|
||||
"debian-11",
|
||||
"debian-12",
|
||||
"debian-13",
|
||||
"rocky-10",
|
||||
"rocky-9",
|
||||
"ubuntu-20.04.6",
|
||||
"ubuntu-22.04",
|
||||
"ubuntu-22.04-desktop",
|
||||
"ubuntu-24.04",
|
||||
"ubuntu-24.04-neon-desktop",
|
||||
"ubuntu-26.04",
|
||||
"windows-2016",
|
||||
"windows-2016-sql-2016-web",
|
||||
"windows-2019",
|
||||
"windows-2019-sql-2017-std",
|
||||
"windows-2019-sql-2017-web",
|
||||
"windows-2022",
|
||||
"windows-2022-sql-2019-std",
|
||||
"windows-2022-sql-2019-web",
|
||||
"windows-2025"
|
||||
]
|
||||
```
|
||||
|
||||
### Sizes
|
||||
|
||||
<details>
|
||||
<summary>curl for sizes</summary>
|
||||
|
||||
```sh
|
||||
curl -X GET "https://api.binarylane.com.au/v2/sizes" \
|
||||
-H "Authorization: Bearer $BINARYLANE_API_TOKEN" > tmp/sizes.json
|
||||
|
||||
jq '[ .sizes[] | .slug ] | sort' tmp/sizes.json
|
||||
```
|
||||
</details>
|
||||
|
||||
```json
|
||||
[
|
||||
"cpu-2thr",
|
||||
"cpu-4thr",
|
||||
"cpu-6thr",
|
||||
"cpu-8thr",
|
||||
"ded-7900x-800gb",
|
||||
"ded-e2136-400gb",
|
||||
"ded-e2136-800gb",
|
||||
"ded-e2288g-800gb",
|
||||
"hdd-1000gb",
|
||||
"hdd-2000gb",
|
||||
"hdd-4000gb",
|
||||
"hdd-500gb",
|
||||
"hdd-6000gb",
|
||||
"hdd-8000gb",
|
||||
"std-1vcpu",
|
||||
"std-2vcpu",
|
||||
"std-4vcpu",
|
||||
"std-6vcpu",
|
||||
"std-8vcpu",
|
||||
"std-min"
|
||||
]
|
||||
```
|
||||
[MIT](./LICENSE), as inherited from upstream.
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@ description: |-
|
||||
terraform {
|
||||
required_providers {
|
||||
binarylane = {
|
||||
source = "git.unkin.net/unkin/binarylane"
|
||||
source = "IUCLabs/binarylane"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
terraform {
|
||||
required_providers {
|
||||
binarylane = {
|
||||
source = "git.unkin.net/unkin/binarylane"
|
||||
source = "IUCLabs/binarylane"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ If you want to deploy multiple parts of a cloud-init configuration, you can use
|
||||
terraform {
|
||||
required_providers {
|
||||
binarylane = {
|
||||
source = "git.unkin.net/unkin/binarylane"
|
||||
source = "IUCLabs/binarylane"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
terraform {
|
||||
required_providers {
|
||||
binarylane = {
|
||||
source = "git.unkin.net/unkin/binarylane"
|
||||
source = "IUCLabs/binarylane"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
terraform {
|
||||
required_providers {
|
||||
binarylane = {
|
||||
source = "git.unkin.net/unkin/binarylane"
|
||||
source = "IUCLabs/binarylane"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
terraform {
|
||||
required_providers {
|
||||
binarylane = {
|
||||
source = "git.unkin.net/unkin/binarylane"
|
||||
source = "IUCLabs/binarylane"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
terraform {
|
||||
required_providers {
|
||||
binarylane = {
|
||||
source = "git.unkin.net/unkin/binarylane"
|
||||
source = "IUCLabs/binarylane"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
terraform {
|
||||
required_providers {
|
||||
binarylane = {
|
||||
source = "git.unkin.net/unkin/binarylane"
|
||||
source = "IUCLabs/binarylane"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
terraform {
|
||||
required_providers {
|
||||
binarylane = {
|
||||
source = "git.unkin.net/unkin/binarylane"
|
||||
source = "IUCLabs/binarylane"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
terraform {
|
||||
required_providers {
|
||||
binarylane = {
|
||||
source = "git.unkin.net/unkin/binarylane"
|
||||
source = "IUCLabs/binarylane"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,6 +121,11 @@ func (r *serverFirewallRulesResource) Create(ctx context.Context, req resource.C
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resolveUnknownDestinationPorts(ctx, &data)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
// Save data into Terraform state
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
|
||||
}
|
||||
@@ -207,6 +212,11 @@ func (r *serverFirewallRulesResource) Update(ctx context.Context, req resource.U
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resolveUnknownDestinationPorts(ctx, &data)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
// Save updated data into Terraform state
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
|
||||
}
|
||||
@@ -245,6 +255,22 @@ func (r *serverFirewallRulesResource) Delete(ctx context.Context, req resource.D
|
||||
}
|
||||
}
|
||||
|
||||
// Omitted destination_ports (all ports) are planned as unknown because the attribute is computed.
|
||||
func resolveUnknownDestinationPorts(ctx context.Context, data *serverFirewallRulesResourceModel) diag.Diagnostics {
|
||||
var rules []resources.FirewallRulesValue
|
||||
diags := data.FirewallRules.ElementsAs(ctx, &rules, false)
|
||||
if diags.HasError() {
|
||||
return diags
|
||||
}
|
||||
for i := range rules {
|
||||
if rules[i].DestinationPorts.IsUnknown() {
|
||||
rules[i].DestinationPorts = types.ListNull(types.StringType)
|
||||
}
|
||||
}
|
||||
data.FirewallRules, diags = types.ListValueFrom(ctx, resources.FirewallRulesValue{}.Type(ctx), rules)
|
||||
return diags
|
||||
}
|
||||
|
||||
func GetFirewallRulesState(ctx context.Context, firewallRules *[]binarylane.AdvancedFirewallRule) (basetypes.ListValue, diag.Diagnostics) {
|
||||
var diags diag.Diagnostics
|
||||
|
||||
@@ -258,7 +284,7 @@ func GetFirewallRulesState(ctx context.Context, firewallRules *[]binarylane.Adva
|
||||
destinationAddresses, diag := types.ListValueFrom(ctx, types.StringType, rule.DestinationAddresses)
|
||||
diags.Append(diag...)
|
||||
|
||||
var destinationPorts basetypes.ListValue
|
||||
destinationPorts := types.ListNull(types.StringType)
|
||||
if rule.DestinationPorts != nil {
|
||||
destinationPorts, diag = types.ListValueFrom(ctx, types.StringType, rule.DestinationPorts)
|
||||
diags.Append(diag...)
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"terraform-provider-binarylane/internal/binarylane"
|
||||
"terraform-provider-binarylane/internal/resources"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/tfsdk"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/hashicorp/terraform-plugin-go/tftypes"
|
||||
)
|
||||
|
||||
func TestServerFirewallRulesResourceOmittedPorts(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if r.Method == http.MethodGet {
|
||||
_, _ = w.Write([]byte(`{"firewall_rules":[{"action":"accept","protocol":"icmp","source_addresses":["10.0.0.0/8"],"destination_addresses":["10.0.0.1"],"destination_ports":null}]}`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
client, err := binarylane.NewClientWithConfig(srv.URL, "test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := &serverFirewallRulesResource{bc: &BinarylaneClient{client: client}}
|
||||
|
||||
schemaResp := resource.SchemaResponse{}
|
||||
r.Schema(ctx, resource.SchemaRequest{}, &schemaResp)
|
||||
s := schemaResp.Schema
|
||||
emptyState := func() tfsdk.State {
|
||||
return tfsdk.State{Schema: s, Raw: tftypes.NewValue(s.Type().TerraformType(ctx), nil)}
|
||||
}
|
||||
|
||||
ruleType := resources.FirewallRulesValue{}
|
||||
rule := resources.NewFirewallRulesValueMust(ruleType.AttributeTypes(ctx), map[string]attr.Value{
|
||||
"description": types.StringNull(),
|
||||
"action": types.StringValue("accept"),
|
||||
"protocol": types.StringValue("icmp"),
|
||||
"destination_addresses": types.ListValueMust(types.StringType, []attr.Value{types.StringValue("10.0.0.1")}),
|
||||
"destination_ports": types.ListUnknown(types.StringType),
|
||||
"source_addresses": types.ListValueMust(types.StringType, []attr.Value{types.StringValue("10.0.0.0/8")}),
|
||||
})
|
||||
model := serverFirewallRulesResourceModel{}
|
||||
model.ServerId = types.Int64Value(1)
|
||||
model.FirewallRules = types.ListValueMust(ruleType.Type(ctx), []attr.Value{rule})
|
||||
|
||||
plan := tfsdk.Plan{Schema: s, Raw: tftypes.NewValue(s.Type().TerraformType(ctx), nil)}
|
||||
if diags := plan.Set(ctx, &model); diags.HasError() {
|
||||
t.Fatal(diags)
|
||||
}
|
||||
|
||||
createResp := resource.CreateResponse{State: emptyState()}
|
||||
r.Create(ctx, resource.CreateRequest{Plan: plan}, &createResp)
|
||||
if createResp.Diagnostics.HasError() {
|
||||
t.Fatal(createResp.Diagnostics)
|
||||
}
|
||||
var ports types.List
|
||||
createResp.State.GetAttribute(ctx, path.Root("firewall_rules").AtListIndex(0).AtName("destination_ports"), &ports)
|
||||
if !ports.IsNull() {
|
||||
t.Fatalf("create: expected null destination_ports, got %s", ports)
|
||||
}
|
||||
|
||||
updateResp := resource.UpdateResponse{State: emptyState()}
|
||||
r.Update(ctx, resource.UpdateRequest{Plan: plan}, &updateResp)
|
||||
if updateResp.Diagnostics.HasError() {
|
||||
t.Fatal(updateResp.Diagnostics)
|
||||
}
|
||||
updateResp.State.GetAttribute(ctx, path.Root("firewall_rules").AtListIndex(0).AtName("destination_ports"), &ports)
|
||||
if !ports.IsNull() {
|
||||
t.Fatalf("update: expected null destination_ports, got %s", ports)
|
||||
}
|
||||
|
||||
readResp := resource.ReadResponse{State: createResp.State}
|
||||
r.Read(ctx, resource.ReadRequest{State: createResp.State}, &readResp)
|
||||
if readResp.Diagnostics.HasError() {
|
||||
t.Fatal(readResp.Diagnostics)
|
||||
}
|
||||
readResp.State.GetAttribute(ctx, path.Root("firewall_rules").AtListIndex(0).AtName("destination_ports"), &ports)
|
||||
if !ports.IsNull() {
|
||||
t.Fatalf("read: expected null destination_ports, got %s", ports)
|
||||
}
|
||||
}
|
||||
@@ -1361,28 +1361,36 @@ func (r *serverResource) ImportState(
|
||||
resp.Diagnostics.Append(diags...)
|
||||
}
|
||||
|
||||
var (
|
||||
serverActionPollInterval = 5 * time.Second
|
||||
serverActionTimeout = 20 * time.Minute
|
||||
)
|
||||
|
||||
func (r *serverResource) waitForServerAction(ctx context.Context, serverId int64, actionId int64) error {
|
||||
if _, ok := ctx.Deadline(); !ok {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ctx, serverActionTimeout)
|
||||
defer cancel()
|
||||
}
|
||||
|
||||
var lastReadyResp *binarylane.GetServersServerIdActionsActionIdResponse
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
if lastReadyResp == nil {
|
||||
return fmt.Errorf("timed out waiting for server action: server_id=%d, action_id=%d", serverId, actionId)
|
||||
} else {
|
||||
return fmt.Errorf("timed out waiting for server action: server_id=%d, action_id=%d, last response was status=%s, body: %s",
|
||||
serverId, actionId, lastReadyResp.Status(), lastReadyResp.Body)
|
||||
readyResp, err := r.bc.client.GetServersServerIdActionsActionIdWithResponse(ctx, serverId, actionId)
|
||||
if err != nil && ctx.Err() == nil {
|
||||
return fmt.Errorf("unexpected error waiting for server action: server_id=%d, action_id=%d, error: %w", serverId, actionId, err)
|
||||
}
|
||||
if err == nil {
|
||||
if readyResp.StatusCode() == http.StatusNotFound {
|
||||
return fmt.Errorf("server action not found: server_id=%d, action_id=%d, body: %s", serverId, actionId, readyResp.Body)
|
||||
}
|
||||
default:
|
||||
readyResp, err := r.bc.client.GetServersServerIdActionsActionIdWithResponse(ctx, serverId, actionId)
|
||||
if err != nil {
|
||||
return fmt.Errorf("unexpected error waiting for server action: server_id=%d, action_id=%d, error: %w", serverId, actionId, err)
|
||||
}
|
||||
if readyResp.StatusCode() == http.StatusOK && readyResp.JSON200.Action.Status == binarylane.Errored {
|
||||
return fmt.Errorf("server action failed to with error: server_id=%d, action_id=%d, error: %s", serverId, actionId, readyResp.Body)
|
||||
}
|
||||
if readyResp.StatusCode() == http.StatusOK && readyResp.JSON200.Action.CompletedAt != nil {
|
||||
return nil
|
||||
if readyResp.StatusCode() == http.StatusOK {
|
||||
switch {
|
||||
case readyResp.JSON200.Action.Status == binarylane.Errored:
|
||||
return fmt.Errorf("server action failed to with error: server_id=%d, action_id=%d, error: %s", serverId, actionId, readyResp.Body)
|
||||
case readyResp.JSON200.Action.Status == binarylane.Completed, readyResp.JSON200.Action.CompletedAt != nil:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
lastReadyResp = readyResp
|
||||
tflog.Debug(ctx,
|
||||
@@ -1391,7 +1399,16 @@ func (r *serverResource) waitForServerAction(ctx context.Context, serverId int64
|
||||
),
|
||||
)
|
||||
}
|
||||
time.Sleep(time.Second * 5)
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
if lastReadyResp == nil {
|
||||
return fmt.Errorf("timed out waiting for server action: server_id=%d, action_id=%d", serverId, actionId)
|
||||
}
|
||||
return fmt.Errorf("timed out waiting for server action: server_id=%d, action_id=%d, last response was status=%s, body: %s",
|
||||
serverId, actionId, lastReadyResp.Status(), lastReadyResp.Body)
|
||||
case <-time.After(serverActionPollInterval):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"terraform-provider-binarylane/internal/binarylane"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/int64validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
|
||||
@@ -262,17 +263,40 @@ func (r *serverReverseNameResource) changeReverseName(ctx context.Context, serve
|
||||
if actionResp.StatusCode() != http.StatusOK && actionResp.StatusCode() != http.StatusAccepted {
|
||||
return fmt.Errorf("unexpected HTTP status code changing reverse name for server: server_id=%d, details: %s", serverId, actionResp.Body)
|
||||
}
|
||||
// 202 Accepted carries no action ID to poll
|
||||
if actionResp.JSON200 == nil {
|
||||
// The change_reverse_name action can stay unresolvable, so wait for the result on the server instead
|
||||
if reverseName == nil {
|
||||
return nil
|
||||
}
|
||||
return r.waitForReverseName(ctx, serverId, ipv4Address, *reverseName)
|
||||
}
|
||||
|
||||
sr := serverResource{bc: r.bc}
|
||||
if err := sr.waitForServerAction(ctx, serverId, actionResp.JSON200.Action.Id); err != nil {
|
||||
return fmt.Errorf("error changing reverse name: %w", err)
|
||||
func (r *serverReverseNameResource) waitForReverseName(ctx context.Context, serverId int64, ipv4Address string, want string) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, serverActionTimeout)
|
||||
defer cancel()
|
||||
|
||||
var last string
|
||||
for {
|
||||
serverResp, err := r.bc.client.GetServersServerIdWithResponse(ctx, serverId)
|
||||
if err == nil && serverResp.StatusCode() == http.StatusOK {
|
||||
for _, n := range serverResp.JSON200.Server.Networks.V4 {
|
||||
if n.IpAddress != ipv4Address {
|
||||
continue
|
||||
}
|
||||
if n.ReverseName != nil {
|
||||
if *n.ReverseName == want {
|
||||
return nil
|
||||
}
|
||||
last = *n.ReverseName
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return fmt.Errorf("timed out waiting for reverse name: server_id=%d, ipv4_address=%s, want=%q, last=%q", serverId, ipv4Address, want, last)
|
||||
case <-time.After(serverActionPollInterval):
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func formatServerReverseNameId(serverId int64, ipv4Address string) string {
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"terraform-provider-binarylane/internal/binarylane"
|
||||
|
||||
@@ -40,8 +41,6 @@ func TestServerReverseNameResourceUnit(t *testing.T) {
|
||||
if postStatus == http.StatusOK {
|
||||
_, _ = w.Write([]byte(`{"action":{"id":9,"status":"in-progress"}}`))
|
||||
}
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/servers/1/actions/9":
|
||||
_, _ = w.Write([]byte(`{"action":{"id":9,"status":"completed","completed_at":"2026-01-01T00:00:00Z"}}`))
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/servers/1":
|
||||
if !serverFound {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
@@ -120,6 +119,7 @@ func TestServerReverseNameResourceUnit(t *testing.T) {
|
||||
t.Fatal("read: expected state removed when server is 404")
|
||||
}
|
||||
|
||||
serverFound, serverIp, serverName = true, "203.0.113.7", "ptr.example.com"
|
||||
postStatus = http.StatusAccepted
|
||||
updateResp := resource.UpdateResponse{State: emptyState()}
|
||||
r.Update(ctx, resource.UpdateRequest{Plan: plan, State: state}, &updateResp)
|
||||
@@ -139,3 +139,84 @@ func TestServerReverseNameResourceUnit(t *testing.T) {
|
||||
t.Fatalf("delete: unexpected request body %v", lastBody)
|
||||
}
|
||||
}
|
||||
|
||||
// The change_reverse_name action never resolves while the PTR is already applied on the server.
|
||||
func TestServerReverseNameCreateStuckActionUnit(t *testing.T) {
|
||||
serverActionPollInterval = time.Millisecond
|
||||
t.Cleanup(func() { serverActionPollInterval = 5 * time.Second })
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
serverGets := 0
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch {
|
||||
case r.Method == http.MethodPost && r.URL.Path == "/servers/1/actions":
|
||||
_, _ = w.Write([]byte(`{"action":{"id":9,"status":"in-progress"}}`))
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/servers/1/actions/9":
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/servers/1":
|
||||
serverGets++
|
||||
name := "default.example.net"
|
||||
if serverGets > 2 {
|
||||
name = "ptr.example.com"
|
||||
}
|
||||
_, _ = fmt.Fprintf(w, `{"server":{"id":1,"networks":{"v4":[{"ip_address":"203.0.113.7","type":"public","reverse_name":%q}]}}}`, name)
|
||||
default:
|
||||
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
|
||||
w.WriteHeader(http.StatusTeapot)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
client, err := binarylane.NewClientWithConfig(srv.URL, "test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := &serverReverseNameResource{bc: &BinarylaneClient{client: client}}
|
||||
want := "ptr.example.com"
|
||||
if err := r.changeReverseName(ctx, 1, "203.0.113.7", &want); err != nil {
|
||||
t.Fatalf("create must finish once the server reports the reverse name: %v", err)
|
||||
}
|
||||
if serverGets != 3 {
|
||||
t.Fatalf("expected to poll the server until the reverse name applied, got %d GETs", serverGets)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitForServerActionUnit(t *testing.T) {
|
||||
serverActionPollInterval = time.Millisecond
|
||||
t.Cleanup(func() { serverActionPollInterval = 5 * time.Second })
|
||||
|
||||
for name, tc := range map[string]struct {
|
||||
status int
|
||||
body string
|
||||
wantErr bool
|
||||
}{
|
||||
"completed_at set": {http.StatusOK, `{"action":{"id":9,"status":"in-progress","completed_at":"2026-01-01T00:00:00Z"}}`, false},
|
||||
"completed status only": {http.StatusOK, `{"action":{"id":9,"status":"completed"}}`, false},
|
||||
"errored": {http.StatusOK, `{"action":{"id":9,"status":"errored"}}`, true},
|
||||
"not found": {http.StatusNotFound, `{"message":"Action not found."}`, true},
|
||||
"in progress until timeout": {http.StatusOK, `{"action":{"id":9,"status":"in-progress"}}`, true},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(tc.status)
|
||||
_, _ = w.Write([]byte(tc.body))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
client, err := binarylane.NewClientWithConfig(srv.URL, "test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sr := serverResource{bc: &BinarylaneClient{client: client}}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := sr.waitForServerAction(ctx, 1, 9); (err != nil) != tc.wantErr {
|
||||
t.Fatalf("wantErr=%v, got %v", tc.wantErr, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user