Compare commits
25 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f947f23e45 | |||
| 24c11d233a | |||
| c69c3d9f74 | |||
| bc13e7372d | |||
| cd49af0f94 | |||
| 9ed7f07463 | |||
| 0879921398 | |||
| 719b0dd502 | |||
| 8d2e0ef27d | |||
| cb1110c723 | |||
| b8c18690ef | |||
| 25b72fd1ac | |||
| 5ee3a1d3d6 | |||
| b21892217a | |||
| 2d8584f103 | |||
| b26e651d45 | |||
| c7a2416518 | |||
| 14b7c4bdcd | |||
| a232a26bf5 | |||
| 30b414141a | |||
| b149e1bf9d | |||
| f82a9900a9 | |||
| 7d7cbde0bf | |||
| 0561bae10e | |||
| 4dd290518d |
@@ -6,3 +6,13 @@ steps:
|
||||
image: golang:1.25
|
||||
commands:
|
||||
- make build
|
||||
backend_options:
|
||||
kubernetes:
|
||||
serviceAccountName: default
|
||||
resources:
|
||||
requests:
|
||||
memory: 512Mi
|
||||
cpu: 1
|
||||
limits:
|
||||
memory: 2Gi
|
||||
cpu: 2
|
||||
|
||||
+22
-1
@@ -6,6 +6,16 @@ steps:
|
||||
image: git.unkin.net/unkin/almalinux9-gobuilder:20260606
|
||||
commands:
|
||||
- make package VERSION=${CI_COMMIT_TAG}
|
||||
backend_options:
|
||||
kubernetes:
|
||||
serviceAccountName: default
|
||||
resources:
|
||||
requests:
|
||||
memory: 512Mi
|
||||
cpu: 1
|
||||
limits:
|
||||
memory: 2Gi
|
||||
cpu: 2
|
||||
|
||||
- name: upload
|
||||
image: git.unkin.net/unkin/almalinux9-base:20260606
|
||||
@@ -14,6 +24,17 @@ steps:
|
||||
VERSION=$$(echo ${CI_COMMIT_TAG} | sed 's/^v//')
|
||||
FILE="terraform-provider-artifactapi_$${VERSION}_linux_amd64.zip"
|
||||
curl -f -X PUT \
|
||||
"https://artifactapi3.k8s.syd1.au.unkin.net/api/v2/remotes/terraform-unkin/files/unkin/artifactapi/$${FILE}" \
|
||||
"https://artifactapi.k8s.syd1.au.unkin.net/api/v2/remotes/terraform-unkin/files/unkin/artifactapi/$${FILE}" \
|
||||
-H "Content-Type: application/zip" \
|
||||
--data-binary @"$${FILE}"
|
||||
depends_on: [package]
|
||||
backend_options:
|
||||
kubernetes:
|
||||
serviceAccountName: default
|
||||
resources:
|
||||
requests:
|
||||
memory: 128Mi
|
||||
cpu: 100m
|
||||
limits:
|
||||
memory: 512Mi
|
||||
cpu: 500m
|
||||
|
||||
@@ -6,8 +6,28 @@ steps:
|
||||
image: golang:1.25
|
||||
commands:
|
||||
- make lint
|
||||
backend_options:
|
||||
kubernetes:
|
||||
serviceAccountName: default
|
||||
resources:
|
||||
requests:
|
||||
memory: 512Mi
|
||||
cpu: 1
|
||||
limits:
|
||||
memory: 2Gi
|
||||
cpu: 2
|
||||
|
||||
- name: test
|
||||
image: golang:1.25
|
||||
commands:
|
||||
- make test
|
||||
backend_options:
|
||||
kubernetes:
|
||||
serviceAccountName: default
|
||||
resources:
|
||||
requests:
|
||||
memory: 512Mi
|
||||
cpu: 1
|
||||
limits:
|
||||
memory: 2Gi
|
||||
cpu: 2
|
||||
|
||||
@@ -58,10 +58,14 @@ Available resource types:
|
||||
- `artifactapi_remote_pypi`
|
||||
- `artifactapi_remote_npm`
|
||||
- `artifactapi_remote_rpm`
|
||||
- `artifactapi_remote_deb`
|
||||
- `artifactapi_remote_alpine`
|
||||
- `artifactapi_remote_puppet`
|
||||
- `artifactapi_remote_terraform`
|
||||
- `artifactapi_remote_goproxy`
|
||||
- `artifactapi_remote_github_rpm`
|
||||
- `artifactapi_remote_github_deb`
|
||||
- `artifactapi_remote_github_alpine`
|
||||
|
||||
#### Common Attributes
|
||||
|
||||
@@ -82,6 +86,32 @@ Available resource types:
|
||||
| `quarantine_enabled` | No | `false` | Enable quarantine for new artifacts |
|
||||
| `quarantine_days` | No | `3` | Days to quarantine new artifacts |
|
||||
| `stale_on_error` | No | `true` | Serve stale cache when upstream is unreachable |
|
||||
| `upstream_dial_timeout` | No | `0` | Upstream TCP connect timeout in seconds (0 = server default) |
|
||||
| `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`. |
|
||||
| `mirror_strategy` | `round_robin` | Mirror load-balancing strategy across `base_url` + `mirrorlist`. One of `round_robin` or `least_conn`. |
|
||||
|
||||
Only valid on the `artifactapi_remote_rpm`, `artifactapi_remote_deb`, and
|
||||
`artifactapi_remote_alpine` resources. Setting either 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",
|
||||
]
|
||||
mirror_strategy = "least_conn"
|
||||
}
|
||||
```
|
||||
|
||||
#### Docker-specific Attributes
|
||||
|
||||
@@ -90,11 +120,47 @@ Available resource types:
|
||||
| `ban_tags_enabled` | `false` | Enable tag banning |
|
||||
| `ban_tags` | | List of tags to ban |
|
||||
|
||||
#### Terraform-specific Attributes
|
||||
#### Terraform / github_rpm / github_deb / github_alpine-specific Attributes
|
||||
|
||||
| Attribute | Default | Description |
|
||||
|-------------------|---------|----------------------------------------------------------|
|
||||
| `releases_remote` | `""` | Name of a generic remote for download URL rewriting |
|
||||
| `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
|
||||
|
||||
`artifactapi_remote_github_rpm` exposes a GitHub repo's releases as a `dnf`/`yum`
|
||||
repository 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 `.rpm` bytes. `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_rpm/main.tf`.
|
||||
|
||||
#### github_deb-specific notes
|
||||
|
||||
`artifactapi_remote_github_deb` is the Debian/apt analog of `github_rpm`: it
|
||||
exposes a GitHub repo's release `.deb` assets as an `apt` repository, synthesizing
|
||||
the apt index (`Packages`/`Release`) 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 `.deb` bytes; `.deb` 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_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
|
||||
|
||||
@@ -115,6 +181,33 @@ resource "artifactapi_remote_docker" "dockerhub" {
|
||||
}
|
||||
```
|
||||
|
||||
### Local Resources
|
||||
|
||||
Local resources manage repositories that ArtifactAPI hosts directly (rather than
|
||||
proxying an upstream) — each is a real registry for its package type.
|
||||
|
||||
Available resource types:
|
||||
|
||||
- `artifactapi_local_docker` — a container registry (Docker Registry HTTP API V2, push and pull)
|
||||
- `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
|
||||
`description`.
|
||||
|
||||
```hcl
|
||||
resource "artifactapi_local_docker" "internal" {
|
||||
name = "docker-internal"
|
||||
description = "Internal container image registry"
|
||||
}
|
||||
```
|
||||
|
||||
Images push and pull against `<endpoint>/<name>/<image>:<tag>`, e.g.
|
||||
`docker push artifactapi.example.com/docker-internal/myapp:latest`.
|
||||
|
||||
### Virtual Resources
|
||||
|
||||
Virtual repositories merge multiple remotes of the same package type into a single endpoint.
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
resource "artifactapi_local_alpine" "internal" {
|
||||
name = "alpine-internal"
|
||||
description = "Internal Alpine package repository"
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
resource "artifactapi_local_deb" "internal" {
|
||||
name = "deb-internal"
|
||||
description = "Internal Deb package repository"
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
resource "artifactapi_local_docker" "internal" {
|
||||
name = "docker-internal"
|
||||
description = "Internal container image registry"
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
resource "artifactapi_local_generic" "rootfs_images" {
|
||||
name = "rootfs-images"
|
||||
description = "Prebuilt node rootfs tarballs (bootapi image provisioning)"
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
terraform {
|
||||
required_providers {
|
||||
artifactapi = {
|
||||
source = "git.unkin.net/unkin/artifactapi"
|
||||
version = "0.0.1"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
provider "artifactapi" {
|
||||
endpoint = "https://artifactapi.example.com"
|
||||
}
|
||||
|
||||
# Deb remote proxies a Debian/apt package repository.
|
||||
# The provider knows the index files (Release, Packages) are mutable; .deb packages are immutable.
|
||||
resource "artifactapi_remote_deb" "debian" {
|
||||
name = "debian"
|
||||
base_url = "http://deb.debian.org/debian"
|
||||
description = "Debian apt package repository"
|
||||
|
||||
immutable_ttl = 0
|
||||
mutable_ttl = 7200
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 .deb 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/.*\\.deb$",
|
||||
]
|
||||
}
|
||||
|
||||
# Metadata-only remote: scans goodtune/ghp releases for .deb assets and serves a
|
||||
# synthesized apt repo. Packages are never precached; downloads 302-redirect to
|
||||
# the "github" remote above.
|
||||
resource "artifactapi_remote_github_deb" "goodtune_ghp" {
|
||||
name = "goodtune-ghp"
|
||||
base_url = "https://api.github.com/repos/goodtune/ghp"
|
||||
description = "goodtune/ghp GitHub releases as an apt repo"
|
||||
releases_remote = artifactapi_remote_generic.github.name
|
||||
|
||||
mutable_ttl = 3600
|
||||
|
||||
# Optional: restrict which release assets become packages.
|
||||
patterns = [
|
||||
".*_amd64\\.deb$",
|
||||
".*_all\\.deb$",
|
||||
]
|
||||
|
||||
# Optional: token for private repos / higher GitHub API rate limits.
|
||||
# password = var.github_token
|
||||
}
|
||||
@@ -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 .rpm 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 = [
|
||||
"acme/tools/releases/download/.*\\.rpm$",
|
||||
]
|
||||
}
|
||||
|
||||
# Metadata-only remote: scans acme/tools releases for .rpm assets and serves a
|
||||
# synthesized yum repo. Packages are never precached; downloads 302-redirect to
|
||||
# the "github" remote above.
|
||||
resource "artifactapi_remote_github_rpm" "acme_tools" {
|
||||
name = "acme-tools"
|
||||
base_url = "https://api.github.com/repos/acme/tools"
|
||||
description = "acme/tools GitHub releases as a yum repo"
|
||||
releases_remote = artifactapi_remote_generic.github.name
|
||||
|
||||
mutable_ttl = 3600
|
||||
|
||||
# Optional: restrict which release assets become packages.
|
||||
patterns = [
|
||||
".*\\.x86_64\\.rpm$",
|
||||
".*\\.noarch\\.rpm$",
|
||||
]
|
||||
|
||||
# Optional: token for private repos / higher GitHub API rate limits.
|
||||
# password = var.github_token
|
||||
}
|
||||
@@ -18,6 +18,17 @@ 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",
|
||||
]
|
||||
|
||||
# Load-balancing strategy across base_url + mirrorlist:
|
||||
# "round_robin" (default) or "least_conn".
|
||||
mirror_strategy = "least_conn"
|
||||
|
||||
immutable_ttl = 0
|
||||
mutable_ttl = 7200
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -30,6 +30,8 @@ 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},
|
||||
"mirror_strategy": schema.StringAttribute{Computed: true},
|
||||
"description": schema.StringAttribute{Computed: true},
|
||||
"immutable_ttl": schema.Int64Attribute{Computed: true},
|
||||
"mutable_ttl": schema.Int64Attribute{Computed: true},
|
||||
@@ -45,6 +47,10 @@ func (d *remoteDataSource) Schema(_ context.Context, _ datasource.SchemaRequest,
|
||||
"stale_on_error": schema.BoolAttribute{Computed: true},
|
||||
"releases_remote": schema.StringAttribute{Computed: true},
|
||||
"managed_by": schema.StringAttribute{Computed: true},
|
||||
|
||||
"upstream_dial_timeout": schema.Int64Attribute{Computed: true},
|
||||
"upstream_tls_timeout": schema.Int64Attribute{Computed: true},
|
||||
"upstream_response_header_timeout": schema.Int64Attribute{Computed: true},
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -53,6 +59,8 @@ 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"`
|
||||
MirrorStrategy types.String `tfsdk:"mirror_strategy"`
|
||||
Description types.String `tfsdk:"description"`
|
||||
ImmutableTTL types.Int64 `tfsdk:"immutable_ttl"`
|
||||
MutableTTL types.Int64 `tfsdk:"mutable_ttl"`
|
||||
@@ -68,6 +76,10 @@ type remoteDataSourceModel struct {
|
||||
StaleOnError types.Bool `tfsdk:"stale_on_error"`
|
||||
ReleasesRemote types.String `tfsdk:"releases_remote"`
|
||||
ManagedBy types.String `tfsdk:"managed_by"`
|
||||
|
||||
UpstreamDialTimeout types.Int64 `tfsdk:"upstream_dial_timeout"`
|
||||
UpstreamTLSTimeout types.Int64 `tfsdk:"upstream_tls_timeout"`
|
||||
UpstreamResponseHeaderTimeout types.Int64 `tfsdk:"upstream_response_header_timeout"`
|
||||
}
|
||||
|
||||
func (d *remoteDataSource) Configure(_ context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
@@ -99,6 +111,8 @@ 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),
|
||||
MirrorStrategy: types.StringValue(remote.MirrorStrategy),
|
||||
Description: types.StringValue(remote.Description),
|
||||
ImmutableTTL: types.Int64Value(remote.ImmutableTTL),
|
||||
MutableTTL: types.Int64Value(remote.MutableTTL),
|
||||
@@ -114,6 +128,10 @@ func (d *remoteDataSource) Read(ctx context.Context, req datasource.ReadRequest,
|
||||
StaleOnError: types.BoolValue(remote.StaleOnError),
|
||||
ReleasesRemote: types.StringValue(remote.ReleasesRemote),
|
||||
ManagedBy: types.StringValue(remote.ManagedBy),
|
||||
|
||||
UpstreamDialTimeout: types.Int64Value(remote.UpstreamDialTimeout),
|
||||
UpstreamTLSTimeout: types.Int64Value(remote.UpstreamTLSTimeout),
|
||||
UpstreamResponseHeaderTimeout: types.Int64Value(remote.UpstreamResponseHeaderTimeout),
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, state)...)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ type remoteAPI struct {
|
||||
PackageType string `json:"package_type"`
|
||||
RepoType string `json:"repo_type,omitempty"`
|
||||
BaseURL string `json:"base_url"`
|
||||
Mirrorlist []string `json:"mirrorlist,omitempty"`
|
||||
MirrorStrategy string `json:"mirror_strategy,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Username string `json:"username,omitempty"`
|
||||
Password string `json:"password,omitempty"`
|
||||
@@ -22,6 +24,10 @@ type remoteAPI struct {
|
||||
StaleOnError bool `json:"stale_on_error"`
|
||||
ReleasesRemote string `json:"releases_remote,omitempty"`
|
||||
ManagedBy string `json:"managed_by,omitempty"`
|
||||
|
||||
UpstreamDialTimeout int64 `json:"upstream_dial_timeout"`
|
||||
UpstreamTLSTimeout int64 `json:"upstream_tls_timeout"`
|
||||
UpstreamResponseHeaderTimeout int64 `json:"upstream_response_header_timeout"`
|
||||
}
|
||||
|
||||
type virtualAPI struct {
|
||||
|
||||
@@ -63,14 +63,22 @@ func (p *ArtifactAPIProvider) Resources(_ context.Context) []func() resource.Res
|
||||
newRemoteResource("pypi"),
|
||||
newRemoteResource("npm"),
|
||||
newRemoteResource("rpm"),
|
||||
newRemoteResource("deb"),
|
||||
newRemoteResource("alpine"),
|
||||
newRemoteResource("puppet"),
|
||||
newRemoteResource("terraform"),
|
||||
newRemoteResource("goproxy"),
|
||||
newRemoteResource("github_rpm"),
|
||||
newRemoteResource("github_deb"),
|
||||
newRemoteResource("github_alpine"),
|
||||
NewVirtualResource,
|
||||
NewLocalTerraformResource,
|
||||
NewLocalPyPIResource,
|
||||
NewLocalRPMResource,
|
||||
NewLocalDebResource,
|
||||
NewLocalAlpineResource,
|
||||
NewLocalDockerResource,
|
||||
NewLocalGenericResource,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -66,8 +66,8 @@ func TestProvider_Resources(t *testing.T) {
|
||||
p := &ArtifactAPIProvider{version: "1.0.0"}
|
||||
resources := p.Resources(context.Background())
|
||||
|
||||
// 10 remote resource types + 1 virtual + 1 local_terraform + 1 local_pypi + 1 local_rpm = 14
|
||||
expectedCount := 14
|
||||
// 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))
|
||||
}
|
||||
@@ -102,14 +102,22 @@ func TestProvider_Resources_ContainsExpectedTypes(t *testing.T) {
|
||||
"artifactapi_remote_pypi",
|
||||
"artifactapi_remote_npm",
|
||||
"artifactapi_remote_rpm",
|
||||
"artifactapi_remote_deb",
|
||||
"artifactapi_remote_alpine",
|
||||
"artifactapi_remote_puppet",
|
||||
"artifactapi_remote_terraform",
|
||||
"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",
|
||||
}
|
||||
|
||||
for _, name := range expected {
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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 = &localDebResource{}
|
||||
_ resource.ResourceWithImportState = &localDebResource{}
|
||||
)
|
||||
|
||||
type localDebResource struct {
|
||||
client *apiClient
|
||||
}
|
||||
|
||||
type localDebResourceModel struct {
|
||||
Name types.String `tfsdk:"name"`
|
||||
Description types.String `tfsdk:"description"`
|
||||
}
|
||||
|
||||
func NewLocalDebResource() resource.Resource {
|
||||
return &localDebResource{}
|
||||
}
|
||||
|
||||
func (r *localDebResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_local_deb"
|
||||
}
|
||||
|
||||
func (r *localDebResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "Manages a local ArtifactAPI Deb repository for hosting Debian/apt packages directly.",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"name": schema.StringAttribute{
|
||||
Description: "Unique name of the local Deb repository.",
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"description": schema.StringAttribute{
|
||||
Description: "Human-readable description.",
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Default: stringdefault.StaticString(""),
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *localDebResource) 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 *localDebResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
var plan localDebResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
api := localDebModelToAPI(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 deb failed", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
state := localDebAPIToModel(created)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, state)...)
|
||||
}
|
||||
|
||||
func (r *localDebResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
var state localDebResourceModel
|
||||
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 deb failed", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
newState := localDebAPIToModel(remote)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, newState)...)
|
||||
}
|
||||
|
||||
func (r *localDebResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
var plan localDebResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
api := localDebModelToAPI(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 deb failed", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
state := localDebAPIToModel(updated)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, state)...)
|
||||
}
|
||||
|
||||
func (r *localDebResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
var state localDebResourceModel
|
||||
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 deb failed", err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (r *localDebResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
resource.ImportStatePassthroughID(ctx, path.Root("name"), req, resp)
|
||||
}
|
||||
|
||||
func localDebModelToAPI(m localDebResourceModel) remoteAPI {
|
||||
return remoteAPI{
|
||||
Name: m.Name.ValueString(),
|
||||
PackageType: "deb",
|
||||
RepoType: "local",
|
||||
Description: m.Description.ValueString(),
|
||||
}
|
||||
}
|
||||
|
||||
func localDebAPIToModel(api remoteAPI) localDebResourceModel {
|
||||
return localDebResourceModel{
|
||||
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 TestLocalDebModelToAPI(t *testing.T) {
|
||||
model := localDebResourceModel{
|
||||
Name: types.StringValue("deb-internal"),
|
||||
Description: types.StringValue("Internal Deb repository"),
|
||||
}
|
||||
|
||||
api := localDebModelToAPI(model)
|
||||
|
||||
if api.Name != "deb-internal" {
|
||||
t.Errorf("Name: expected deb-internal, got %s", api.Name)
|
||||
}
|
||||
if api.PackageType != "deb" {
|
||||
t.Errorf("PackageType: expected deb, got %s", api.PackageType)
|
||||
}
|
||||
if api.RepoType != "local" {
|
||||
t.Errorf("RepoType: expected local, got %s", api.RepoType)
|
||||
}
|
||||
if api.Description != "Internal Deb repository" {
|
||||
t.Errorf("Description: expected 'Internal Deb repository', got %s", api.Description)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalDebModelToAPI_EmptyDescription(t *testing.T) {
|
||||
model := localDebResourceModel{
|
||||
Name: types.StringValue("deb-empty"),
|
||||
Description: types.StringValue(""),
|
||||
}
|
||||
|
||||
api := localDebModelToAPI(model)
|
||||
|
||||
if api.Name != "deb-empty" {
|
||||
t.Errorf("Name: expected deb-empty, got %s", api.Name)
|
||||
}
|
||||
if api.Description != "" {
|
||||
t.Errorf("Description: expected empty string, got %s", api.Description)
|
||||
}
|
||||
if api.PackageType != "deb" {
|
||||
t.Errorf("PackageType: expected deb, got %s", api.PackageType)
|
||||
}
|
||||
if api.RepoType != "local" {
|
||||
t.Errorf("RepoType: expected local, got %s", api.RepoType)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalDebAPIToModel(t *testing.T) {
|
||||
api := remoteAPI{
|
||||
Name: "deb-internal",
|
||||
PackageType: "deb",
|
||||
RepoType: "local",
|
||||
Description: "Internal Deb repository",
|
||||
ManagedBy: "terraform",
|
||||
}
|
||||
|
||||
model := localDebAPIToModel(api)
|
||||
|
||||
if model.Name.ValueString() != "deb-internal" {
|
||||
t.Errorf("Name: expected deb-internal, got %s", model.Name.ValueString())
|
||||
}
|
||||
if model.Description.ValueString() != "Internal Deb repository" {
|
||||
t.Errorf("Description: expected 'Internal Deb repository', got %s", model.Description.ValueString())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalDebRoundTrip(t *testing.T) {
|
||||
original := localDebResourceModel{
|
||||
Name: types.StringValue("roundtrip-deb"),
|
||||
Description: types.StringValue("Round trip test"),
|
||||
}
|
||||
|
||||
api := localDebModelToAPI(original)
|
||||
result := localDebAPIToModel(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 TestLocalDebResource_Metadata(t *testing.T) {
|
||||
r := NewLocalDebResource()
|
||||
req := resource.MetadataRequest{ProviderTypeName: "artifactapi"}
|
||||
var resp resource.MetadataResponse
|
||||
r.Metadata(context.Background(), req, &resp)
|
||||
if resp.TypeName != "artifactapi_local_deb" {
|
||||
t.Errorf("expected artifactapi_local_deb, got %s", resp.TypeName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalDebResource_Schema(t *testing.T) {
|
||||
r := NewLocalDebResource()
|
||||
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 TestNewLocalDebResource_Type(t *testing.T) {
|
||||
r := NewLocalDebResource()
|
||||
_, ok := r.(*localDebResource)
|
||||
if !ok {
|
||||
t.Error("expected *localDebResource")
|
||||
}
|
||||
}
|
||||
@@ -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 = &localDockerResource{}
|
||||
_ resource.ResourceWithImportState = &localDockerResource{}
|
||||
)
|
||||
|
||||
type localDockerResource struct {
|
||||
client *apiClient
|
||||
}
|
||||
|
||||
type localDockerResourceModel struct {
|
||||
Name types.String `tfsdk:"name"`
|
||||
Description types.String `tfsdk:"description"`
|
||||
}
|
||||
|
||||
func NewLocalDockerResource() resource.Resource {
|
||||
return &localDockerResource{}
|
||||
}
|
||||
|
||||
func (r *localDockerResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_local_docker"
|
||||
}
|
||||
|
||||
func (r *localDockerResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "Manages a local ArtifactAPI Docker repository — a real container registry serving the Docker Registry HTTP API V2 for push and pull.",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"name": schema.StringAttribute{
|
||||
Description: "Unique name of the local Docker repository. Becomes the first path segment of pushed image references (e.g. <endpoint>/<name>/<image>:<tag>).",
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"description": schema.StringAttribute{
|
||||
Description: "Human-readable description.",
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Default: stringdefault.StaticString(""),
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *localDockerResource) 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 *localDockerResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
var plan localDockerResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
api := localDockerModelToAPI(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 docker failed", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
state := localDockerAPIToModel(created)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, state)...)
|
||||
}
|
||||
|
||||
func (r *localDockerResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
var state localDockerResourceModel
|
||||
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 docker failed", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
newState := localDockerAPIToModel(remote)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, newState)...)
|
||||
}
|
||||
|
||||
func (r *localDockerResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
var plan localDockerResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
api := localDockerModelToAPI(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 docker failed", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
state := localDockerAPIToModel(updated)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, state)...)
|
||||
}
|
||||
|
||||
func (r *localDockerResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
var state localDockerResourceModel
|
||||
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 docker failed", err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (r *localDockerResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
resource.ImportStatePassthroughID(ctx, path.Root("name"), req, resp)
|
||||
}
|
||||
|
||||
func localDockerModelToAPI(m localDockerResourceModel) remoteAPI {
|
||||
return remoteAPI{
|
||||
Name: m.Name.ValueString(),
|
||||
PackageType: "docker",
|
||||
RepoType: "local",
|
||||
Description: m.Description.ValueString(),
|
||||
}
|
||||
}
|
||||
|
||||
func localDockerAPIToModel(api remoteAPI) localDockerResourceModel {
|
||||
return localDockerResourceModel{
|
||||
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 TestLocalDockerModelToAPI(t *testing.T) {
|
||||
model := localDockerResourceModel{
|
||||
Name: types.StringValue("docker-internal"),
|
||||
Description: types.StringValue("Internal container registry"),
|
||||
}
|
||||
|
||||
api := localDockerModelToAPI(model)
|
||||
|
||||
if api.Name != "docker-internal" {
|
||||
t.Errorf("Name: expected docker-internal, got %s", api.Name)
|
||||
}
|
||||
if api.PackageType != "docker" {
|
||||
t.Errorf("PackageType: expected docker, got %s", api.PackageType)
|
||||
}
|
||||
if api.RepoType != "local" {
|
||||
t.Errorf("RepoType: expected local, got %s", api.RepoType)
|
||||
}
|
||||
if api.Description != "Internal container registry" {
|
||||
t.Errorf("Description: expected 'Internal container registry', got %s", api.Description)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalDockerModelToAPI_EmptyDescription(t *testing.T) {
|
||||
model := localDockerResourceModel{
|
||||
Name: types.StringValue("docker-empty"),
|
||||
Description: types.StringValue(""),
|
||||
}
|
||||
|
||||
api := localDockerModelToAPI(model)
|
||||
|
||||
if api.Name != "docker-empty" {
|
||||
t.Errorf("Name: expected docker-empty, got %s", api.Name)
|
||||
}
|
||||
if api.Description != "" {
|
||||
t.Errorf("Description: expected empty string, got %s", api.Description)
|
||||
}
|
||||
if api.PackageType != "docker" {
|
||||
t.Errorf("PackageType: expected docker, got %s", api.PackageType)
|
||||
}
|
||||
if api.RepoType != "local" {
|
||||
t.Errorf("RepoType: expected local, got %s", api.RepoType)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalDockerAPIToModel(t *testing.T) {
|
||||
api := remoteAPI{
|
||||
Name: "docker-internal",
|
||||
PackageType: "docker",
|
||||
RepoType: "local",
|
||||
Description: "Internal container registry",
|
||||
ManagedBy: "terraform",
|
||||
}
|
||||
|
||||
model := localDockerAPIToModel(api)
|
||||
|
||||
if model.Name.ValueString() != "docker-internal" {
|
||||
t.Errorf("Name: expected docker-internal, got %s", model.Name.ValueString())
|
||||
}
|
||||
if model.Description.ValueString() != "Internal container registry" {
|
||||
t.Errorf("Description: expected 'Internal container registry', got %s", model.Description.ValueString())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalDockerRoundTrip(t *testing.T) {
|
||||
original := localDockerResourceModel{
|
||||
Name: types.StringValue("roundtrip-docker"),
|
||||
Description: types.StringValue("Round trip test"),
|
||||
}
|
||||
|
||||
api := localDockerModelToAPI(original)
|
||||
result := localDockerAPIToModel(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 TestLocalDockerResource_Metadata(t *testing.T) {
|
||||
r := NewLocalDockerResource()
|
||||
req := resource.MetadataRequest{ProviderTypeName: "artifactapi"}
|
||||
var resp resource.MetadataResponse
|
||||
r.Metadata(context.Background(), req, &resp)
|
||||
if resp.TypeName != "artifactapi_local_docker" {
|
||||
t.Errorf("expected artifactapi_local_docker, got %s", resp.TypeName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalDockerResource_Schema(t *testing.T) {
|
||||
r := NewLocalDockerResource()
|
||||
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 TestNewLocalDockerResource_Type(t *testing.T) {
|
||||
r := NewLocalDockerResource()
|
||||
_, ok := r.(*localDockerResource)
|
||||
if !ok {
|
||||
t.Error("expected *localDockerResource")
|
||||
}
|
||||
}
|
||||
@@ -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 = &localGenericResource{}
|
||||
_ resource.ResourceWithImportState = &localGenericResource{}
|
||||
)
|
||||
|
||||
type localGenericResource struct {
|
||||
client *apiClient
|
||||
}
|
||||
|
||||
type localGenericResourceModel struct {
|
||||
Name types.String `tfsdk:"name"`
|
||||
Description types.String `tfsdk:"description"`
|
||||
}
|
||||
|
||||
func NewLocalGenericResource() resource.Resource {
|
||||
return &localGenericResource{}
|
||||
}
|
||||
|
||||
func (r *localGenericResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_local_generic"
|
||||
}
|
||||
|
||||
func (r *localGenericResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "Manages a local ArtifactAPI generic repository for hosting arbitrary files (e.g. rootfs tarballs).",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"name": schema.StringAttribute{
|
||||
Description: "Unique name of the local Generic repository.",
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"description": schema.StringAttribute{
|
||||
Description: "Human-readable description.",
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Default: stringdefault.StaticString(""),
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *localGenericResource) 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 *localGenericResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
var plan localGenericResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
api := localGenericModelToAPI(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 rpm failed", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
state := localGenericAPIToModel(created)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, state)...)
|
||||
}
|
||||
|
||||
func (r *localGenericResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
var state localGenericResourceModel
|
||||
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 rpm failed", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
newState := localGenericAPIToModel(remote)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, newState)...)
|
||||
}
|
||||
|
||||
func (r *localGenericResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
var plan localGenericResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
api := localGenericModelToAPI(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 rpm failed", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
state := localGenericAPIToModel(updated)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, state)...)
|
||||
}
|
||||
|
||||
func (r *localGenericResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
var state localGenericResourceModel
|
||||
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 rpm failed", err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (r *localGenericResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
resource.ImportStatePassthroughID(ctx, path.Root("name"), req, resp)
|
||||
}
|
||||
|
||||
func localGenericModelToAPI(m localGenericResourceModel) remoteAPI {
|
||||
return remoteAPI{
|
||||
Name: m.Name.ValueString(),
|
||||
PackageType: "generic",
|
||||
RepoType: "local",
|
||||
Description: m.Description.ValueString(),
|
||||
}
|
||||
}
|
||||
|
||||
func localGenericAPIToModel(api remoteAPI) localGenericResourceModel {
|
||||
return localGenericResourceModel{
|
||||
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 TestLocalGenericModelToAPI(t *testing.T) {
|
||||
model := localGenericResourceModel{
|
||||
Name: types.StringValue("rootfs-images"),
|
||||
Description: types.StringValue("Internal Generic repository"),
|
||||
}
|
||||
|
||||
api := localGenericModelToAPI(model)
|
||||
|
||||
if api.Name != "rootfs-images" {
|
||||
t.Errorf("Name: expected rootfs-images, got %s", api.Name)
|
||||
}
|
||||
if api.PackageType != "generic" {
|
||||
t.Errorf("PackageType: expected generic, got %s", api.PackageType)
|
||||
}
|
||||
if api.RepoType != "local" {
|
||||
t.Errorf("RepoType: expected local, got %s", api.RepoType)
|
||||
}
|
||||
if api.Description != "Internal Generic repository" {
|
||||
t.Errorf("Description: expected 'Internal Generic repository', got %s", api.Description)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalGenericModelToAPI_EmptyDescription(t *testing.T) {
|
||||
model := localGenericResourceModel{
|
||||
Name: types.StringValue("generic-empty"),
|
||||
Description: types.StringValue(""),
|
||||
}
|
||||
|
||||
api := localGenericModelToAPI(model)
|
||||
|
||||
if api.Name != "generic-empty" {
|
||||
t.Errorf("Name: expected generic-empty, got %s", api.Name)
|
||||
}
|
||||
if api.Description != "" {
|
||||
t.Errorf("Description: expected empty string, got %s", api.Description)
|
||||
}
|
||||
if api.PackageType != "generic" {
|
||||
t.Errorf("PackageType: expected generic, got %s", api.PackageType)
|
||||
}
|
||||
if api.RepoType != "local" {
|
||||
t.Errorf("RepoType: expected local, got %s", api.RepoType)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalGenericAPIToModel(t *testing.T) {
|
||||
api := remoteAPI{
|
||||
Name: "rootfs-images",
|
||||
PackageType: "generic",
|
||||
RepoType: "local",
|
||||
Description: "Internal Generic repository",
|
||||
ManagedBy: "terraform",
|
||||
}
|
||||
|
||||
model := localGenericAPIToModel(api)
|
||||
|
||||
if model.Name.ValueString() != "rootfs-images" {
|
||||
t.Errorf("Name: expected rootfs-images, got %s", model.Name.ValueString())
|
||||
}
|
||||
if model.Description.ValueString() != "Internal Generic repository" {
|
||||
t.Errorf("Description: expected 'Internal Generic repository', got %s", model.Description.ValueString())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalGenericRoundTrip(t *testing.T) {
|
||||
original := localGenericResourceModel{
|
||||
Name: types.StringValue("roundtrip-generic"),
|
||||
Description: types.StringValue("Round trip test"),
|
||||
}
|
||||
|
||||
api := localGenericModelToAPI(original)
|
||||
result := localGenericAPIToModel(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 TestLocalGenericResource_Metadata(t *testing.T) {
|
||||
r := NewLocalGenericResource()
|
||||
req := resource.MetadataRequest{ProviderTypeName: "artifactapi"}
|
||||
var resp resource.MetadataResponse
|
||||
r.Metadata(context.Background(), req, &resp)
|
||||
if resp.TypeName != "artifactapi_local_generic" {
|
||||
t.Errorf("expected artifactapi_local_generic, got %s", resp.TypeName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalGenericResource_Schema(t *testing.T) {
|
||||
r := NewLocalGenericResource()
|
||||
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 TestNewLocalGenericResource_Type(t *testing.T) {
|
||||
r := NewLocalGenericResource()
|
||||
_, ok := r.(*localGenericResource)
|
||||
if !ok {
|
||||
t.Error("expected *localGenericResource")
|
||||
}
|
||||
}
|
||||
@@ -16,10 +16,23 @@ 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
|
||||
// and mirror_strategy attributes are valid; the API load-balances
|
||||
// base_url + mirrorlist for these.
|
||||
var mirrorlistPackageTypes = map[string]bool{"rpm": true, "deb": true, "alpine": true}
|
||||
|
||||
// defaultMirrorStrategy is the API's server-side default for mirror_strategy
|
||||
// (stored NOT NULL DEFAULT 'round_robin' and always echoed back on read).
|
||||
const defaultMirrorStrategy = "round_robin"
|
||||
|
||||
// validMirrorStrategies are the accepted mirror_strategy values.
|
||||
var validMirrorStrategies = map[string]bool{"round_robin": true, "least_conn": true}
|
||||
|
||||
type remoteResource struct {
|
||||
client *apiClient
|
||||
packageType string
|
||||
@@ -28,6 +41,8 @@ type remoteResource struct {
|
||||
type remoteResourceModel struct {
|
||||
Name types.String `tfsdk:"name"`
|
||||
BaseURL types.String `tfsdk:"base_url"`
|
||||
Mirrorlist types.List `tfsdk:"mirrorlist"`
|
||||
MirrorStrategy types.String `tfsdk:"mirror_strategy"`
|
||||
Description types.String `tfsdk:"description"`
|
||||
Username types.String `tfsdk:"username"`
|
||||
Password types.String `tfsdk:"password"`
|
||||
@@ -44,6 +59,10 @@ type remoteResourceModel struct {
|
||||
QuarantineDays types.Int64 `tfsdk:"quarantine_days"`
|
||||
StaleOnError types.Bool `tfsdk:"stale_on_error"`
|
||||
ReleasesRemote types.String `tfsdk:"releases_remote"`
|
||||
|
||||
UpstreamDialTimeout types.Int64 `tfsdk:"upstream_dial_timeout"`
|
||||
UpstreamTLSTimeout types.Int64 `tfsdk:"upstream_tls_timeout"`
|
||||
UpstreamResponseHeaderTimeout types.Int64 `tfsdk:"upstream_response_header_timeout"`
|
||||
}
|
||||
|
||||
func newRemoteResource(packageType string) func() resource.Resource {
|
||||
@@ -58,10 +77,16 @@ func NewRemoteHelm() resource.Resource { return &remoteResource{packageType
|
||||
func NewRemotePyPI() resource.Resource { return &remoteResource{packageType: "pypi"} }
|
||||
func NewRemoteNPM() resource.Resource { return &remoteResource{packageType: "npm"} }
|
||||
func NewRemoteRPM() resource.Resource { return &remoteResource{packageType: "rpm"} }
|
||||
func NewRemoteDeb() resource.Resource { return &remoteResource{packageType: "deb"} }
|
||||
func NewRemoteAlpine() resource.Resource { return &remoteResource{packageType: "alpine"} }
|
||||
func NewRemotePuppet() resource.Resource { return &remoteResource{packageType: "puppet"} }
|
||||
func NewRemoteTerraform() resource.Resource { return &remoteResource{packageType: "terraform"} }
|
||||
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
|
||||
@@ -80,6 +105,15 @@ 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,
|
||||
},
|
||||
"mirror_strategy": schema.StringAttribute{
|
||||
Description: "Mirror load-balancing strategy across base_url + mirrorlist; only valid on remote rpm/deb/apk (alpine) repos. One of \"round_robin\" (default) or \"least_conn\".",
|
||||
Optional: true, Computed: true, Default: stringdefault.StaticString(defaultMirrorStrategy),
|
||||
},
|
||||
"description": schema.StringAttribute{
|
||||
Optional: true, Computed: true, Default: stringdefault.StaticString(""),
|
||||
},
|
||||
@@ -141,9 +175,21 @@ func (r *remoteResource) Schema(_ context.Context, _ resource.SchemaRequest, res
|
||||
ElementType: types.StringType,
|
||||
},
|
||||
"releases_remote": schema.StringAttribute{
|
||||
Description: "Name of the CDN remote for download URL rewriting (terraform only).",
|
||||
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{
|
||||
Description: "Upstream TCP connect timeout in seconds (0 = server default).",
|
||||
Optional: true, Computed: true, Default: int64default.StaticInt64(0),
|
||||
},
|
||||
"upstream_tls_timeout": schema.Int64Attribute{
|
||||
Description: "Upstream TLS handshake timeout in seconds (0 = server default).",
|
||||
Optional: true, Computed: true, Default: int64default.StaticInt64(0),
|
||||
},
|
||||
"upstream_response_header_timeout": schema.Int64Attribute{
|
||||
Description: "Upstream response-header timeout in seconds (0 = server default).",
|
||||
Optional: true, Computed: true, Default: int64default.StaticInt64(0),
|
||||
},
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
@@ -246,7 +292,39 @@ 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() && !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),
|
||||
)
|
||||
}
|
||||
|
||||
if !config.MirrorStrategy.IsNull() && !config.MirrorStrategy.IsUnknown() {
|
||||
if !mirrorlistPackageTypes[r.packageType] {
|
||||
resp.Diagnostics.AddAttributeError(
|
||||
path.Root("mirror_strategy"),
|
||||
"mirror_strategy not supported for this remote type",
|
||||
fmt.Sprintf("mirror_strategy is only valid on remote rpm/deb/apk (alpine) repos, not %q remotes.", r.packageType),
|
||||
)
|
||||
} else if v := config.MirrorStrategy.ValueString(); !validMirrorStrategies[v] {
|
||||
resp.Diagnostics.AddAttributeError(
|
||||
path.Root("mirror_strategy"),
|
||||
"invalid mirror_strategy",
|
||||
fmt.Sprintf("mirror_strategy must be \"round_robin\" or \"least_conn\", got %q.", v),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -268,7 +346,13 @@ func (r *remoteResource) modelToAPI(ctx context.Context, m remoteResourceModel)
|
||||
QuarantineEnabled: m.QuarantineEnabled.ValueBool(),
|
||||
QuarantineDays: m.QuarantineDays.ValueInt64(),
|
||||
StaleOnError: m.StaleOnError.ValueBool(),
|
||||
|
||||
UpstreamDialTimeout: m.UpstreamDialTimeout.ValueInt64(),
|
||||
UpstreamTLSTimeout: m.UpstreamTLSTimeout.ValueInt64(),
|
||||
UpstreamResponseHeaderTimeout: m.UpstreamResponseHeaderTimeout.ValueInt64(),
|
||||
}
|
||||
api.Mirrorlist = listToStrings(ctx, m.Mirrorlist)
|
||||
api.MirrorStrategy = m.MirrorStrategy.ValueString()
|
||||
api.Patterns = listToStrings(ctx, m.Patterns)
|
||||
api.Blocklist = listToStrings(ctx, m.Blocklist)
|
||||
api.MutablePatterns = listToStrings(ctx, m.MutablePatterns)
|
||||
@@ -279,10 +363,22 @@ func (r *remoteResource) modelToAPI(ctx context.Context, m remoteResourceModel)
|
||||
return api
|
||||
}
|
||||
|
||||
// mirrorStrategyOrDefault normalizes the API's mirror_strategy to the server
|
||||
// default when empty (e.g. an older create response), so a Computed+Default
|
||||
// attribute settles to round_robin instead of an inconsistent-result error.
|
||||
func mirrorStrategyOrDefault(s string) string {
|
||||
if s == "" {
|
||||
return defaultMirrorStrategy
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (r *remoteResource) apiToModel(ctx context.Context, api remoteAPI) remoteResourceModel {
|
||||
m := remoteResourceModel{
|
||||
Name: types.StringValue(api.Name),
|
||||
BaseURL: types.StringValue(api.BaseURL),
|
||||
Mirrorlist: stringsToList(ctx, api.Mirrorlist),
|
||||
MirrorStrategy: types.StringValue(mirrorStrategyOrDefault(api.MirrorStrategy)),
|
||||
Description: types.StringValue(api.Description),
|
||||
Username: types.StringValue(api.Username),
|
||||
Password: types.StringValue(api.Password),
|
||||
@@ -299,6 +395,10 @@ func (r *remoteResource) apiToModel(ctx context.Context, api remoteAPI) remoteRe
|
||||
BanTagsEnabled: types.BoolValue(api.BanTagsEnabled),
|
||||
BanTags: stringsToList(ctx, api.BanTags),
|
||||
ReleasesRemote: types.StringValue(api.ReleasesRemote),
|
||||
|
||||
UpstreamDialTimeout: types.Int64Value(api.UpstreamDialTimeout),
|
||||
UpstreamTLSTimeout: types.Int64Value(api.UpstreamTLSTimeout),
|
||||
UpstreamResponseHeaderTimeout: types.Int64Value(api.UpstreamResponseHeaderTimeout),
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
@@ -31,10 +33,18 @@ func TestModelToAPI_FullFields(t *testing.T) {
|
||||
QuarantineDays: types.Int64Value(7),
|
||||
StaleOnError: types.BoolValue(false),
|
||||
ReleasesRemote: types.StringValue("cdn-remote"),
|
||||
|
||||
UpstreamDialTimeout: types.Int64Value(3),
|
||||
UpstreamTLSTimeout: types.Int64Value(4),
|
||||
UpstreamResponseHeaderTimeout: types.Int64Value(5),
|
||||
}
|
||||
|
||||
api := r.modelToAPI(ctx, model)
|
||||
|
||||
if api.UpstreamDialTimeout != 3 || api.UpstreamTLSTimeout != 4 || api.UpstreamResponseHeaderTimeout != 5 {
|
||||
t.Errorf("upstream timeouts: got %d/%d/%d, want 3/4/5",
|
||||
api.UpstreamDialTimeout, api.UpstreamTLSTimeout, api.UpstreamResponseHeaderTimeout)
|
||||
}
|
||||
if api.Name != "my-remote" {
|
||||
t.Errorf("Name: expected my-remote, got %s", api.Name)
|
||||
}
|
||||
@@ -211,10 +221,22 @@ func TestAPIToModel_FullFields(t *testing.T) {
|
||||
StaleOnError: false,
|
||||
ReleasesRemote: "cdn-remote",
|
||||
ManagedBy: "terraform",
|
||||
|
||||
UpstreamDialTimeout: 3,
|
||||
UpstreamTLSTimeout: 4,
|
||||
UpstreamResponseHeaderTimeout: 5,
|
||||
}
|
||||
|
||||
model := r.apiToModel(ctx, api)
|
||||
|
||||
if model.UpstreamDialTimeout.ValueInt64() != 3 ||
|
||||
model.UpstreamTLSTimeout.ValueInt64() != 4 ||
|
||||
model.UpstreamResponseHeaderTimeout.ValueInt64() != 5 {
|
||||
t.Errorf("upstream timeouts: got %d/%d/%d, want 3/4/5",
|
||||
model.UpstreamDialTimeout.ValueInt64(),
|
||||
model.UpstreamTLSTimeout.ValueInt64(),
|
||||
model.UpstreamResponseHeaderTimeout.ValueInt64())
|
||||
}
|
||||
if model.Name.ValueString() != "my-remote" {
|
||||
t.Errorf("Name: expected my-remote, got %s", model.Name.ValueString())
|
||||
}
|
||||
@@ -324,12 +346,24 @@ func TestModelToAPI_RoundTrip(t *testing.T) {
|
||||
QuarantineDays: 3,
|
||||
StaleOnError: true,
|
||||
ReleasesRemote: "",
|
||||
|
||||
UpstreamDialTimeout: 5,
|
||||
UpstreamTLSTimeout: 0,
|
||||
UpstreamResponseHeaderTimeout: 45,
|
||||
}
|
||||
|
||||
// API -> Model -> API round-trip
|
||||
model := r.apiToModel(ctx, original)
|
||||
result := r.modelToAPI(ctx, model)
|
||||
|
||||
if result.UpstreamDialTimeout != original.UpstreamDialTimeout ||
|
||||
result.UpstreamTLSTimeout != original.UpstreamTLSTimeout ||
|
||||
result.UpstreamResponseHeaderTimeout != original.UpstreamResponseHeaderTimeout {
|
||||
t.Errorf("upstream timeouts round-trip: got %d/%d/%d, want %d/%d/%d",
|
||||
result.UpstreamDialTimeout, result.UpstreamTLSTimeout, result.UpstreamResponseHeaderTimeout,
|
||||
original.UpstreamDialTimeout, original.UpstreamTLSTimeout, original.UpstreamResponseHeaderTimeout)
|
||||
}
|
||||
|
||||
if result.Name != original.Name {
|
||||
t.Errorf("Name: expected %s, got %s", original.Name, result.Name)
|
||||
}
|
||||
@@ -377,6 +411,9 @@ func TestRemoteResource_Metadata(t *testing.T) {
|
||||
{"helm", "artifactapi_remote_helm"},
|
||||
{"pypi", "artifactapi_remote_pypi"},
|
||||
{"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 {
|
||||
@@ -392,6 +429,62 @@ func TestRemoteResource_Metadata(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelToAPI_GitHubRPM(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
r := &remoteResource{packageType: "github_rpm"}
|
||||
|
||||
model := remoteResourceModel{
|
||||
Name: types.StringValue("acme-tools"),
|
||||
BaseURL: types.StringValue("https://api.github.com/repos/acme/tools"),
|
||||
ReleasesRemote: types.StringValue("github"),
|
||||
MutableTTL: types.Int64Value(3600),
|
||||
Patterns: stringsToList(ctx, []string{`.*\.x86_64\.rpm$`}),
|
||||
}
|
||||
|
||||
api := r.modelToAPI(ctx, model)
|
||||
|
||||
if api.PackageType != "github_rpm" {
|
||||
t.Errorf("PackageType: expected github_rpm, got %s", api.PackageType)
|
||||
}
|
||||
if api.BaseURL != "https://api.github.com/repos/acme/tools" {
|
||||
t.Errorf("BaseURL: got %s", api.BaseURL)
|
||||
}
|
||||
if api.ReleasesRemote != "github" {
|
||||
t.Errorf("ReleasesRemote: expected github, got %s", api.ReleasesRemote)
|
||||
}
|
||||
if len(api.Patterns) != 1 || api.Patterns[0] != `.*\.x86_64\.rpm$` {
|
||||
t.Errorf("Patterns: got %v", api.Patterns)
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelToAPI_GitHubDeb(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
r := &remoteResource{packageType: "github_deb"}
|
||||
|
||||
model := remoteResourceModel{
|
||||
Name: types.StringValue("acme-tools"),
|
||||
BaseURL: types.StringValue("https://api.github.com/repos/acme/tools"),
|
||||
ReleasesRemote: types.StringValue("github"),
|
||||
MutableTTL: types.Int64Value(3600),
|
||||
Patterns: stringsToList(ctx, []string{`.*_amd64\.deb$`}),
|
||||
}
|
||||
|
||||
api := r.modelToAPI(ctx, model)
|
||||
|
||||
if api.PackageType != "github_deb" {
|
||||
t.Errorf("PackageType: expected github_deb, got %s", api.PackageType)
|
||||
}
|
||||
if api.BaseURL != "https://api.github.com/repos/acme/tools" {
|
||||
t.Errorf("BaseURL: got %s", api.BaseURL)
|
||||
}
|
||||
if api.ReleasesRemote != "github" {
|
||||
t.Errorf("ReleasesRemote: expected github, got %s", api.ReleasesRemote)
|
||||
}
|
||||
if len(api.Patterns) != 1 || api.Patterns[0] != `.*_amd64\.deb$` {
|
||||
t.Errorf("Patterns: got %v", api.Patterns)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteResource_Schema(t *testing.T) {
|
||||
r := &remoteResource{packageType: "docker"}
|
||||
req := resource.SchemaRequest{}
|
||||
@@ -405,6 +498,7 @@ func TestRemoteResource_Schema(t *testing.T) {
|
||||
"ban_tags_enabled", "ban_tags",
|
||||
"quarantine_enabled", "quarantine_days",
|
||||
"stale_on_error", "releases_remote",
|
||||
"upstream_dial_timeout", "upstream_tls_timeout", "upstream_response_header_timeout",
|
||||
}
|
||||
|
||||
for _, attr := range expectedAttrs {
|
||||
@@ -430,6 +524,9 @@ func TestNewRemoteResource_Constructors(t *testing.T) {
|
||||
{"puppet", func() resource.Resource { return NewRemotePuppet() }, "puppet"},
|
||||
{"terraform", func() resource.Resource { return NewRemoteTerraform() }, "terraform"},
|
||||
{"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 {
|
||||
@@ -445,3 +542,281 @@ 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())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestModelToAPI_MirrorStrategy(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
for _, pkgType := range []string{"rpm", "deb", "alpine"} {
|
||||
t.Run(pkgType, func(t *testing.T) {
|
||||
r := &remoteResource{packageType: pkgType}
|
||||
model := remoteResourceModel{
|
||||
Name: types.StringValue("strategy-remote"),
|
||||
BaseURL: types.StringValue("https://primary.example.com"),
|
||||
MirrorStrategy: types.StringValue("least_conn"),
|
||||
}
|
||||
api := r.modelToAPI(ctx, model)
|
||||
if api.MirrorStrategy != "least_conn" {
|
||||
t.Errorf("MirrorStrategy: expected least_conn, got %q", api.MirrorStrategy)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelToAPI_MirrorStrategyNull(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
r := &remoteResource{packageType: "rpm"}
|
||||
model := remoteResourceModel{
|
||||
Name: types.StringValue("no-strategy"),
|
||||
BaseURL: types.StringValue("https://primary.example.com"),
|
||||
MirrorStrategy: types.StringNull(),
|
||||
}
|
||||
api := r.modelToAPI(ctx, model)
|
||||
if api.MirrorStrategy != "" {
|
||||
t.Errorf("MirrorStrategy: expected \"\" (omitted) for null, got %q", api.MirrorStrategy)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIToModel_MirrorStrategy(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
r := &remoteResource{packageType: "rpm"}
|
||||
|
||||
// Round-trip: mirror_strategy survives API -> Model -> API without churn.
|
||||
api := remoteAPI{Name: "rt", PackageType: "rpm", BaseURL: "https://primary.example.com", MirrorStrategy: "least_conn"}
|
||||
model := r.apiToModel(ctx, api)
|
||||
if model.MirrorStrategy.ValueString() != "least_conn" {
|
||||
t.Errorf("MirrorStrategy round-trip: expected least_conn, got %q", model.MirrorStrategy.ValueString())
|
||||
}
|
||||
if got := r.modelToAPI(ctx, model); got.MirrorStrategy != "least_conn" {
|
||||
t.Errorf("MirrorStrategy round-trip back to API: expected least_conn, got %q", got.MirrorStrategy)
|
||||
}
|
||||
|
||||
// The refresh/GET path: the API stores mirror_strategy NOT NULL DEFAULT
|
||||
// 'round_robin' and always returns it, even when the config omitted it.
|
||||
// Read must keep round_robin in state (not collapse to null) so that a null
|
||||
// config — which the Computed+Default schema resolves to round_robin —
|
||||
// produces no post-apply diff. This is the perpetual-churn regression guard.
|
||||
getResp := r.apiToModel(ctx, remoteAPI{Name: "g", PackageType: "rpm", BaseURL: "https://x", MirrorStrategy: "round_robin"})
|
||||
if getResp.MirrorStrategy.IsNull() {
|
||||
t.Fatal("MirrorStrategy: GET returning round_robin must not map to null (would churn every plan)")
|
||||
}
|
||||
if getResp.MirrorStrategy.ValueString() != "round_robin" {
|
||||
t.Errorf("MirrorStrategy: expected round_robin from GET, got %q", getResp.MirrorStrategy.ValueString())
|
||||
}
|
||||
|
||||
// A create response that omits the field settles to the server default so a
|
||||
// Computed+Default (round_robin) attribute does not raise inconsistent-result.
|
||||
empty := r.apiToModel(ctx, remoteAPI{Name: "e", PackageType: "rpm", BaseURL: "https://x"})
|
||||
if empty.MirrorStrategy.ValueString() != "round_robin" {
|
||||
t.Errorf("MirrorStrategy: expected round_robin default for empty input, got %q", empty.MirrorStrategy.ValueString())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteResource_SchemaHasMirrorStrategy(t *testing.T) {
|
||||
r := &remoteResource{packageType: "rpm"}
|
||||
var resp resource.SchemaResponse
|
||||
r.Schema(context.Background(), resource.SchemaRequest{}, &resp)
|
||||
attr, ok := resp.Schema.Attributes["mirror_strategy"]
|
||||
if !ok {
|
||||
t.Fatal("missing mirror_strategy attribute in schema")
|
||||
}
|
||||
// Must be Computed (with a server-default) so an API-defaulted round_robin
|
||||
// can live in state while the config is null, without a perpetual diff.
|
||||
if !attr.IsComputed() {
|
||||
t.Error("mirror_strategy must be Computed to hold the API's round_robin default without churn")
|
||||
}
|
||||
if !attr.IsOptional() {
|
||||
t.Error("mirror_strategy must remain Optional so users can set least_conn")
|
||||
}
|
||||
}
|
||||
|
||||
// mirrorStrategyConfig builds a tfsdk.Config for the remote schema with every
|
||||
// attribute null except mirror_strategy, which is set to the given value (or
|
||||
// null when value is "").
|
||||
func mirrorStrategyConfig(ctx context.Context, t *testing.T, r *remoteResource, value 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 value != "" {
|
||||
attrs["mirror_strategy"] = tftypes.NewValue(tftypes.String, value)
|
||||
}
|
||||
return tfsdk.Config{Schema: resp.Schema, Raw: tftypes.NewValue(objType, attrs)}
|
||||
}
|
||||
|
||||
func TestValidateConfig_MirrorStrategy(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
// Supported types accept a valid mirror_strategy.
|
||||
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: mirrorStrategyConfig(ctx, t, r, "least_conn")}, &resp)
|
||||
if resp.Diagnostics.HasError() {
|
||||
t.Errorf("unexpected error for %s: %v", pkgType, resp.Diagnostics.Errors())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Unsupported types reject a set mirror_strategy.
|
||||
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: mirrorStrategyConfig(ctx, t, r, "round_robin")}, &resp)
|
||||
if !resp.Diagnostics.HasError() {
|
||||
t.Errorf("expected error setting mirror_strategy on %s remote", pkgType)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// An invalid enum value is rejected even on a supported type.
|
||||
t.Run("invalid-value-on-rpm", func(t *testing.T) {
|
||||
r := &remoteResource{packageType: "rpm"}
|
||||
var resp resource.ValidateConfigResponse
|
||||
r.ValidateConfig(ctx, resource.ValidateConfigRequest{Config: mirrorStrategyConfig(ctx, t, r, "bogus")}, &resp)
|
||||
if !resp.Diagnostics.HasError() {
|
||||
t.Error("expected error for invalid mirror_strategy value on rpm")
|
||||
}
|
||||
})
|
||||
|
||||
// A null mirror_strategy 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: mirrorStrategyConfig(ctx, t, r, "")}, &resp)
|
||||
if resp.Diagnostics.HasError() {
|
||||
t.Errorf("unexpected error for null mirror_strategy on docker: %v", resp.Diagnostics.Errors())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user