Compare commits

..

7 Commits

Author SHA1 Message Date
benvin bc13e7372d Merge pull request 'resource_remote: add mirrorlist attribute (rpm/deb/apk remotes)' (#18) from benvin/mirrorlist into main
ci/woodpecker/tag/release Pipeline was successful
Reviewed-on: #18
2026-08-13 17:24:58 +10:00
unkin-agent cd49af0f94 go.mod: promote terraform-plugin-go to a direct dependency
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
The mirrorlist ValidateConfig test imports terraform-plugin-go/tftypes
directly to build a tfsdk.Config, so `go mod tidy` moves it from an
indirect to a direct require. Commit the tidied go.mod so the CI
go-mod-tidy pre-commit hook is green.
2026-08-13 16:22:29 +10:00
unkin-agent 9ed7f07463 resource_remote: add mirrorlist attribute (rpm/deb/apk remotes)
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline failed
Expose the artifactapi remotes API's new mirrorlist field so users can
configure extra upstream mirror base URLs. The API load-balances
base_url + mirrorlist with failover.

- Add optional mirrorlist list attribute to the remote resource schema
  and the remote data source (read-only).
- Wire it end-to-end: TF model, wire model (json mirrorlist,omitempty),
  modelToAPI/apiToModel, and preserve null/empty list semantics to avoid
  plan churn.
- Scope to rpm/deb/alpine via ValidateConfig (plan-time error on other
  remote types); API 400 is the backstop.
- Docs + rpm example; unit tests for round-trip, null handling, and the
  type-scoping validation.
2026-08-13 16:16:49 +10:00
benvin 0879921398 Merge pull request 'Add artifactapi_remote_github_alpine resource' (#17) from benvin/apk-github into main
ci/woodpecker/tag/release Pipeline was successful
Reviewed-on: #17
2026-08-12 20:49:57 +10:00
unkin-agent 719b0dd502 Add artifactapi_remote_github_alpine resource
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
Adds the metadata-only Alpine/apk analog of the github_deb/github_rpm
remotes: exposes a GitHub repo's release .apk assets as an apk repository
(synthesized APKINDEX) without precaching, redirecting downloads to a
backing releases_remote.

- register newRemoteResource("github_alpine") in provider Resources()
- add NewRemoteGitHubAlpine convenience ctor
- extend provider/metadata/ctor table tests + bump resource count to 22
- document github_alpine remote type in README
- add examples/resources/artifactapi_remote_github_alpine/main.tf
2026-08-12 20:42:10 +10:00
benvin 8d2e0ef27d Merge pull request 'Add artifactapi_local_alpine resource' (#16) from benvin/apk-local into main
Reviewed-on: #16
2026-08-12 20:41:03 +10:00
unkin-agent cb1110c723 Add artifactapi_local_alpine resource
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
Adds a local Alpine/apk repository resource mirroring the existing
artifactapi_local_deb and artifactapi_local_rpm locals, so Alpine
package registries can be managed directly via Terraform.

- add localAlpineResource (PackageType alpine, RepoType local) with
  CRUD + import passthrough and model<->API mappers
- register NewLocalAlpineResource in provider Resources()
- bump provider_test resource count to 21 and expected type list
- add local unit tests and README/example entries
2026-08-12 00:52:33 +10:00
13 changed files with 563 additions and 9 deletions
+38 -2
View File
@@ -65,6 +65,7 @@ Available resource types:
- `artifactapi_remote_goproxy`
- `artifactapi_remote_github_rpm`
- `artifactapi_remote_github_deb`
- `artifactapi_remote_github_alpine`
#### Common Attributes
@@ -89,6 +90,27 @@ Available resource types:
| `upstream_tls_timeout` | No | `0` | Upstream TLS handshake timeout in seconds (0 = server default) |
| `upstream_response_header_timeout` | No | `0` | Upstream response-header timeout in seconds (0 = server default) |
#### rpm / deb / alpine-specific Attributes
| Attribute | Default | Description |
|--------------|---------|-------------------------------------------------------------------------------------------------|
| `mirrorlist` | | Extra upstream mirror base URLs. Requests are load-balanced with failover across `base_url` + `mirrorlist`. |
Only valid on the `artifactapi_remote_rpm`, `artifactapi_remote_deb`, and
`artifactapi_remote_alpine` resources. Setting it on any other remote type is
rejected at plan time.
```hcl
resource "artifactapi_remote_rpm" "epel" {
name = "epel-9"
base_url = "https://download.example.com/pub/epel/9/Everything/x86_64"
mirrorlist = [
"https://mirror-a.example.net/epel/9/Everything/x86_64",
"https://mirror-b.example.org/epel/9/Everything/x86_64",
]
}
```
#### Docker-specific Attributes
| Attribute | Default | Description |
@@ -96,11 +118,11 @@ Available resource types:
| `ban_tags_enabled` | `false` | Enable tag banning |
| `ban_tags` | | List of tags to ban |
#### Terraform / github_rpm / github_deb-specific Attributes
#### Terraform / github_rpm / github_deb / github_alpine-specific Attributes
| Attribute | Default | Description |
|-------------------|---------|----------------------------------------------------------|
| `releases_remote` | `""` | Name of a backend remote that serves the download bytes. Terraform uses it for download URL rewriting; `github_rpm`/`github_deb` 302-redirect `.rpm`/`.deb` downloads to it. |
| `releases_remote` | `""` | Name of a backend remote that serves the download bytes. Terraform uses it for download URL rewriting; `github_rpm`/`github_deb`/`github_alpine` 302-redirect `.rpm`/`.deb`/`.apk` downloads to it. |
#### github_rpm-specific notes
@@ -125,6 +147,19 @@ generic `github.com` remote that streams the `.deb` bytes; `.deb` downloads
higher API rate limits. See
`examples/resources/artifactapi_remote_github_deb/main.tf`.
#### github_alpine-specific notes
`artifactapi_remote_github_alpine` is the Alpine/apk analog of `github_rpm`: it
exposes a GitHub repo's release `.apk` assets as an `apk` repository, synthesizing
the apk index (`APKINDEX.tar.gz`) from release metadata without precaching
packages. Set `base_url` to the releases API root
(`https://api.github.com/repos/{owner}/{repo}`) and `releases_remote` to a
generic `github.com` remote that streams the `.apk` bytes; `.apk` downloads
302-redirect there. `patterns` filters which release assets become packages
(regex on asset filename). `password` may hold a token for private repos or
higher API rate limits. See
`examples/resources/artifactapi_remote_github_alpine/main.tf`.
#### Example
```hcl
@@ -155,6 +190,7 @@ Available resource types:
- `artifactapi_local_pypi`
- `artifactapi_local_rpm`
- `artifactapi_local_deb`
- `artifactapi_local_alpine`
- `artifactapi_local_terraform`
Each takes just `name` (required, forces replacement) and an optional
@@ -0,0 +1,4 @@
resource "artifactapi_local_alpine" "internal" {
name = "alpine-internal"
description = "Internal Alpine package repository"
}
@@ -0,0 +1,44 @@
terraform {
required_providers {
artifactapi = {
source = "git.unkin.net/unkin/artifactapi"
version = "0.0.1"
}
}
}
provider "artifactapi" {
endpoint = "https://artifactapi.example.com"
}
# Backend generic remote that serves the actual .apk bytes from github.com.
# Its patterns must allowlist the target repo's release-download assets.
resource "artifactapi_remote_generic" "github" {
name = "github"
base_url = "https://github.com"
patterns = [
"goodtune/ghp/releases/download/.*\\.apk$",
]
}
# Metadata-only remote: scans goodtune/ghp releases for .apk assets and serves a
# synthesized apk repo (APKINDEX). Packages are never precached; downloads
# 302-redirect to the "github" remote above.
resource "artifactapi_remote_github_alpine" "goodtune_ghp" {
name = "goodtune-ghp"
base_url = "https://api.github.com/repos/goodtune/ghp"
description = "goodtune/ghp GitHub releases as an apk repo"
releases_remote = artifactapi_remote_generic.github.name
mutable_ttl = 3600
# Optional: restrict which release assets become packages.
patterns = [
".*_x86_64\\.apk$",
".*_noarch\\.apk$",
]
# Optional: token for private repos / higher GitHub API rate limits.
# password = var.github_token
}
@@ -18,6 +18,13 @@ resource "artifactapi_remote_rpm" "almalinux" {
base_url = "https://gsl-syd.mm.fcix.net/almalinux"
description = "AlmaLinux RPM package repository"
# Extra mirrors; requests are load-balanced with failover across
# base_url + mirrorlist (rpm/deb/alpine remotes only).
mirrorlist = [
"https://mirror.aarnet.edu.au/pub/almalinux",
"https://mirror.realcompute.io/almalinux",
]
immutable_ttl = 0
mutable_ttl = 7200
}
+4 -2
View File
@@ -2,7 +2,10 @@ module git.unkin.net/unkin/terraform-provider-artifactapi
go 1.25.9
require github.com/hashicorp/terraform-plugin-framework v1.15.0
require (
github.com/hashicorp/terraform-plugin-framework v1.15.0
github.com/hashicorp/terraform-plugin-go v0.28.0
)
require (
github.com/fatih/color v1.13.0 // indirect
@@ -10,7 +13,6 @@ require (
github.com/hashicorp/go-hclog v1.5.0 // indirect
github.com/hashicorp/go-plugin v1.6.3 // indirect
github.com/hashicorp/go-uuid v1.0.3 // indirect
github.com/hashicorp/terraform-plugin-go v0.28.0 // indirect
github.com/hashicorp/terraform-plugin-log v0.9.0 // indirect
github.com/hashicorp/terraform-registry-address v0.2.5 // indirect
github.com/hashicorp/terraform-svchost v0.1.1 // indirect
+3
View File
@@ -30,6 +30,7 @@ func (d *remoteDataSource) Schema(_ context.Context, _ datasource.SchemaRequest,
"name": schema.StringAttribute{Required: true},
"package_type": schema.StringAttribute{Computed: true},
"base_url": schema.StringAttribute{Computed: true},
"mirrorlist": schema.ListAttribute{Computed: true, ElementType: types.StringType},
"description": schema.StringAttribute{Computed: true},
"immutable_ttl": schema.Int64Attribute{Computed: true},
"mutable_ttl": schema.Int64Attribute{Computed: true},
@@ -57,6 +58,7 @@ type remoteDataSourceModel struct {
Name types.String `tfsdk:"name"`
PackageType types.String `tfsdk:"package_type"`
BaseURL types.String `tfsdk:"base_url"`
Mirrorlist types.List `tfsdk:"mirrorlist"`
Description types.String `tfsdk:"description"`
ImmutableTTL types.Int64 `tfsdk:"immutable_ttl"`
MutableTTL types.Int64 `tfsdk:"mutable_ttl"`
@@ -107,6 +109,7 @@ func (d *remoteDataSource) Read(ctx context.Context, req datasource.ReadRequest,
Name: types.StringValue(remote.Name),
PackageType: types.StringValue(remote.PackageType),
BaseURL: types.StringValue(remote.BaseURL),
Mirrorlist: stringsToList(ctx, remote.Mirrorlist),
Description: types.StringValue(remote.Description),
ImmutableTTL: types.Int64Value(remote.ImmutableTTL),
MutableTTL: types.Int64Value(remote.MutableTTL),
+1
View File
@@ -5,6 +5,7 @@ type remoteAPI struct {
PackageType string `json:"package_type"`
RepoType string `json:"repo_type,omitempty"`
BaseURL string `json:"base_url"`
Mirrorlist []string `json:"mirrorlist,omitempty"`
Description string `json:"description,omitempty"`
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
+2
View File
@@ -70,11 +70,13 @@ func (p *ArtifactAPIProvider) Resources(_ context.Context) []func() resource.Res
newRemoteResource("goproxy"),
newRemoteResource("github_rpm"),
newRemoteResource("github_deb"),
newRemoteResource("github_alpine"),
NewVirtualResource,
NewLocalTerraformResource,
NewLocalPyPIResource,
NewLocalRPMResource,
NewLocalDebResource,
NewLocalAlpineResource,
NewLocalDockerResource,
NewLocalGenericResource,
}
+4 -2
View File
@@ -66,8 +66,8 @@ func TestProvider_Resources(t *testing.T) {
p := &ArtifactAPIProvider{version: "1.0.0"}
resources := p.Resources(context.Background())
// 13 remote resource types + 1 virtual + local_terraform/pypi/rpm/deb/docker/generic = 20
expectedCount := 20
// 13 remote resource types + 1 virtual + local_terraform/pypi/rpm/deb/alpine/docker/generic = 21
expectedCount := 22
if len(resources) != expectedCount {
t.Fatalf("expected %d resources, got %d", expectedCount, len(resources))
}
@@ -109,11 +109,13 @@ func TestProvider_Resources_ContainsExpectedTypes(t *testing.T) {
"artifactapi_remote_goproxy",
"artifactapi_remote_github_rpm",
"artifactapi_remote_github_deb",
"artifactapi_remote_github_alpine",
"artifactapi_virtual",
"artifactapi_local_terraform",
"artifactapi_local_pypi",
"artifactapi_local_rpm",
"artifactapi_local_deb",
"artifactapi_local_alpine",
"artifactapi_local_docker",
"artifactapi_local_generic",
}
+164
View File
@@ -0,0 +1,164 @@
package provider
import (
"context"
"fmt"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var (
_ resource.Resource = &localAlpineResource{}
_ resource.ResourceWithImportState = &localAlpineResource{}
)
type localAlpineResource struct {
client *apiClient
}
type localAlpineResourceModel struct {
Name types.String `tfsdk:"name"`
Description types.String `tfsdk:"description"`
}
func NewLocalAlpineResource() resource.Resource {
return &localAlpineResource{}
}
func (r *localAlpineResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_local_alpine"
}
func (r *localAlpineResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Manages a local ArtifactAPI Alpine repository for hosting Alpine/apk packages directly.",
Attributes: map[string]schema.Attribute{
"name": schema.StringAttribute{
Description: "Unique name of the local Alpine repository.",
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"description": schema.StringAttribute{
Description: "Human-readable description.",
Optional: true,
Computed: true,
Default: stringdefault.StaticString(""),
},
},
}
}
func (r *localAlpineResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
client, ok := req.ProviderData.(*apiClient)
if !ok {
resp.Diagnostics.AddError("unexpected provider data type", fmt.Sprintf("got %T", req.ProviderData))
return
}
r.client = client
}
func (r *localAlpineResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan localAlpineResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
api := localAlpineModelToAPI(plan)
api.ManagedBy = "terraform"
var created remoteAPI
if err := r.client.post(ctx, "/api/v2/remotes", api, &created); err != nil {
resp.Diagnostics.AddError("create local alpine failed", err.Error())
return
}
state := localAlpineAPIToModel(created)
resp.Diagnostics.Append(resp.State.Set(ctx, state)...)
}
func (r *localAlpineResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state localAlpineResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
var remote remoteAPI
err := r.client.get(ctx, "/api/v2/remotes/"+state.Name.ValueString(), &remote)
if err != nil {
if isNotFound(err) {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError("read local alpine failed", err.Error())
return
}
newState := localAlpineAPIToModel(remote)
resp.Diagnostics.Append(resp.State.Set(ctx, newState)...)
}
func (r *localAlpineResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan localAlpineResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
api := localAlpineModelToAPI(plan)
api.ManagedBy = "terraform"
var updated remoteAPI
if err := r.client.put(ctx, "/api/v2/remotes/"+plan.Name.ValueString(), api, &updated); err != nil {
resp.Diagnostics.AddError("update local alpine failed", err.Error())
return
}
state := localAlpineAPIToModel(updated)
resp.Diagnostics.Append(resp.State.Set(ctx, state)...)
}
func (r *localAlpineResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state localAlpineResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
if err := r.client.del(ctx, "/api/v2/remotes/"+state.Name.ValueString()); err != nil {
resp.Diagnostics.AddError("delete local alpine failed", err.Error())
return
}
}
func (r *localAlpineResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
resource.ImportStatePassthroughID(ctx, path.Root("name"), req, resp)
}
func localAlpineModelToAPI(m localAlpineResourceModel) remoteAPI {
return remoteAPI{
Name: m.Name.ValueString(),
PackageType: "alpine",
RepoType: "local",
Description: m.Description.ValueString(),
}
}
func localAlpineAPIToModel(api remoteAPI) localAlpineResourceModel {
return localAlpineResourceModel{
Name: types.StringValue(api.Name),
Description: types.StringValue(api.Description),
}
}
@@ -0,0 +1,125 @@
package provider
import (
"context"
"testing"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/types"
)
func TestLocalAlpineModelToAPI(t *testing.T) {
model := localAlpineResourceModel{
Name: types.StringValue("alpine-internal"),
Description: types.StringValue("Internal Alpine repository"),
}
api := localAlpineModelToAPI(model)
if api.Name != "alpine-internal" {
t.Errorf("Name: expected alpine-internal, got %s", api.Name)
}
if api.PackageType != "alpine" {
t.Errorf("PackageType: expected alpine, got %s", api.PackageType)
}
if api.RepoType != "local" {
t.Errorf("RepoType: expected local, got %s", api.RepoType)
}
if api.Description != "Internal Alpine repository" {
t.Errorf("Description: expected 'Internal Alpine repository', got %s", api.Description)
}
}
func TestLocalAlpineModelToAPI_EmptyDescription(t *testing.T) {
model := localAlpineResourceModel{
Name: types.StringValue("alpine-empty"),
Description: types.StringValue(""),
}
api := localAlpineModelToAPI(model)
if api.Name != "alpine-empty" {
t.Errorf("Name: expected alpine-empty, got %s", api.Name)
}
if api.Description != "" {
t.Errorf("Description: expected empty string, got %s", api.Description)
}
if api.PackageType != "alpine" {
t.Errorf("PackageType: expected alpine, got %s", api.PackageType)
}
if api.RepoType != "local" {
t.Errorf("RepoType: expected local, got %s", api.RepoType)
}
}
func TestLocalAlpineAPIToModel(t *testing.T) {
api := remoteAPI{
Name: "alpine-internal",
PackageType: "alpine",
RepoType: "local",
Description: "Internal Alpine repository",
ManagedBy: "terraform",
}
model := localAlpineAPIToModel(api)
if model.Name.ValueString() != "alpine-internal" {
t.Errorf("Name: expected alpine-internal, got %s", model.Name.ValueString())
}
if model.Description.ValueString() != "Internal Alpine repository" {
t.Errorf("Description: expected 'Internal Alpine repository', got %s", model.Description.ValueString())
}
}
func TestLocalAlpineRoundTrip(t *testing.T) {
original := localAlpineResourceModel{
Name: types.StringValue("roundtrip-alpine"),
Description: types.StringValue("Round trip test"),
}
api := localAlpineModelToAPI(original)
result := localAlpineAPIToModel(api)
if result.Name.ValueString() != original.Name.ValueString() {
t.Errorf("Name: expected %s, got %s", original.Name.ValueString(), result.Name.ValueString())
}
if result.Description.ValueString() != original.Description.ValueString() {
t.Errorf("Description: expected %s, got %s", original.Description.ValueString(), result.Description.ValueString())
}
}
func TestLocalAlpineResource_Metadata(t *testing.T) {
r := NewLocalAlpineResource()
req := resource.MetadataRequest{ProviderTypeName: "artifactapi"}
var resp resource.MetadataResponse
r.Metadata(context.Background(), req, &resp)
if resp.TypeName != "artifactapi_local_alpine" {
t.Errorf("expected artifactapi_local_alpine, got %s", resp.TypeName)
}
}
func TestLocalAlpineResource_Schema(t *testing.T) {
r := NewLocalAlpineResource()
req := resource.SchemaRequest{}
var resp resource.SchemaResponse
r.Schema(context.Background(), req, &resp)
expectedAttrs := []string{"name", "description"}
for _, attr := range expectedAttrs {
if _, ok := resp.Schema.Attributes[attr]; !ok {
t.Errorf("missing expected attribute: %s", attr)
}
}
if len(resp.Schema.Attributes) != len(expectedAttrs) {
t.Errorf("expected %d attributes, got %d", len(expectedAttrs), len(resp.Schema.Attributes))
}
}
func TestNewLocalAlpineResource_Type(t *testing.T) {
r := NewLocalAlpineResource()
_, ok := r.(*localAlpineResource)
if !ok {
t.Error("expected *localAlpineResource")
}
}
+38 -3
View File
@@ -16,10 +16,15 @@ import (
)
var (
_ resource.Resource = &remoteResource{}
_ resource.ResourceWithImportState = &remoteResource{}
_ resource.Resource = &remoteResource{}
_ resource.ResourceWithImportState = &remoteResource{}
_ resource.ResourceWithValidateConfig = &remoteResource{}
)
// mirrorlistPackageTypes are the remote package types for which the mirrorlist
// attribute is valid; the API load-balances base_url + mirrorlist for these.
var mirrorlistPackageTypes = map[string]bool{"rpm": true, "deb": true, "alpine": true}
type remoteResource struct {
client *apiClient
packageType string
@@ -28,6 +33,7 @@ type remoteResource struct {
type remoteResourceModel struct {
Name types.String `tfsdk:"name"`
BaseURL types.String `tfsdk:"base_url"`
Mirrorlist types.List `tfsdk:"mirrorlist"`
Description types.String `tfsdk:"description"`
Username types.String `tfsdk:"username"`
Password types.String `tfsdk:"password"`
@@ -69,6 +75,9 @@ func NewRemoteTerraform() resource.Resource { return &remoteResource{packageType
func NewRemoteGoProxy() resource.Resource { return &remoteResource{packageType: "goproxy"} }
func NewRemoteGitHubRPM() resource.Resource { return &remoteResource{packageType: "github_rpm"} }
func NewRemoteGitHubDeb() resource.Resource { return &remoteResource{packageType: "github_deb"} }
func NewRemoteGitHubAlpine() resource.Resource {
return &remoteResource{packageType: "github_alpine"}
}
func (r *remoteResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_remote_" + r.packageType
@@ -87,6 +96,11 @@ func (r *remoteResource) Schema(_ context.Context, _ resource.SchemaRequest, res
Description: "Upstream repository base URL.",
Required: true,
},
"mirrorlist": schema.ListAttribute{
Description: "Extra upstream mirror base URLs; only valid on remote rpm/deb/apk (alpine) repos. Requests are load-balanced with failover across base_url + mirrorlist.",
Optional: true,
ElementType: types.StringType,
},
"description": schema.StringAttribute{
Optional: true, Computed: true, Default: stringdefault.StaticString(""),
},
@@ -148,7 +162,7 @@ func (r *remoteResource) Schema(_ context.Context, _ resource.SchemaRequest, res
ElementType: types.StringType,
},
"releases_remote": schema.StringAttribute{
Description: "Name of a backend remote that serves the actual download bytes. Used by the terraform remote (download URL rewriting) and the github_rpm/github_deb remotes (302 redirect of .rpm/.deb downloads to a generic github.com remote).",
Description: "Name of a backend remote that serves the actual download bytes. Used by the terraform remote (download URL rewriting) and the github_rpm/github_deb/github_alpine remotes (302 redirect of .rpm/.deb/.apk downloads to a generic github.com remote).",
Optional: true, Computed: true, Default: stringdefault.StaticString(""),
},
"upstream_dial_timeout": schema.Int64Attribute{
@@ -265,7 +279,26 @@ func (r *remoteResource) ImportState(ctx context.Context, req resource.ImportSta
resource.ImportStatePassthroughID(ctx, path.Root("name"), req, resp)
}
func (r *remoteResource) ValidateConfig(ctx context.Context, req resource.ValidateConfigRequest, resp *resource.ValidateConfigResponse) {
var config remoteResourceModel
resp.Diagnostics.Append(req.Config.Get(ctx, &config)...)
if resp.Diagnostics.HasError() {
return
}
if config.Mirrorlist.IsNull() || config.Mirrorlist.IsUnknown() {
return
}
if !mirrorlistPackageTypes[r.packageType] {
resp.Diagnostics.AddAttributeError(
path.Root("mirrorlist"),
"mirrorlist not supported for this remote type",
fmt.Sprintf("mirrorlist is only valid on remote rpm/deb/apk (alpine) repos, not %q remotes.", r.packageType),
)
}
}
func reconcileOptionalLists(prior, current *remoteResourceModel) {
current.Mirrorlist = preserveListNullEmptySemantics(prior.Mirrorlist, current.Mirrorlist)
current.Patterns = preserveListNullEmptySemantics(prior.Patterns, current.Patterns)
current.Blocklist = preserveListNullEmptySemantics(prior.Blocklist, current.Blocklist)
current.MutablePatterns = preserveListNullEmptySemantics(prior.MutablePatterns, current.MutablePatterns)
@@ -292,6 +325,7 @@ func (r *remoteResource) modelToAPI(ctx context.Context, m remoteResourceModel)
UpstreamTLSTimeout: m.UpstreamTLSTimeout.ValueInt64(),
UpstreamResponseHeaderTimeout: m.UpstreamResponseHeaderTimeout.ValueInt64(),
}
api.Mirrorlist = listToStrings(ctx, m.Mirrorlist)
api.Patterns = listToStrings(ctx, m.Patterns)
api.Blocklist = listToStrings(ctx, m.Blocklist)
api.MutablePatterns = listToStrings(ctx, m.MutablePatterns)
@@ -306,6 +340,7 @@ func (r *remoteResource) apiToModel(ctx context.Context, api remoteAPI) remoteRe
m := remoteResourceModel{
Name: types.StringValue(api.Name),
BaseURL: types.StringValue(api.BaseURL),
Mirrorlist: stringsToList(ctx, api.Mirrorlist),
Description: types.StringValue(api.Description),
Username: types.StringValue(api.Username),
Password: types.StringValue(api.Password),
+129
View File
@@ -5,7 +5,9 @@ import (
"testing"
"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 TestModelToAPI_FullFields(t *testing.T) {
@@ -411,6 +413,7 @@ func TestRemoteResource_Metadata(t *testing.T) {
{"npm", "artifactapi_remote_npm"},
{"github_rpm", "artifactapi_remote_github_rpm"},
{"github_deb", "artifactapi_remote_github_deb"},
{"github_alpine", "artifactapi_remote_github_alpine"},
}
for _, tt := range tests {
@@ -523,6 +526,7 @@ func TestNewRemoteResource_Constructors(t *testing.T) {
{"goproxy", func() resource.Resource { return NewRemoteGoProxy() }, "goproxy"},
{"github_rpm", func() resource.Resource { return NewRemoteGitHubRPM() }, "github_rpm"},
{"github_deb", func() resource.Resource { return NewRemoteGitHubDeb() }, "github_deb"},
{"github_alpine", func() resource.Resource { return NewRemoteGitHubAlpine() }, "github_alpine"},
}
for _, tt := range tests {
@@ -538,3 +542,128 @@ func TestNewRemoteResource_Constructors(t *testing.T) {
})
}
}
func TestModelToAPI_Mirrorlist(t *testing.T) {
ctx := context.Background()
mirrors := []string{"https://mirror-a.example.com/rpm", "https://mirror-b.example.com/rpm"}
for _, pkgType := range []string{"rpm", "deb", "alpine"} {
t.Run(pkgType, func(t *testing.T) {
r := &remoteResource{packageType: pkgType}
model := remoteResourceModel{
Name: types.StringValue("mirror-remote"),
BaseURL: types.StringValue("https://primary.example.com"),
Mirrorlist: stringsToList(ctx, mirrors),
}
api := r.modelToAPI(ctx, model)
if len(api.Mirrorlist) != 2 || api.Mirrorlist[0] != mirrors[0] || api.Mirrorlist[1] != mirrors[1] {
t.Errorf("Mirrorlist: expected %v, got %v", mirrors, api.Mirrorlist)
}
})
}
}
func TestModelToAPI_MirrorlistNull(t *testing.T) {
ctx := context.Background()
r := &remoteResource{packageType: "rpm"}
model := remoteResourceModel{
Name: types.StringValue("no-mirror"),
BaseURL: types.StringValue("https://primary.example.com"),
Mirrorlist: types.ListNull(types.StringType),
}
api := r.modelToAPI(ctx, model)
if api.Mirrorlist != nil {
t.Errorf("Mirrorlist: expected nil (omitted) for null list, got %v", api.Mirrorlist)
}
}
func TestAPIToModel_Mirrorlist(t *testing.T) {
ctx := context.Background()
r := &remoteResource{packageType: "rpm"}
mirrors := []string{"https://mirror-a.example.com/rpm", "https://mirror-b.example.com/rpm"}
// Round-trip: mirrorlist survives API -> Model -> API without churn.
api := remoteAPI{Name: "rt", PackageType: "rpm", BaseURL: "https://primary.example.com", Mirrorlist: mirrors}
model := r.apiToModel(ctx, api)
got := listToStrings(ctx, model.Mirrorlist)
if len(got) != 2 || got[0] != mirrors[0] || got[1] != mirrors[1] {
t.Errorf("Mirrorlist round-trip: expected %v, got %v", mirrors, got)
}
// nil mirrorlist maps to a null list (not empty) to avoid perpetual diff.
empty := r.apiToModel(ctx, remoteAPI{Name: "e", PackageType: "rpm", BaseURL: "https://x"})
if !empty.Mirrorlist.IsNull() {
t.Errorf("Mirrorlist: expected null for nil input, got %v", empty.Mirrorlist)
}
}
func TestRemoteResource_SchemaHasMirrorlist(t *testing.T) {
r := &remoteResource{packageType: "rpm"}
var resp resource.SchemaResponse
r.Schema(context.Background(), resource.SchemaRequest{}, &resp)
if _, ok := resp.Schema.Attributes["mirrorlist"]; !ok {
t.Fatal("missing mirrorlist attribute in schema")
}
}
// mirrorlistConfig builds a tfsdk.Config for the remote schema with every
// attribute null except mirrorlist, which is set to the given values (or null
// when values is nil).
func mirrorlistConfig(ctx context.Context, t *testing.T, r *remoteResource, values []string) tfsdk.Config {
t.Helper()
var resp resource.SchemaResponse
r.Schema(ctx, resource.SchemaRequest{}, &resp)
objType := resp.Schema.Type().TerraformType(ctx).(tftypes.Object)
attrs := make(map[string]tftypes.Value, len(objType.AttributeTypes))
for name, at := range objType.AttributeTypes {
attrs[name] = tftypes.NewValue(at, nil)
}
if values != nil {
elems := make([]tftypes.Value, len(values))
for i, v := range values {
elems[i] = tftypes.NewValue(tftypes.String, v)
}
attrs["mirrorlist"] = tftypes.NewValue(objType.AttributeTypes["mirrorlist"], elems)
}
return tfsdk.Config{Schema: resp.Schema, Raw: tftypes.NewValue(objType, attrs)}
}
func TestValidateConfig_Mirrorlist(t *testing.T) {
ctx := context.Background()
mirrors := []string{"https://mirror.example.com"}
// Supported types accept mirrorlist.
for _, pkgType := range []string{"rpm", "deb", "alpine"} {
t.Run("allowed/"+pkgType, func(t *testing.T) {
r := &remoteResource{packageType: pkgType}
var resp resource.ValidateConfigResponse
r.ValidateConfig(ctx, resource.ValidateConfigRequest{Config: mirrorlistConfig(ctx, t, r, mirrors)}, &resp)
if resp.Diagnostics.HasError() {
t.Errorf("unexpected error for %s: %v", pkgType, resp.Diagnostics.Errors())
}
})
}
// Unsupported types reject a set mirrorlist.
for _, pkgType := range []string{"docker", "pypi", "helm", "generic"} {
t.Run("rejected/"+pkgType, func(t *testing.T) {
r := &remoteResource{packageType: pkgType}
var resp resource.ValidateConfigResponse
r.ValidateConfig(ctx, resource.ValidateConfigRequest{Config: mirrorlistConfig(ctx, t, r, mirrors)}, &resp)
if !resp.Diagnostics.HasError() {
t.Errorf("expected error setting mirrorlist on %s remote", pkgType)
}
})
}
// A null mirrorlist is fine on any type.
t.Run("null-on-docker", func(t *testing.T) {
r := &remoteResource{packageType: "docker"}
var resp resource.ValidateConfigResponse
r.ValidateConfig(ctx, resource.ValidateConfigRequest{Config: mirrorlistConfig(ctx, t, r, nil)}, &resp)
if resp.Diagnostics.HasError() {
t.Errorf("unexpected error for null mirrorlist on docker: %v", resp.Diagnostics.Errors())
}
})
}