mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 11:07:31 +01:00
terraform/provider: import the SeaweedFS Terraform provider
Import terraform-provider-seaweedfs by Luís Costa (MIT) as a nested Go module. It manages S3 buckets and their configuration (tags, CORS, lifecycle, versioning, policy, encryption, public access block, ownership controls, request payment, quota), IAM users, access keys, groups, roles, policies, attachments, OIDC providers and service accounts, and S3 Tables buckets, namespaces, tables, policies and maintenance configuration. The module path and the provider source address move to seaweedfs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
08aeac6b53
commit
0ea30aa456
77 files changed
+9791
No files matched your search
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 LuisCosta
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,31 @@
|
||||
SHELL := /bin/bash
|
||||
|
||||
.PHONY: fmt test test-race build docs check lint vuln hooks
|
||||
|
||||
fmt:
|
||||
go fmt ./...
|
||||
terraform -chdir=examples/basic fmt
|
||||
|
||||
test:
|
||||
go test ./...
|
||||
|
||||
test-race:
|
||||
go test -race ./...
|
||||
|
||||
build:
|
||||
go build ./...
|
||||
|
||||
docs:
|
||||
go generate ./...
|
||||
|
||||
check: fmt test build
|
||||
|
||||
lint:
|
||||
go vet ./...
|
||||
|
||||
vuln:
|
||||
govulncheck ./...
|
||||
|
||||
hooks:
|
||||
git config core.hooksPath .githooks
|
||||
pre-commit install --install-hooks --hook-dir .githooks
|
||||
@@ -0,0 +1,128 @@
|
||||
# terraform-provider-seaweedfs
|
||||
|
||||
Terraform and OpenTofu provider for SeaweedFS S3, IAM, and S3 Tables APIs. The
|
||||
provider targets SeaweedFS 4.51 API behavior and supports importing every
|
||||
managed resource; each resource's documentation lists its import identifier.
|
||||
|
||||
## Managed resources
|
||||
|
||||
- **S3 buckets:** bucket lifecycle and tags, CORS, lifecycle rules, versioning,
|
||||
bucket policies, encryption, public access block, ownership controls,
|
||||
requester-pays configuration, and SeaweedFS bucket quotas.
|
||||
- **IAM:** users, access keys, inline user/group policies, groups and
|
||||
authoritative group membership, roles and trust policies, managed policies,
|
||||
user/group/role policy attachments, OIDC providers, and service accounts.
|
||||
- **S3 Tables:** table buckets and policies, namespaces, Iceberg tables and
|
||||
table policies, resource tags, and bucket/table maintenance configuration.
|
||||
|
||||
S3 bucket configuration documents and S3 Tables table metadata are passed as
|
||||
JSON strings using the SeaweedFS/AWS API field names. IAM and S3 Tables policy
|
||||
documents are JSON strings as well.
|
||||
|
||||
### Lifecycle and secret notes
|
||||
|
||||
- Destroying bucket versioning suspends versioning; S3 has no operation to
|
||||
remove the versioning configuration. Request-payment destroy resets the
|
||||
payer to the bucket owner, and quota destroy disables the quota.
|
||||
- S3 Tables maintenance configuration has no delete API; destroy disables the
|
||||
maintenance type.
|
||||
- A service-account secret is returned only at creation and is retained in
|
||||
Terraform state. `sensitive` masks CLI output but does not encrypt state.
|
||||
Use an encrypted, access-controlled state backend and protect state backups.
|
||||
- SeaweedFS stores one active managed-policy version; policy updates replace
|
||||
that document in place.
|
||||
|
||||
Object data operations, cluster installation, and irreversible object-lock
|
||||
configuration are intentionally not modeled as Terraform resources.
|
||||
|
||||
## SeaweedFS compatibility
|
||||
|
||||
IAM feature availability can vary between SeaweedFS deployments. In particular,
|
||||
`CreateAccessKey` has returned `ServiceFailure: Internal server error` in some
|
||||
deployments. Run the integration smoke test against the exact SeaweedFS version
|
||||
and configuration you intend to use before relying on IAM resources.
|
||||
|
||||
## Build
|
||||
|
||||
```bash
|
||||
go mod tidy
|
||||
go build -o terraform-provider-seaweedfs
|
||||
```
|
||||
|
||||
## Generate Docs
|
||||
|
||||
```bash
|
||||
make docs
|
||||
```
|
||||
|
||||
This runs `tfplugindocs` via `go generate` and updates files under `docs/`.
|
||||
|
||||
## Use locally with Terraform
|
||||
|
||||
Create `~/.terraformrc`:
|
||||
|
||||
```hcl
|
||||
provider_installation {
|
||||
dev_overrides {
|
||||
"seaweedfs/seaweedfs" = "/absolute/path/to/terraform-provider-seaweedfs"
|
||||
}
|
||||
direct {}
|
||||
}
|
||||
```
|
||||
|
||||
Then in your Terraform config:
|
||||
|
||||
```hcl
|
||||
terraform {
|
||||
required_providers {
|
||||
seaweedfs = {
|
||||
source = "seaweedfs/seaweedfs"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
provider "seaweedfs" {
|
||||
endpoint = "https://s3.example.com"
|
||||
region = "us-east-1"
|
||||
access_key = var.admin_access_key
|
||||
secret_key = var.admin_secret_key
|
||||
}
|
||||
|
||||
resource "seaweedfs_iam_user" "example" {
|
||||
name = "example-user"
|
||||
}
|
||||
```
|
||||
|
||||
`endpoint`, `access_key`, and `secret_key` may alternatively be supplied by
|
||||
`SEAWEEDFS_ENDPOINT`, `SEAWEEDFS_ACCESS_KEY`, and `SEAWEEDFS_SECRET_KEY`.
|
||||
`SEAWEEDFS_REGION` defaults to `us-east-1`; `SEAWEEDFS_INSECURE` accepts
|
||||
`true`/`false` and defaults to `false`. Explicit provider configuration takes
|
||||
precedence over environment variables.
|
||||
|
||||
## CI and Release
|
||||
|
||||
- CI: `.github/workflows/ci.yml` — runs on every push and pull request.
|
||||
- Release: `.github/workflows/release.yml` — runs on every push to `main`.
|
||||
Parses conventional commits since the last tag and creates a new `vMAJOR.MINOR.PATCH`
|
||||
tag and GitHub release automatically. No manual tagging required.
|
||||
`GITHUB_TOKEN` is provided automatically by GitHub Actions; no additional secrets are needed.
|
||||
- GoReleaser config: `.goreleaser.yml`
|
||||
- Install pre-commit and Conventional Commit hooks with `make hooks`
|
||||
(requires the `pre-commit` CLI).
|
||||
|
||||
## Local SeaweedFS integration smoke test
|
||||
|
||||
The smoke fixture exercises bucket/tagging, core IAM, S3 Tables, and table
|
||||
maintenance create/read behavior with OpenTofu against SeaweedFS 4.51:
|
||||
|
||||
```sh
|
||||
make test-race
|
||||
tofu fmt -check -recursive
|
||||
./scripts/minikube-smoke.sh
|
||||
```
|
||||
|
||||
The script requires the existing `seaweedfs-kvm-smoke` Minikube profile (or a
|
||||
profile selected with `MINIKUBE_PROFILE`). It creates the namespace and Helm
|
||||
resources if needed, but does not delete the cluster, release, or Terraform
|
||||
resources. It applies the example automatically; use only a disposable test
|
||||
cluster and review the local example state before any manual cleanup.
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs Provider"
|
||||
description: |-
|
||||
|
||||
---
|
||||
|
||||
# seaweedfs Provider
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Optional
|
||||
|
||||
- `access_key` (String, Sensitive) Admin access key. Falls back to SEAWEEDFS_ACCESS_KEY.
|
||||
- `endpoint` (String) SeaweedFS S3/IAM endpoint. Falls back to SEAWEEDFS_ENDPOINT.
|
||||
- `insecure` (Boolean) Skip TLS verification. Falls back to SEAWEEDFS_INSECURE.
|
||||
- `region` (String) Signing region. Falls back to SEAWEEDFS_REGION. Default: us-east-1.
|
||||
- `secret_key` (String, Sensitive) Admin secret key. Falls back to SEAWEEDFS_SECRET_KEY.
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_bucket Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages a SeaweedFS S3 bucket.
|
||||
---
|
||||
|
||||
# seaweedfs_bucket (Resource)
|
||||
|
||||
Manages a SeaweedFS S3 bucket.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `bucket` (String) Bucket name.
|
||||
|
||||
### Optional
|
||||
|
||||
- `tags` (Map of String) Bucket tags.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `arn` (String) Bucket ARN.
|
||||
- `id` (String) The ID of this resource.
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_bucket_cors_configuration Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages a SeaweedFS S3 bucket CORS configuration. Configuration is JSON encoded.
|
||||
---
|
||||
|
||||
# seaweedfs_bucket_cors_configuration (Resource)
|
||||
|
||||
Manages a SeaweedFS S3 bucket CORS configuration. Configuration is JSON encoded.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `bucket` (String) S3 bucket name.
|
||||
- `configuration` (String) JSON encoded configuration document.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `id` (String) The ID of this resource.
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_bucket_encryption Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages a SeaweedFS S3 bucket default encryption configuration. Configuration is JSON encoded.
|
||||
---
|
||||
|
||||
# seaweedfs_bucket_encryption (Resource)
|
||||
|
||||
Manages a SeaweedFS S3 bucket default encryption configuration. Configuration is JSON encoded.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `bucket` (String) S3 bucket name.
|
||||
- `configuration` (String) JSON encoded configuration document.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `id` (String) The ID of this resource.
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_bucket_lifecycle_configuration Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages a SeaweedFS S3 bucket lifecycle configuration. Configuration is JSON encoded.
|
||||
---
|
||||
|
||||
# seaweedfs_bucket_lifecycle_configuration (Resource)
|
||||
|
||||
Manages a SeaweedFS S3 bucket lifecycle configuration. Configuration is JSON encoded.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `bucket` (String) S3 bucket name.
|
||||
- `configuration` (String) JSON encoded configuration document.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `id` (String) The ID of this resource.
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_bucket_ownership_controls Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages SeaweedFS S3 bucket ownership controls. Configuration is JSON encoded.
|
||||
---
|
||||
|
||||
# seaweedfs_bucket_ownership_controls (Resource)
|
||||
|
||||
Manages SeaweedFS S3 bucket ownership controls. Configuration is JSON encoded.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `bucket` (String) S3 bucket name.
|
||||
- `configuration` (String) JSON encoded configuration document.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `id` (String) The ID of this resource.
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_bucket_policy Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages the S3 bucket policy in SeaweedFS. Import using the bucket name.
|
||||
---
|
||||
|
||||
# seaweedfs_bucket_policy (Resource)
|
||||
|
||||
Manages the S3 bucket policy in SeaweedFS. Import using the bucket name.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `bucket` (String) S3 bucket name.
|
||||
- `policy` (String) JSON bucket policy document.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `id` (String) The ID of this resource.
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_bucket_public_access_block Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages a SeaweedFS S3 bucket public access block configuration where supported. SeaweedFS 4.51.0 returns NotImplemented for this API.
|
||||
---
|
||||
|
||||
# seaweedfs_bucket_public_access_block (Resource)
|
||||
|
||||
Manages a SeaweedFS S3 bucket public access block configuration where supported. SeaweedFS 4.51.0 returns NotImplemented for this API.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `bucket` (String) S3 bucket name.
|
||||
- `configuration` (String) JSON encoded configuration document.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `id` (String) The ID of this resource.
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_bucket_quota Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages a SeaweedFS-specific S3 bucket storage quota. Import using the bucket name.
|
||||
---
|
||||
|
||||
# seaweedfs_bucket_quota (Resource)
|
||||
|
||||
Manages a SeaweedFS-specific S3 bucket storage quota. Import using the bucket name.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `bucket` (String) S3 bucket name.
|
||||
- `enabled` (Boolean) Whether SeaweedFS enforces the quota.
|
||||
- `quota_bytes` (Number) Maximum bucket size in bytes. Use zero only when the quota is disabled.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `id` (String) The ID of this resource.
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_bucket_request_payment Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages a SeaweedFS S3 bucket request payment configuration. Destroy resets the payer to BucketOwner.
|
||||
|
||||
SeaweedFS 4.51.0 accepts only `BucketOwner`; setting `Requester` is rejected by the server with `MalformedXML`.
|
||||
---
|
||||
|
||||
# seaweedfs_bucket_request_payment (Resource)
|
||||
|
||||
Manages a SeaweedFS S3 bucket request payment configuration. Destroy resets the payer to BucketOwner.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `bucket` (String) S3 bucket name.
|
||||
- `configuration` (String) JSON encoded configuration document.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `id` (String) The ID of this resource.
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_bucket_versioning Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages SeaweedFS S3 bucket versioning. Configuration is JSON encoded; destroy suspends versioning because S3 cannot unset it.
|
||||
---
|
||||
|
||||
# seaweedfs_bucket_versioning (Resource)
|
||||
|
||||
Manages SeaweedFS S3 bucket versioning. Configuration is JSON encoded; destroy suspends versioning because S3 cannot unset it.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `bucket` (String) S3 bucket name.
|
||||
- `configuration` (String) JSON encoded configuration document.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `id` (String) The ID of this resource.
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_iam_access_key Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages a SeaweedFS IAM access key for a user.
|
||||
---
|
||||
|
||||
# seaweedfs_iam_access_key (Resource)
|
||||
|
||||
Manages a SeaweedFS IAM access key for a user.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `user_name` (String)
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `access_key_id` (String)
|
||||
- `id` (String) The ID of this resource.
|
||||
- `secret_access_key` (String, Sensitive)
|
||||
- `status` (String)
|
||||
@@ -0,0 +1,24 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_iam_group Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages a SeaweedFS IAM group. Group membership and attached policies are managed by separate resources. Import using the group name.
|
||||
---
|
||||
|
||||
# seaweedfs_iam_group (Resource)
|
||||
|
||||
Manages a SeaweedFS IAM group. Group membership and attached policies are managed by separate resources. Import using the group name.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `name` (String)
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `id` (String) The ID of this resource.
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_iam_group_membership Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages the complete user membership set for a SeaweedFS IAM group. Import using the group name.
|
||||
---
|
||||
|
||||
# seaweedfs_iam_group_membership (Resource)
|
||||
|
||||
Manages the complete user membership set for a SeaweedFS IAM group. Import using the group name.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `group_name` (String)
|
||||
- `users` (Set of String) IAM user names that belong to the group.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `id` (String) The ID of this resource.
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_iam_group_policy Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages an inline IAM group policy in SeaweedFS. Import using group_name,policy_name.
|
||||
---
|
||||
|
||||
# seaweedfs_iam_group_policy (Resource)
|
||||
|
||||
Manages an inline IAM group policy in SeaweedFS. Import using `group_name,policy_name`.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `group_name` (String)
|
||||
- `name` (String)
|
||||
- `policy` (String) JSON policy document.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `id` (String) The ID of this resource.
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_iam_group_policy_attachment Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages attachment of an existing managed IAM policy to a SeaweedFS IAM group. Import using group_name,policy_arn.
|
||||
---
|
||||
|
||||
# seaweedfs_iam_group_policy_attachment (Resource)
|
||||
|
||||
Manages attachment of an existing managed IAM policy to a SeaweedFS IAM group. Import using `group_name,policy_arn`.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `group_name` (String) IAM group name.
|
||||
- `policy_arn` (String) ARN of the managed IAM policy.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `id` (String) The ID of this resource.
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_iam_oidc_provider Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages a SeaweedFS IAM OpenID Connect provider. Import using the provider ARN.
|
||||
---
|
||||
|
||||
# seaweedfs_iam_oidc_provider (Resource)
|
||||
|
||||
Manages a SeaweedFS IAM OpenID Connect provider. Import using the provider ARN.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `client_ids` (Set of String) Client IDs allowed to use the provider.
|
||||
- `thumbprints` (Set of String) TLS certificate thumbprints trusted for the provider. At least one is required.
|
||||
- `url` (String) Issuer URL for the OIDC provider.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `arn` (String)
|
||||
- `id` (String) The ID of this resource.
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_iam_policy Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages a SeaweedFS IAM managed policy. SeaweedFS stores one active policy version; updates replace that document in place. Import using the policy ARN or name.
|
||||
---
|
||||
|
||||
# seaweedfs_iam_policy (Resource)
|
||||
|
||||
Manages a SeaweedFS IAM managed policy. SeaweedFS stores one active policy version; updates replace that document in place. Import using the policy ARN or name.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `name` (String) Managed policy name.
|
||||
- `policy` (String) JSON policy document.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `arn` (String) Managed policy ARN.
|
||||
- `id` (String) The ID of this resource.
|
||||
@@ -0,0 +1,30 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_iam_role Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages a SeaweedFS IAM role. SeaweedFS roles do not support paths or mutable descriptions/session duration; changing those attributes replaces the role. Import using the role name.
|
||||
---
|
||||
|
||||
# seaweedfs_iam_role (Resource)
|
||||
|
||||
Manages a SeaweedFS IAM role. SeaweedFS roles do not support paths or mutable descriptions/session duration; changing those attributes replaces the role. Import using the role name.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `assume_role_policy` (String) JSON trust policy document.
|
||||
- `name` (String) IAM role name.
|
||||
|
||||
### Optional
|
||||
|
||||
- `description` (String) Role description.
|
||||
- `max_session_duration` (Number) Maximum role session duration in seconds.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `id` (String) The ID of this resource.
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_iam_role_policy_attachment Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages attachment of an existing managed IAM policy to a SeaweedFS IAM role. Import using role_name,policy_arn.
|
||||
---
|
||||
|
||||
# seaweedfs_iam_role_policy_attachment (Resource)
|
||||
|
||||
Manages attachment of an existing managed IAM policy to a SeaweedFS IAM role. Import using `role_name,policy_arn`.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `policy_arn` (String) ARN of the managed IAM policy.
|
||||
- `role_name` (String) IAM role name.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `id` (String) The ID of this resource.
|
||||
@@ -0,0 +1,33 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_iam_service_account Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages a SeaweedFS IAM service account. The secret key is returned only at creation and is retained in Terraform state; mark state storage as sensitive. Import using the service account ID.
|
||||
---
|
||||
|
||||
# seaweedfs_iam_service_account (Resource)
|
||||
|
||||
Manages a SeaweedFS IAM service account. The secret key is returned only at creation and is retained in Terraform state; mark state storage as sensitive. Import using the service account ID.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `parent_user` (String) IAM user that owns this service account.
|
||||
|
||||
### Optional
|
||||
|
||||
- `description` (String) Service account description. Set to an empty string to clear it.
|
||||
- `expiration` (String) Expiration time in RFC3339 format. Set to an empty string to remove expiration.
|
||||
- `status` (String) Credential status: Active or Inactive.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `access_key_id` (String)
|
||||
- `id` (String) The ID of this resource.
|
||||
- `secret_key` (String, Sensitive)
|
||||
- `service_account_id` (String)
|
||||
@@ -0,0 +1,30 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_iam_user Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages a SeaweedFS IAM user using IAM query API calls.
|
||||
---
|
||||
|
||||
# seaweedfs_iam_user (Resource)
|
||||
|
||||
Manages a SeaweedFS IAM user using IAM query API calls.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `name` (String) IAM user name.
|
||||
|
||||
### Optional
|
||||
|
||||
- `path` (String) IAM path for the user.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `arn` (String) ARN returned by SeaweedFS.
|
||||
- `id` (String) Terraform identifier for this resource. Equals user name.
|
||||
- `user_id` (String) Unique user identifier returned by SeaweedFS.
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_iam_user_policy Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages an inline IAM user policy in SeaweedFS.
|
||||
---
|
||||
|
||||
# seaweedfs_iam_user_policy (Resource)
|
||||
|
||||
Manages an inline IAM user policy in SeaweedFS.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `name` (String)
|
||||
- `policy` (String) JSON policy document.
|
||||
- `user_name` (String)
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `id` (String) The ID of this resource.
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_iam_user_policy_attachment Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages attachment of an existing managed IAM policy to a SeaweedFS IAM user. Import using user_name,policy_arn.
|
||||
---
|
||||
|
||||
# seaweedfs_iam_user_policy_attachment (Resource)
|
||||
|
||||
Manages attachment of an existing managed IAM policy to a SeaweedFS IAM user. Import using `user_name,policy_arn`.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `policy_arn` (String) ARN of the managed IAM policy.
|
||||
- `user_name` (String) IAM user name.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `id` (String) The ID of this resource.
|
||||
@@ -0,0 +1,37 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_table Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages an Iceberg table in a SeaweedFS S3 Tables namespace. Table schema metadata is JSON encoded. Import using table_bucket_arn,namespace,table_name.
|
||||
---
|
||||
|
||||
# seaweedfs_table (Resource)
|
||||
|
||||
Manages an Iceberg table in a SeaweedFS S3 Tables namespace. Table schema metadata is JSON encoded. Import using `table_bucket_arn,namespace,table_name`.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `format` (String) Table format, typically ICEBERG.
|
||||
- `name` (String)
|
||||
- `namespace` (String)
|
||||
- `table_bucket_arn` (String)
|
||||
|
||||
### Optional
|
||||
|
||||
- `metadata` (String) Optional JSON encoded table metadata, including Iceberg schema fields.
|
||||
- `tags` (Map of String) Tags applied to the table.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `created_at` (String)
|
||||
- `id` (String) The ID of this resource.
|
||||
- `metadata_location` (String)
|
||||
- `modified_at` (String)
|
||||
- `table_arn` (String)
|
||||
- `version_token` (String)
|
||||
@@ -0,0 +1,32 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_table_bucket Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages a SeaweedFS S3 Tables bucket. Import using its table bucket ARN.
|
||||
---
|
||||
|
||||
# seaweedfs_table_bucket (Resource)
|
||||
|
||||
Manages a SeaweedFS S3 Tables bucket. Import using its table bucket ARN.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `name` (String) Table bucket name.
|
||||
|
||||
### Optional
|
||||
|
||||
- `format` (String) Table format served by the bucket, such as ICEBERG.
|
||||
- `tags` (Map of String) Tags applied to the table bucket.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `arn` (String)
|
||||
- `created_at` (String)
|
||||
- `id` (String) The ID of this resource.
|
||||
- `owner_account_id` (String)
|
||||
@@ -0,0 +1,31 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_table_bucket_maintenance_configuration Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages a SeaweedFS S3 Tables maintenance configuration. Import using table_bucket_arn. Deletion disables the configuration because the S3 Tables API has no delete operation.
|
||||
---
|
||||
|
||||
# seaweedfs_table_bucket_maintenance_configuration (Resource)
|
||||
|
||||
Manages a SeaweedFS S3 Tables maintenance configuration. Import using `table_bucket_arn`. Deletion disables the configuration because the S3 Tables API has no delete operation.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `status` (String) Whether the maintenance operation is enabled or disabled.
|
||||
- `table_bucket_arn` (String)
|
||||
|
||||
### Optional
|
||||
|
||||
- `non_current_days` (Number) Age in days after which non-current files may be removed.
|
||||
- `unreferenced_days` (Number) Age in days after which unreferenced files may be removed.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `id` (String) The ID of this resource.
|
||||
- `type` (String) The bucket maintenance type is icebergUnreferencedFileRemoval.
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_table_bucket_policy Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages a SeaweedFS S3 Tables table bucket policy policy. Import using table_bucket_arn.
|
||||
---
|
||||
|
||||
# seaweedfs_table_bucket_policy (Resource)
|
||||
|
||||
Manages a SeaweedFS S3 Tables table bucket policy policy. Import using `table_bucket_arn`.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `policy` (String) JSON resource policy.
|
||||
- `table_bucket_arn` (String)
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `id` (String) The ID of this resource.
|
||||
@@ -0,0 +1,35 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_table_maintenance_configuration Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages a SeaweedFS S3 Tables maintenance configuration. Import using table_bucket_arn,namespace,table_name,type. Deletion disables the configuration because the S3 Tables API has no delete operation.
|
||||
---
|
||||
|
||||
# seaweedfs_table_maintenance_configuration (Resource)
|
||||
|
||||
Manages a SeaweedFS S3 Tables maintenance configuration. Import using `table_bucket_arn,namespace,table_name,type`. Deletion disables the configuration because the S3 Tables API has no delete operation.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `name` (String)
|
||||
- `namespace` (String)
|
||||
- `status` (String) Whether the maintenance operation is enabled or disabled.
|
||||
- `table_bucket_arn` (String)
|
||||
- `type` (String) Maintenance type: icebergCompaction or icebergSnapshotManagement.
|
||||
|
||||
### Optional
|
||||
|
||||
- `max_snapshot_age_hours` (Number) Maximum snapshot age in hours. Only applies to icebergSnapshotManagement.
|
||||
- `min_snapshots_to_keep` (Number) Minimum snapshots to retain. Only applies to icebergSnapshotManagement.
|
||||
- `strategy` (String) Compaction strategy: auto, binpack, or sort. Only applies to icebergCompaction.
|
||||
- `target_file_size_mb` (Number) Target compacted file size in MiB. Only applies to icebergCompaction.
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `id` (String) The ID of this resource.
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_table_namespace Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages a namespace in a SeaweedFS S3 Tables bucket. Use a dot-separated path for nested namespaces. Import using table_bucket_arn,namespace.
|
||||
---
|
||||
|
||||
# seaweedfs_table_namespace (Resource)
|
||||
|
||||
Manages a namespace in a SeaweedFS S3 Tables bucket. Use a dot-separated path for nested namespaces. Import using `table_bucket_arn,namespace`.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `namespace` (String) Namespace name or dot-separated namespace path.
|
||||
- `table_bucket_arn` (String)
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `created_at` (String)
|
||||
- `id` (String) The ID of this resource.
|
||||
- `owner_account_id` (String)
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
# generated by https://github.com/hashicorp/terraform-plugin-docs
|
||||
page_title: "seaweedfs_table_policy Resource - seaweedfs"
|
||||
subcategory: ""
|
||||
description: |-
|
||||
Manages a SeaweedFS S3 Tables table policy policy. Import using table_bucket_arn,namespace,table_name.
|
||||
---
|
||||
|
||||
# seaweedfs_table_policy (Resource)
|
||||
|
||||
Manages a SeaweedFS S3 Tables table policy policy. Import using `table_bucket_arn,namespace,table_name`.
|
||||
|
||||
|
||||
|
||||
<!-- schema generated by tfplugindocs -->
|
||||
## Schema
|
||||
|
||||
### Required
|
||||
|
||||
- `name` (String)
|
||||
- `namespace` (String)
|
||||
- `policy` (String) JSON resource policy.
|
||||
- `table_bucket_arn` (String)
|
||||
|
||||
### Read-Only
|
||||
|
||||
- `id` (String) The ID of this resource.
|
||||
@@ -0,0 +1,69 @@
|
||||
terraform {
|
||||
required_version = ">= 1.6.0"
|
||||
required_providers {
|
||||
seaweedfs = {
|
||||
source = "seaweedfs/seaweedfs"
|
||||
version = ">= 0.1.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
provider "seaweedfs" {
|
||||
endpoint = var.endpoint
|
||||
region = var.region
|
||||
access_key = var.access_key
|
||||
secret_key = var.secret_key
|
||||
insecure = var.insecure
|
||||
}
|
||||
|
||||
resource "seaweedfs_iam_user" "test" {
|
||||
name = var.user_name
|
||||
}
|
||||
|
||||
resource "seaweedfs_bucket" "test" {
|
||||
count = var.create_bucket ? 1 : 0
|
||||
bucket = var.bucket_name
|
||||
tags = {
|
||||
managed_by = "terraform"
|
||||
project = "homelab"
|
||||
}
|
||||
}
|
||||
|
||||
resource "seaweedfs_iam_user_policy" "test" {
|
||||
count = var.create_user_policy ? 1 : 0
|
||||
user_name = seaweedfs_iam_user.test.name
|
||||
name = var.policy_name
|
||||
policy = jsonencode({
|
||||
Version = "2012-10-17"
|
||||
Statement = [{
|
||||
Effect = "Allow"
|
||||
Action = ["s3:*"]
|
||||
Resource = [
|
||||
"arn:aws:s3:::${var.bucket_name}",
|
||||
"arn:aws:s3:::${var.bucket_name}/*",
|
||||
]
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
resource "seaweedfs_iam_access_key" "test" {
|
||||
count = var.create_access_key ? 1 : 0
|
||||
user_name = seaweedfs_iam_user.test.name
|
||||
}
|
||||
|
||||
output "user_name" {
|
||||
value = seaweedfs_iam_user.test.name
|
||||
}
|
||||
|
||||
output "user_arn" {
|
||||
value = seaweedfs_iam_user.test.arn
|
||||
}
|
||||
|
||||
output "bucket_name" {
|
||||
value = var.create_bucket ? seaweedfs_bucket.test[0].bucket : null
|
||||
}
|
||||
|
||||
output "access_key_id" {
|
||||
value = var.create_access_key ? seaweedfs_iam_access_key.test[0].access_key_id : null
|
||||
sensitive = true
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
variable "endpoint" {
|
||||
type = string
|
||||
description = "SeaweedFS endpoint."
|
||||
}
|
||||
|
||||
variable "region" {
|
||||
type = string
|
||||
description = "SigV4 region."
|
||||
default = "us-east-1"
|
||||
}
|
||||
|
||||
variable "access_key" {
|
||||
type = string
|
||||
description = "Admin access key."
|
||||
sensitive = true
|
||||
}
|
||||
|
||||
variable "secret_key" {
|
||||
type = string
|
||||
description = "Admin secret key."
|
||||
sensitive = true
|
||||
}
|
||||
|
||||
variable "insecure" {
|
||||
type = bool
|
||||
description = "Skip TLS verification."
|
||||
default = false
|
||||
}
|
||||
|
||||
variable "user_name" {
|
||||
type = string
|
||||
description = "User to create."
|
||||
default = "tf-seaweedfs-test-user"
|
||||
}
|
||||
|
||||
variable "bucket_name" {
|
||||
type = string
|
||||
description = "Bucket to create for testing."
|
||||
default = "tf-seaweedfs-test-bucket"
|
||||
}
|
||||
|
||||
variable "policy_name" {
|
||||
type = string
|
||||
description = "Inline policy name for the test user."
|
||||
default = "tf-seaweedfs-test-policy"
|
||||
}
|
||||
|
||||
variable "create_bucket" {
|
||||
type = bool
|
||||
description = "Whether to create the test bucket."
|
||||
default = true
|
||||
}
|
||||
|
||||
variable "create_user_policy" {
|
||||
type = bool
|
||||
description = "Whether to create and attach a user inline policy."
|
||||
default = true
|
||||
}
|
||||
|
||||
variable "create_access_key" {
|
||||
type = bool
|
||||
description = "Whether to create an IAM access key for the user."
|
||||
default = false
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
terraform {
|
||||
required_version = ">= 1.6.0"
|
||||
required_providers {
|
||||
seaweedfs = {
|
||||
source = "seaweedfs/seaweedfs"
|
||||
version = ">= 0.1.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
provider "seaweedfs" {
|
||||
endpoint = var.seaweedfs_endpoint
|
||||
region = var.seaweedfs_region
|
||||
access_key = var.admin_access_key
|
||||
secret_key = var.admin_secret_key
|
||||
}
|
||||
|
||||
resource "seaweedfs_bucket" "smoke" {
|
||||
bucket = "terraform-provider-smoke"
|
||||
tags = {
|
||||
environment = "local"
|
||||
managed-by = "terraform"
|
||||
}
|
||||
}
|
||||
|
||||
resource "seaweedfs_iam_user" "smoke" {
|
||||
name = "terraform-provider-smoke"
|
||||
path = "/terraform/"
|
||||
}
|
||||
|
||||
resource "seaweedfs_iam_access_key" "smoke" {
|
||||
user_name = seaweedfs_iam_user.smoke.name
|
||||
}
|
||||
|
||||
resource "seaweedfs_iam_user_policy" "smoke" {
|
||||
user_name = seaweedfs_iam_user.smoke.name
|
||||
name = "S3SmokePolicy"
|
||||
policy = jsonencode({
|
||||
Version = "2012-10-17"
|
||||
Statement = [{
|
||||
Effect = "Allow"
|
||||
Action = ["s3:*"]
|
||||
Resource = ["arn:aws:s3:::terraform-provider-smoke", "arn:aws:s3:::terraform-provider-smoke/*"]
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
resource "seaweedfs_table_bucket" "lake" {
|
||||
name = "terraform-provider-smoke-lake"
|
||||
format = "ICEBERG"
|
||||
tags = {
|
||||
environment = "local"
|
||||
managed-by = "terraform"
|
||||
}
|
||||
}
|
||||
|
||||
resource "seaweedfs_table_bucket_maintenance_configuration" "cleanup" {
|
||||
table_bucket_arn = seaweedfs_table_bucket.lake.arn
|
||||
status = "enabled"
|
||||
unreferenced_days = 30
|
||||
}
|
||||
|
||||
resource "seaweedfs_table_namespace" "analytics" {
|
||||
table_bucket_arn = seaweedfs_table_bucket.lake.arn
|
||||
namespace = "analytics"
|
||||
}
|
||||
|
||||
resource "seaweedfs_table" "orders" {
|
||||
table_bucket_arn = seaweedfs_table_bucket.lake.arn
|
||||
namespace = seaweedfs_table_namespace.analytics.namespace
|
||||
name = "orders"
|
||||
format = "ICEBERG"
|
||||
metadata = jsonencode({
|
||||
iceberg = {
|
||||
schema = {
|
||||
fields = [
|
||||
{
|
||||
name = "order_id"
|
||||
type = "long"
|
||||
required = true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
resource "seaweedfs_table_maintenance_configuration" "compaction" {
|
||||
table_bucket_arn = seaweedfs_table_bucket.lake.arn
|
||||
namespace = seaweedfs_table_namespace.analytics.namespace
|
||||
name = seaweedfs_table.orders.name
|
||||
type = "icebergCompaction"
|
||||
status = "enabled"
|
||||
strategy = "binpack"
|
||||
target_file_size_mb = 512
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
variable "seaweedfs_endpoint" {
|
||||
type = string
|
||||
description = "SeaweedFS S3/IAM endpoint."
|
||||
}
|
||||
|
||||
variable "seaweedfs_region" {
|
||||
type = string
|
||||
description = "AWS SigV4 signing region."
|
||||
default = "us-east-1"
|
||||
}
|
||||
|
||||
variable "admin_access_key" {
|
||||
type = string
|
||||
sensitive = true
|
||||
}
|
||||
|
||||
variable "admin_secret_key" {
|
||||
type = string
|
||||
sensitive = true
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
module github.com/seaweedfs/seaweedfs/terraform/provider
|
||||
|
||||
go 1.27.4
|
||||
|
||||
require (
|
||||
github.com/aws/aws-sdk-go-v2 v1.49.0
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.21.7
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.97.3
|
||||
github.com/aws/smithy-go v1.28.13
|
||||
github.com/hashicorp/terraform-plugin-framework v1.17.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.27 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.13 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21 // indirect
|
||||
github.com/fatih/color v1.15.0 // indirect
|
||||
github.com/golang/protobuf v1.5.4 // indirect
|
||||
github.com/hashicorp/go-hclog v1.6.3 // indirect
|
||||
github.com/hashicorp/go-plugin v1.7.0 // indirect
|
||||
github.com/hashicorp/go-uuid v1.0.3 // indirect
|
||||
github.com/hashicorp/terraform-plugin-go v0.29.0 // indirect
|
||||
github.com/hashicorp/terraform-plugin-log v0.10.0 // indirect
|
||||
github.com/hashicorp/terraform-registry-address v0.4.0 // indirect
|
||||
github.com/hashicorp/terraform-svchost v0.1.1 // indirect
|
||||
github.com/hashicorp/yamux v0.1.2 // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.19 // indirect
|
||||
github.com/mitchellh/go-testing-interface v1.14.1 // indirect
|
||||
github.com/oklog/run v1.1.0 // indirect
|
||||
github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect
|
||||
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
|
||||
golang.org/x/net v0.62.0 // indirect
|
||||
golang.org/x/sys v0.49.0 // indirect
|
||||
golang.org/x/text v0.43.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect
|
||||
google.golang.org/grpc v1.83.2 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
)
|
||||
@@ -0,0 +1,125 @@
|
||||
github.com/aws/aws-sdk-go-v2 v1.49.0 h1:nfIScsXPSCz+vXIKz49IjNPHmC4oT72SLPVc8P0OBbU=
|
||||
github.com/aws/aws-sdk-go-v2 v1.49.0/go.mod h1:XwfdWCjuiyYPbYF4ObLoa5I25KjV0ry6d105smVjNKY=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 h1:eBMB84YGghSocM7PsjmmPffTa+1FBUeNvGvFou6V/4o=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8/go.mod h1:lyw7GFp3qENLh7kwzf7iMzAxDn+NzjXEAGjKS2UOKqI=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.21.7 h1:KtckEwHoY6AlldyiX4QAtekiL0S/AITVIYdqZnWWWcA=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.21.7/go.mod h1:YnM7TYbV1J65/yn/4E0Rnj9A/UO2OTeiGNZP8tcYKRw=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15 h1:Y0fe1Hcly/OSHtSWzuQrXGt3RtRjso063UbwZgyCHyQ=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15/go.mod h1:52lvlO6umU2TRGxZJfCtjOR6xnbJotZD11mmzhJLQzI=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15 h1:g2qcH0dUfjjigOI+HQB3DLXDq/8c84uH1ii/SDkwatg=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15/go.mod h1:yGE7vsxRwTs6YBSYcE1j/KNA7EmAGEgBX+TAH0AAvk0=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.15 h1:XKIkHY7yRHnTJrixMmcA1qIm3qenDe/vmOtf/xiuWYE=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.15/go.mod h1:HqYW3gHCQl0tF6dO7kXgc0wFe1Yng0hgCEI7Xa3rK54=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.27 h1:2jIfOe8ZuoStxOkRtVU45zxgvt/qeIRChhm2USOS6g8=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.27/go.mod h1:LpMjYa8iT3kMkAxsVCGfyXkBDOOKsziY6S2wSpEvY70=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.13 h1:JRaIgADQS/U6uXDqlPiefP32yXTda7Kqfx+LgspooZM=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.13/go.mod h1:CEuVn5WqOMilYl+tbccq8+N2ieCy0gVn3OtRb0vBNNM=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.15 h1:ds6Pm/S5xYXPmiqyebd0AeK0zHAAO7qHP1+JZauFnpA=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.15/go.mod h1:WqaHpxUhwzsE+NYp2TQitKclpwhi1XYp6wMsdg+yd/k=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21 h1:ZlvrNcHSFFWURB8avufQq9gFsheUgjVD9536obIknfM=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21/go.mod h1:cv3TNhVrssKR0O/xxLJVRfd2oazSnZnkUeTf6ctUwfQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.97.3 h1:HwxWTbTrIHm5qY+CAEur0s/figc3qwvLWsNkF4RPToo=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.97.3/go.mod h1:uoA43SdFwacedBfSgfFSjjCvYe8aYBS7EnU5GZ/YKMM=
|
||||
github.com/aws/smithy-go v1.28.13 h1:cBdveQH7NJe99gJKArwOKc11/57r17Gjq374TgDs6LY=
|
||||
github.com/aws/smithy-go v1.28.13/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/bufbuild/protocompile v0.14.1 h1:iA73zAf/fyljNjQKwYzUHD6AD4R8KMasmwa/FBatYVw=
|
||||
github.com/bufbuild/protocompile v0.14.1/go.mod h1:ppVdAIhbr2H8asPk6k4pY7t9zB1OU5DoEw9xY/FUi1c=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk=
|
||||
github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs=
|
||||
github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k=
|
||||
github.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M=
|
||||
github.com/hashicorp/go-plugin v1.7.0 h1:YghfQH/0QmPNc/AZMTFE3ac8fipZyZECHdDPshfk+mA=
|
||||
github.com/hashicorp/go-plugin v1.7.0/go.mod h1:BExt6KEaIYx804z8k4gRzRLEvxKVb+kn0NMcihqOqb8=
|
||||
github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8=
|
||||
github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
|
||||
github.com/hashicorp/terraform-plugin-framework v1.17.0 h1:JdX50CFrYcYFY31gkmitAEAzLKoBgsK+iaJjDC8OexY=
|
||||
github.com/hashicorp/terraform-plugin-framework v1.17.0/go.mod h1:4OUXKdHNosX+ys6rLgVlgklfxN3WHR5VHSOABeS/BM0=
|
||||
github.com/hashicorp/terraform-plugin-go v0.29.0 h1:1nXKl/nSpaYIUBU1IG/EsDOX0vv+9JxAltQyDMpq5mU=
|
||||
github.com/hashicorp/terraform-plugin-go v0.29.0/go.mod h1:vYZbIyvxyy0FWSmDHChCqKvI40cFTDGSb3D8D70i9GM=
|
||||
github.com/hashicorp/terraform-plugin-log v0.10.0 h1:eu2kW6/QBVdN4P3Ju2WiB2W3ObjkAsyfBsL3Wh1fj3g=
|
||||
github.com/hashicorp/terraform-plugin-log v0.10.0/go.mod h1:/9RR5Cv2aAbrqcTSdNmY1NRHP4E3ekrXRGjqORpXyB0=
|
||||
github.com/hashicorp/terraform-registry-address v0.4.0 h1:S1yCGomj30Sao4l5BMPjTGZmCNzuv7/GDTDX99E9gTk=
|
||||
github.com/hashicorp/terraform-registry-address v0.4.0/go.mod h1:LRS1Ay0+mAiRkUyltGT+UHWkIqTFvigGn/LbMshfflE=
|
||||
github.com/hashicorp/terraform-svchost v0.1.1 h1:EZZimZ1GxdqFRinZ1tpJwVxxt49xc/S52uzrw4x0jKQ=
|
||||
github.com/hashicorp/terraform-svchost v0.1.1/go.mod h1:mNsjQfZyf/Jhz35v6/0LWcv26+X7JPS+buii2c9/ctc=
|
||||
github.com/hashicorp/yamux v0.1.2 h1:XtB8kyFOyHXYVFnwT5C3+Bdo8gArse7j2AQ0DA0Uey8=
|
||||
github.com/hashicorp/yamux v0.1.2/go.mod h1:C+zze2n6e/7wshOZep2A70/aQU6QBRWJO/G6FT1wIns=
|
||||
github.com/jhump/protoreflect v1.17.0 h1:qOEr613fac2lOuTgWN4tPAtLL7fUSbuJL5X5XumQh94=
|
||||
github.com/jhump/protoreflect v1.17.0/go.mod h1:h9+vUUL38jiBzck8ck+6G/aeMX8Z4QUY/NiJPwPNi+8=
|
||||
github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
|
||||
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
|
||||
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
|
||||
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mitchellh/go-testing-interface v1.14.1 h1:jrgshOhYAUVNMAJiKbEu7EqAwgJJ2JqpQmpLJOu07cU=
|
||||
github.com/mitchellh/go-testing-interface v1.14.1/go.mod h1:gfgS7OtZj6MA4U1UrDRp04twqAjfvlZyCfX3sDjEym8=
|
||||
github.com/oklog/run v1.1.0 h1:GEenZ1cK0+q0+wsJew9qUg/DyD8k3JzYsZAi5gYi2mA=
|
||||
github.com/oklog/run v1.1.0/go.mod h1:sVPdnTZT1zYwAJeCMu2Th4T21pA3FPOQRfWjQlk7DVU=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals=
|
||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8=
|
||||
github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok=
|
||||
github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g=
|
||||
github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
|
||||
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
|
||||
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
|
||||
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
|
||||
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
|
||||
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
|
||||
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
|
||||
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
|
||||
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
|
||||
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
|
||||
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
|
||||
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=
|
||||
google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,34 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"log"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/providerserver"
|
||||
"github.com/seaweedfs/seaweedfs/terraform/provider/seaweedfs"
|
||||
)
|
||||
|
||||
//go:generate go run github.com/hashicorp/terraform-plugin-docs/cmd/tfplugindocs@v0.25.0 generate --provider-name seaweedfs
|
||||
|
||||
var (
|
||||
version = "dev"
|
||||
commit = "none"
|
||||
date = "unknown"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var debug bool
|
||||
|
||||
flag.BoolVar(&debug, "debug", false, "set to true to run the provider with support for debuggers")
|
||||
flag.Parse()
|
||||
|
||||
opts := providerserver.ServeOpts{
|
||||
Address: "registry.terraform.io/seaweedfs/seaweedfs",
|
||||
Debug: debug,
|
||||
}
|
||||
|
||||
if err := providerserver.Serve(context.Background(), seaweedfs.NewProvider, opts); err != nil {
|
||||
log.Fatal(err.Error())
|
||||
}
|
||||
}
|
||||
Executable
+110
@@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
CHART=${SEAWEEDFS_CHART:-/home/lcosta/work/k8s/seaweedfs/charts/seaweedfs-4.51.0.tgz}
|
||||
NAMESPACE=${SEAWEEDFS_NAMESPACE:-seaweedfs}
|
||||
RELEASE=${SEAWEEDFS_RELEASE:-seaweedfs}
|
||||
PROFILE=${MINIKUBE_PROFILE:-seaweedfs-podman-smoke}
|
||||
|
||||
for tool in minikube kubectl helm tofu curl python3; do
|
||||
command -v "$tool" >/dev/null || {
|
||||
echo "missing required tool: $tool" >&2
|
||||
exit 1
|
||||
}
|
||||
done
|
||||
|
||||
MINIKUBE_ROOTLESS=true minikube -p "$PROFILE" status >/dev/null 2>&1 || {
|
||||
echo "Minikube profile $PROFILE is unavailable. Start it with the host-compatible driver." >&2
|
||||
exit 2
|
||||
}
|
||||
kubectl config use-context "$PROFILE" >/dev/null
|
||||
|
||||
kubectl get namespace "$NAMESPACE" >/dev/null 2>&1 || kubectl create namespace "$NAMESPACE"
|
||||
if ! kubectl -n "$NAMESPACE" get secret seaweedfs-iam-config >/dev/null 2>&1; then
|
||||
IAM_CONFIG=$(mktemp)
|
||||
trap 'rm -f -- "$IAM_CONFIG"' EXIT
|
||||
python3 - "$IAM_CONFIG" <<'PY'
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import sys
|
||||
|
||||
config = {
|
||||
"sts": {
|
||||
"issuer": "https://seaweedfs.test",
|
||||
"signingKey": base64.b64encode(secrets.token_bytes(32)).decode("ascii"),
|
||||
},
|
||||
"roleStore": {"storeType": "memory"},
|
||||
"oidcProviderStore": {"storeType": "memory"},
|
||||
}
|
||||
with open(sys.argv[1], "w", encoding="utf-8") as config_file:
|
||||
json.dump(config, config_file)
|
||||
os.chmod(sys.argv[1], 0o600)
|
||||
PY
|
||||
kubectl -n "$NAMESPACE" create secret generic seaweedfs-iam-config \
|
||||
--from-file=iam-config.json="$IAM_CONFIG" \
|
||||
--dry-run=client -o yaml | kubectl apply -f -
|
||||
rm -f -- "$IAM_CONFIG"
|
||||
trap - EXIT
|
||||
fi
|
||||
helm upgrade --install "$RELEASE" "$CHART" \
|
||||
--namespace "$NAMESPACE" \
|
||||
--values "$ROOT/test-fixtures/minikube-values.yaml" \
|
||||
--wait --timeout 10m
|
||||
|
||||
kubectl -n "$NAMESPACE" rollout status deployment/"$RELEASE"-all-in-one --timeout=5m
|
||||
|
||||
PORT_FORWARD_LOG=$(mktemp)
|
||||
kubectl -n "$NAMESPACE" port-forward service/"$RELEASE"-all-in-one 8333:8333 >"$PORT_FORWARD_LOG" 2>&1 &
|
||||
PF_PID=$!
|
||||
cleanup() {
|
||||
kill "$PF_PID" 2>/dev/null || true
|
||||
rm -f -- "$PORT_FORWARD_LOG"
|
||||
if [[ -n "${TMP_CONFIG:-}" ]]; then
|
||||
rm -f -- "$TMP_CONFIG"
|
||||
fi
|
||||
}
|
||||
trap cleanup EXIT
|
||||
trap 'exit 130' INT
|
||||
trap 'exit 143' TERM
|
||||
|
||||
attempt=1
|
||||
while [ "$attempt" -le 30 ]; do
|
||||
if curl -sS --max-time 1 -o /dev/null http://127.0.0.1:8333/ 2>/dev/null; then
|
||||
break
|
||||
fi
|
||||
attempt=$((attempt + 1))
|
||||
sleep 1
|
||||
done
|
||||
if [ "$attempt" -gt 30 ]; then
|
||||
echo "SeaweedFS S3 gateway did not become ready on 127.0.0.1:8333" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p "$ROOT/bin"
|
||||
go build -o "$ROOT/bin/terraform-provider-seaweedfs" "$ROOT/main.go"
|
||||
|
||||
TMP_CONFIG=$(mktemp)
|
||||
cat >"$TMP_CONFIG" <<EOF
|
||||
provider_installation {
|
||||
dev_overrides {
|
||||
"seaweedfs/seaweedfs" = "$ROOT/bin"
|
||||
}
|
||||
direct {}
|
||||
}
|
||||
EOF
|
||||
|
||||
export TF_CLI_CONFIG_FILE="$TMP_CONFIG"
|
||||
export TF_IN_AUTOMATION=1
|
||||
cd "$ROOT/examples/full"
|
||||
tofu validate
|
||||
tofu apply -input=false -auto-approve \
|
||||
-var="seaweedfs_endpoint=http://127.0.0.1:8333" \
|
||||
-var="admin_access_key=terraform-admin" \
|
||||
-var="admin_secret_key=terraform-admin-secret-key-000000000001"
|
||||
tofu plan -input=false -detailed-exitcode \
|
||||
-var="seaweedfs_endpoint=http://127.0.0.1:8333" \
|
||||
-var="admin_access_key=terraform-admin" \
|
||||
-var="admin_secret_key=terraform-admin-secret-key-000000000001"
|
||||
@@ -0,0 +1,605 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
|
||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
s3types "github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
"github.com/aws/smithy-go"
|
||||
)
|
||||
|
||||
type iamClientConfig struct {
|
||||
Endpoint string
|
||||
Region string
|
||||
AccessKey string
|
||||
SecretKey string
|
||||
Insecure bool
|
||||
}
|
||||
|
||||
type iamClient struct {
|
||||
endpoint string
|
||||
region string
|
||||
creds aws.CredentialsProvider
|
||||
signer *v4.Signer
|
||||
http *http.Client
|
||||
s3 *s3.Client
|
||||
}
|
||||
|
||||
type iamError struct {
|
||||
Code string
|
||||
Message string
|
||||
}
|
||||
|
||||
type iamErrorEnvelope struct {
|
||||
Code string `xml:"Code"`
|
||||
Message string `xml:"Message"`
|
||||
Error iamAPIError `xml:"Error"`
|
||||
}
|
||||
|
||||
type iamAPIError struct {
|
||||
Code string `xml:"Code"`
|
||||
Message string `xml:"Message"`
|
||||
}
|
||||
|
||||
type createAccessKeyResponse struct {
|
||||
AccessKey iamAccessKey `xml:"CreateAccessKeyResult>AccessKey"`
|
||||
}
|
||||
|
||||
type listAccessKeysResponse struct {
|
||||
Items []iamAccessKeyMetadata `xml:"ListAccessKeysResult>AccessKeyMetadata>member"`
|
||||
}
|
||||
|
||||
type getUserPolicyResponse struct {
|
||||
UserName string `xml:"GetUserPolicyResult>UserName"`
|
||||
PolicyName string `xml:"GetUserPolicyResult>PolicyName"`
|
||||
PolicyDocument string `xml:"GetUserPolicyResult>PolicyDocument"`
|
||||
}
|
||||
|
||||
type iamAccessKey struct {
|
||||
UserName string `xml:"UserName"`
|
||||
AccessKeyID string `xml:"AccessKeyId"`
|
||||
Status string `xml:"Status"`
|
||||
SecretAccessKey string `xml:"SecretAccessKey"`
|
||||
}
|
||||
|
||||
type iamAccessKeyMetadata struct {
|
||||
UserName string `xml:"UserName"`
|
||||
AccessKeyID string `xml:"AccessKeyId"`
|
||||
Status string `xml:"Status"`
|
||||
}
|
||||
|
||||
type s3Tagging struct {
|
||||
XMLName xml.Name `xml:"Tagging"`
|
||||
TagSet []s3Tag `xml:"TagSet>Tag"`
|
||||
}
|
||||
|
||||
type s3Tag struct {
|
||||
Key string `xml:"Key"`
|
||||
Value string `xml:"Value"`
|
||||
}
|
||||
|
||||
func (e iamError) Error() string {
|
||||
if e.Code == "" && e.Message == "" {
|
||||
return "unknown IAM error"
|
||||
}
|
||||
return fmt.Sprintf("%s: %s", e.Code, e.Message)
|
||||
}
|
||||
|
||||
type createUserResponse struct {
|
||||
User iamUser `xml:"CreateUserResult>User"`
|
||||
}
|
||||
|
||||
type getUserResponse struct {
|
||||
User iamUser `xml:"GetUserResult>User"`
|
||||
}
|
||||
|
||||
type iamUser struct {
|
||||
UserName string `xml:"UserName"`
|
||||
Arn string `xml:"Arn"`
|
||||
UserID string `xml:"UserId"`
|
||||
Path string `xml:"Path"`
|
||||
}
|
||||
|
||||
func newIAMClient(cfg iamClientConfig) (*iamClient, error) {
|
||||
if cfg.Endpoint == "" {
|
||||
return nil, errors.New("endpoint is required")
|
||||
}
|
||||
if cfg.Region == "" {
|
||||
cfg.Region = "us-east-1"
|
||||
}
|
||||
if cfg.AccessKey == "" || cfg.SecretKey == "" {
|
||||
return nil, errors.New("access_key and secret_key are required")
|
||||
}
|
||||
|
||||
tr := &http.Transport{}
|
||||
if cfg.Insecure {
|
||||
tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} //nolint:gosec
|
||||
}
|
||||
|
||||
client := &iamClient{
|
||||
endpoint: strings.TrimRight(cfg.Endpoint, "/"),
|
||||
region: cfg.Region,
|
||||
creds: credentials.NewStaticCredentialsProvider(
|
||||
cfg.AccessKey,
|
||||
cfg.SecretKey,
|
||||
"",
|
||||
),
|
||||
signer: v4.NewSigner(),
|
||||
http: &http.Client{
|
||||
Transport: tr,
|
||||
Timeout: 30 * time.Second,
|
||||
},
|
||||
}
|
||||
|
||||
client.s3 = s3.New(s3.Options{
|
||||
Region: client.region,
|
||||
Credentials: client.creds,
|
||||
HTTPClient: client.http,
|
||||
BaseEndpoint: aws.String(client.endpoint),
|
||||
UsePathStyle: true,
|
||||
})
|
||||
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) CreateUser(ctx context.Context, userName string, path string) (getUserResponse, error) {
|
||||
vals := url.Values{}
|
||||
vals.Set("Action", "CreateUser")
|
||||
vals.Set("Version", "2010-05-08")
|
||||
vals.Set("UserName", userName)
|
||||
if path != "" {
|
||||
vals.Set("Path", path)
|
||||
}
|
||||
|
||||
var out createUserResponse
|
||||
if err := c.doIAMAction(ctx, vals, &out); err != nil {
|
||||
return getUserResponse{}, err
|
||||
}
|
||||
|
||||
return getUserResponse{User: out.User}, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) GetUser(ctx context.Context, userName string) (getUserResponse, error) {
|
||||
vals := url.Values{}
|
||||
vals.Set("Action", "GetUser")
|
||||
vals.Set("Version", "2010-05-08")
|
||||
vals.Set("UserName", userName)
|
||||
|
||||
var out getUserResponse
|
||||
if err := c.doIAMAction(ctx, vals, &out); err != nil {
|
||||
return getUserResponse{}, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) DeleteUser(ctx context.Context, userName string) error {
|
||||
vals := url.Values{}
|
||||
vals.Set("Action", "DeleteUser")
|
||||
vals.Set("Version", "2010-05-08")
|
||||
vals.Set("UserName", userName)
|
||||
|
||||
return c.doIAMAction(ctx, vals, nil)
|
||||
}
|
||||
|
||||
func (c *iamClient) CreateAccessKey(ctx context.Context, userName string) (iamAccessKey, error) {
|
||||
vals := url.Values{}
|
||||
vals.Set("Action", "CreateAccessKey")
|
||||
vals.Set("Version", "2010-05-08")
|
||||
vals.Set("UserName", userName)
|
||||
|
||||
var out createAccessKeyResponse
|
||||
if err := c.doIAMAction(ctx, vals, &out); err != nil {
|
||||
return iamAccessKey{}, err
|
||||
}
|
||||
|
||||
return out.AccessKey, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) ListAccessKeys(ctx context.Context, userName string) ([]iamAccessKeyMetadata, error) {
|
||||
vals := url.Values{}
|
||||
vals.Set("Action", "ListAccessKeys")
|
||||
vals.Set("Version", "2010-05-08")
|
||||
vals.Set("UserName", userName)
|
||||
|
||||
var out listAccessKeysResponse
|
||||
if err := c.doIAMAction(ctx, vals, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out.Items, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) DeleteAccessKey(ctx context.Context, userName string, accessKeyID string) error {
|
||||
vals := url.Values{}
|
||||
vals.Set("Action", "DeleteAccessKey")
|
||||
vals.Set("Version", "2010-05-08")
|
||||
vals.Set("UserName", userName)
|
||||
vals.Set("AccessKeyId", accessKeyID)
|
||||
|
||||
return c.doIAMAction(ctx, vals, nil)
|
||||
}
|
||||
|
||||
func (c *iamClient) PutUserPolicy(ctx context.Context, userName string, policyName string, policyDocument string) error {
|
||||
vals := url.Values{}
|
||||
vals.Set("Action", "PutUserPolicy")
|
||||
vals.Set("Version", "2010-05-08")
|
||||
vals.Set("UserName", userName)
|
||||
vals.Set("PolicyName", policyName)
|
||||
vals.Set("PolicyDocument", policyDocument)
|
||||
|
||||
return c.doIAMAction(ctx, vals, nil)
|
||||
}
|
||||
|
||||
func (c *iamClient) GetUserPolicy(ctx context.Context, userName string, policyName string) (string, error) {
|
||||
vals := url.Values{}
|
||||
vals.Set("Action", "GetUserPolicy")
|
||||
vals.Set("Version", "2010-05-08")
|
||||
vals.Set("UserName", userName)
|
||||
vals.Set("PolicyName", policyName)
|
||||
|
||||
var out getUserPolicyResponse
|
||||
if err := c.doIAMAction(ctx, vals, &out); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
decoded, err := url.QueryUnescape(out.PolicyDocument)
|
||||
if err != nil {
|
||||
return out.PolicyDocument, nil
|
||||
}
|
||||
return decoded, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) DeleteUserPolicy(ctx context.Context, userName string, policyName string) error {
|
||||
vals := url.Values{}
|
||||
vals.Set("Action", "DeleteUserPolicy")
|
||||
vals.Set("Version", "2010-05-08")
|
||||
vals.Set("UserName", userName)
|
||||
vals.Set("PolicyName", policyName)
|
||||
|
||||
return c.doIAMAction(ctx, vals, nil)
|
||||
}
|
||||
|
||||
func (c *iamClient) CreateBucket(ctx context.Context, name string) error {
|
||||
path := "/" + name
|
||||
_, err := c.doSignedRequest(ctx, "s3", http.MethodPut, c.endpoint+path, "", "", nil)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *iamClient) HeadBucket(ctx context.Context, name string) error {
|
||||
path := "/" + name
|
||||
_, err := c.doSignedRequest(ctx, "s3", http.MethodHead, c.endpoint+path, "", "", nil)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *iamClient) DeleteBucket(ctx context.Context, name string) error {
|
||||
path := "/" + name
|
||||
_, err := c.doSignedRequest(ctx, "s3", http.MethodDelete, c.endpoint+path, "", "", nil)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *iamClient) GetBucketTags(ctx context.Context, name string) (map[string]string, error) {
|
||||
out, err := c.s3.GetBucketTagging(ctx, &s3.GetBucketTaggingInput{
|
||||
Bucket: aws.String(name),
|
||||
})
|
||||
if err != nil {
|
||||
if isNoSuchTagSetError(err) {
|
||||
return map[string]string{}, nil
|
||||
}
|
||||
return nil, fmt.Errorf("get bucket tagging: %w", err)
|
||||
}
|
||||
|
||||
tags := make(map[string]string, len(out.TagSet))
|
||||
for _, tag := range out.TagSet {
|
||||
tags[aws.ToString(tag.Key)] = aws.ToString(tag.Value)
|
||||
}
|
||||
return tags, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) PutBucketTags(ctx context.Context, name string, tags map[string]string) error {
|
||||
keys := make([]string, 0, len(tags))
|
||||
for k := range tags {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
|
||||
tagSet := make([]s3types.Tag, 0, len(tags))
|
||||
for _, key := range keys {
|
||||
value := tags[key]
|
||||
tagSet = append(tagSet, s3types.Tag{
|
||||
Key: aws.String(key),
|
||||
Value: aws.String(value),
|
||||
})
|
||||
}
|
||||
|
||||
_, err := c.s3.PutBucketTagging(ctx, &s3.PutBucketTaggingInput{
|
||||
Bucket: aws.String(name),
|
||||
Tagging: &s3types.Tagging{
|
||||
TagSet: tagSet,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("put bucket tagging: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *iamClient) DeleteBucketTags(ctx context.Context, name string) error {
|
||||
_, err := c.s3.DeleteBucketTagging(ctx, &s3.DeleteBucketTaggingInput{
|
||||
Bucket: aws.String(name),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete bucket tagging: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *iamClient) doIAMAction(ctx context.Context, form url.Values, out any) error {
|
||||
body := form.Encode()
|
||||
_, err := c.doSignedRequest(
|
||||
ctx,
|
||||
"iam",
|
||||
http.MethodPost,
|
||||
c.endpoint+"/",
|
||||
"application/x-www-form-urlencoded",
|
||||
body,
|
||||
out,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *iamClient) doSignedRequest(
|
||||
ctx context.Context,
|
||||
service string,
|
||||
method string,
|
||||
requestURL string,
|
||||
contentType string,
|
||||
body string,
|
||||
out any,
|
||||
) ([]byte, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, method, requestURL, bytes.NewBufferString(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if contentType != "" {
|
||||
req.Header.Set("Content-Type", contentType)
|
||||
}
|
||||
req.Header.Set("Host", req.URL.Host)
|
||||
|
||||
creds, err := c.creds.Retrieve(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("retrieve credentials: %w", err)
|
||||
}
|
||||
|
||||
sum := sha256.Sum256([]byte(body))
|
||||
hash := fmt.Sprintf("%x", sum)
|
||||
if service == "s3" {
|
||||
req.Header.Set("X-Amz-Content-Sha256", hash)
|
||||
}
|
||||
ctx = v4.SetPayloadHash(ctx, hash)
|
||||
|
||||
if err := c.signer.SignHTTP(ctx, creds, req, hash, service, c.region, time.Now()); err != nil {
|
||||
return nil, fmt.Errorf("sign request: %w", err)
|
||||
}
|
||||
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read response body: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode >= 400 {
|
||||
return nil, parseAPIError(resp.StatusCode, data)
|
||||
}
|
||||
|
||||
if out != nil {
|
||||
if err := xml.Unmarshal(data, out); err != nil {
|
||||
return nil, fmt.Errorf("decode xml response: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func parseAPIError(status int, data []byte) error {
|
||||
var envelope iamErrorEnvelope
|
||||
if xmlErr := xml.Unmarshal(data, &envelope); xmlErr == nil {
|
||||
apiErr := iamError{
|
||||
Code: envelope.Error.Code,
|
||||
Message: envelope.Error.Message,
|
||||
}
|
||||
if apiErr.Code == "" {
|
||||
apiErr.Code = envelope.Code
|
||||
}
|
||||
if apiErr.Message == "" {
|
||||
apiErr.Message = envelope.Message
|
||||
}
|
||||
if apiErr.Code == "" || apiErr.Message == "" {
|
||||
var direct iamAPIError
|
||||
if xmlErr := xml.Unmarshal(data, &direct); xmlErr == nil {
|
||||
if apiErr.Code == "" {
|
||||
apiErr.Code = direct.Code
|
||||
}
|
||||
if apiErr.Message == "" {
|
||||
apiErr.Message = direct.Message
|
||||
}
|
||||
}
|
||||
}
|
||||
if apiErr.Code != "" || apiErr.Message != "" {
|
||||
if apiErr.Code == "" {
|
||||
apiErr.Code = fmt.Sprintf("HTTP%d", status)
|
||||
}
|
||||
if apiErr.Message == "" {
|
||||
apiErr.Message = strings.TrimSpace(string(data))
|
||||
}
|
||||
return apiErr
|
||||
}
|
||||
}
|
||||
|
||||
var jsonAPIError struct {
|
||||
Code string `json:"code"`
|
||||
Type string `json:"__type"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
if jsonErr := json.Unmarshal(data, &jsonAPIError); jsonErr == nil && (jsonAPIError.Code != "" || jsonAPIError.Type != "") {
|
||||
if jsonAPIError.Code == "" {
|
||||
jsonAPIError.Code = jsonAPIError.Type
|
||||
}
|
||||
if separator := strings.LastIndex(jsonAPIError.Code, "#"); separator >= 0 {
|
||||
jsonAPIError.Code = jsonAPIError.Code[separator+1:]
|
||||
}
|
||||
return iamError{
|
||||
Code: jsonAPIError.Code,
|
||||
Message: jsonAPIError.Message,
|
||||
}
|
||||
}
|
||||
|
||||
return iamError{
|
||||
Code: fmt.Sprintf("HTTP%d", status),
|
||||
Message: strings.TrimSpace(string(data)),
|
||||
}
|
||||
}
|
||||
|
||||
func isNoSuchEntityError(err error) bool {
|
||||
var apiErr iamError
|
||||
if errors.As(err, &apiErr) {
|
||||
return apiErr.Code == "NoSuchEntity"
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isEntityAlreadyExistsError(err error) bool {
|
||||
var apiErr iamError
|
||||
if errors.As(err, &apiErr) {
|
||||
return apiErr.Code == "EntityAlreadyExists"
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isServiceFailureError(err error) bool {
|
||||
var apiErr iamError
|
||||
if errors.As(err, &apiErr) {
|
||||
return apiErr.Code == "ServiceFailure" || apiErr.Code == "HTTP500" || apiErr.Code == "HTTP503"
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isRetryableIAMError(err error) bool {
|
||||
return isNoSuchEntityError(err) || isServiceFailureError(err)
|
||||
}
|
||||
|
||||
func retryIAMEventuallyConsistent(ctx context.Context, attempts int, fn func() error) error {
|
||||
if attempts < 1 {
|
||||
attempts = 1
|
||||
}
|
||||
|
||||
delay := 200 * time.Millisecond
|
||||
var lastErr error
|
||||
|
||||
for i := 0; i < attempts; i++ {
|
||||
err := fn()
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if !isRetryableIAMError(err) {
|
||||
return err
|
||||
}
|
||||
|
||||
lastErr = err
|
||||
if i == attempts-1 {
|
||||
break
|
||||
}
|
||||
|
||||
timer := time.NewTimer(delay)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
}
|
||||
|
||||
delay *= 2
|
||||
if delay > 2*time.Second {
|
||||
delay = 2 * time.Second
|
||||
}
|
||||
}
|
||||
|
||||
return lastErr
|
||||
}
|
||||
|
||||
func retryIAMRead(ctx context.Context, attempts int, fn func() error) error {
|
||||
if attempts < 1 {
|
||||
attempts = 1
|
||||
}
|
||||
|
||||
delay := 200 * time.Millisecond
|
||||
var lastErr error
|
||||
for i := 0; i < attempts; i++ {
|
||||
err := fn()
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if isNoSuchEntityError(err) || !isServiceFailureError(err) {
|
||||
return err
|
||||
}
|
||||
|
||||
lastErr = err
|
||||
if i == attempts-1 {
|
||||
break
|
||||
}
|
||||
|
||||
timer := time.NewTimer(delay)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
delay *= 2
|
||||
}
|
||||
}
|
||||
return lastErr
|
||||
}
|
||||
|
||||
func isNoSuchBucketError(err error) bool {
|
||||
var apiErr iamError
|
||||
if errors.As(err, &apiErr) {
|
||||
return apiErr.Code == "NoSuchBucket" || apiErr.Code == "NotFound" || apiErr.Code == "HTTP404" || apiErr.Code == "NoSuchKey" || apiErr.Code == "NoSuchEntity"
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isBucketAlreadyExistsError(err error) bool {
|
||||
var apiErr iamError
|
||||
if errors.As(err, &apiErr) {
|
||||
return apiErr.Code == "BucketAlreadyOwnedByYou" || apiErr.Code == "BucketAlreadyExists"
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isNoSuchTagSetError(err error) bool {
|
||||
var apiErr smithy.APIError
|
||||
if errors.As(err, &apiErr) {
|
||||
return apiErr.ErrorCode() == "NoSuchTagSet"
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type iamAttachedPolicy struct {
|
||||
Name string `xml:"PolicyName"`
|
||||
ARN string `xml:"PolicyArn"`
|
||||
}
|
||||
|
||||
func (c *iamClient) AttachManagedPolicy(ctx context.Context, principalType, principalName, policyARN string, attach bool) error {
|
||||
action := "Attach" + titleIAMPrincipal(principalType) + "Policy"
|
||||
if !attach {
|
||||
action = "Detach" + titleIAMPrincipal(principalType) + "Policy"
|
||||
}
|
||||
values := iamActionValues(action)
|
||||
values.Set(titleIAMPrincipal(principalType)+"Name", principalName)
|
||||
values.Set("PolicyArn", policyARN)
|
||||
if err := c.doIAMAction(ctx, values, nil); err != nil {
|
||||
return fmt.Errorf("%s managed policy: %w", action, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *iamClient) ListAttachedManagedPolicies(ctx context.Context, principalType, principalName string) ([]iamAttachedPolicy, error) {
|
||||
action := "ListAttached" + titleIAMPrincipal(principalType) + "Policies"
|
||||
values := iamActionValues(action)
|
||||
values.Set(titleIAMPrincipal(principalType)+"Name", principalName)
|
||||
|
||||
var response struct {
|
||||
UserResult struct {
|
||||
Policies []iamAttachedPolicy `xml:"AttachedPolicies>member"`
|
||||
} `xml:"ListAttachedUserPoliciesResult"`
|
||||
GroupResult struct {
|
||||
Policies []iamAttachedPolicy `xml:"AttachedPolicies>member"`
|
||||
} `xml:"ListAttachedGroupPoliciesResult"`
|
||||
RoleResult struct {
|
||||
Policies []iamAttachedPolicy `xml:"AttachedPolicies>member"`
|
||||
} `xml:"ListAttachedRolePoliciesResult"`
|
||||
}
|
||||
if err := c.doIAMAction(ctx, values, &response); err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", action, err)
|
||||
}
|
||||
|
||||
switch principalType {
|
||||
case "user":
|
||||
return response.UserResult.Policies, nil
|
||||
case "group":
|
||||
return response.GroupResult.Policies, nil
|
||||
case "role":
|
||||
return response.RoleResult.Policies, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported IAM principal type %q", principalType)
|
||||
}
|
||||
}
|
||||
|
||||
func titleIAMPrincipal(principalType string) string {
|
||||
switch principalType {
|
||||
case "user":
|
||||
return "User"
|
||||
case "group":
|
||||
return "Group"
|
||||
case "role":
|
||||
return "Role"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func (c *iamClient) PutGroupPolicy(ctx context.Context, groupName, policyName, document string) error {
|
||||
values := iamActionValues("PutGroupPolicy")
|
||||
values.Set("GroupName", groupName)
|
||||
values.Set("PolicyName", policyName)
|
||||
values.Set("PolicyDocument", document)
|
||||
if err := c.doIAMAction(ctx, values, nil); err != nil {
|
||||
return fmt.Errorf("put group policy: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *iamClient) GetGroupPolicy(ctx context.Context, groupName, policyName string) (string, error) {
|
||||
values := iamActionValues("GetGroupPolicy")
|
||||
values.Set("GroupName", groupName)
|
||||
values.Set("PolicyName", policyName)
|
||||
var response struct {
|
||||
Result struct {
|
||||
PolicyDocument string `xml:"PolicyDocument"`
|
||||
} `xml:"GetGroupPolicyResult"`
|
||||
}
|
||||
if err := c.doIAMAction(ctx, values, &response); err != nil {
|
||||
return "", fmt.Errorf("get group policy: %w", err)
|
||||
}
|
||||
document, err := decodeIAMDocument(response.Result.PolicyDocument)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("decode group policy: %w", err)
|
||||
}
|
||||
return document, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) DeleteGroupPolicy(ctx context.Context, groupName, policyName string) error {
|
||||
values := iamActionValues("DeleteGroupPolicy")
|
||||
values.Set("GroupName", groupName)
|
||||
values.Set("PolicyName", policyName)
|
||||
if err := c.doIAMAction(ctx, values, nil); err != nil {
|
||||
return fmt.Errorf("delete group policy: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type iamGroup struct {
|
||||
Name string `xml:"GroupName"`
|
||||
Users []iamGroupUser `xml:"Users>member"`
|
||||
}
|
||||
|
||||
type iamGroupUser struct {
|
||||
Name string `xml:"UserName"`
|
||||
}
|
||||
|
||||
func (c *iamClient) CreateGroup(ctx context.Context, name string) error {
|
||||
values := iamActionValues("CreateGroup")
|
||||
values.Set("GroupName", name)
|
||||
if err := c.doIAMAction(ctx, values, nil); err != nil {
|
||||
return fmt.Errorf("create group: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *iamClient) GetGroup(ctx context.Context, name string) (iamGroup, error) {
|
||||
values := iamActionValues("GetGroup")
|
||||
values.Set("GroupName", name)
|
||||
|
||||
var response struct {
|
||||
Result struct {
|
||||
Group struct {
|
||||
Name string `xml:"GroupName"`
|
||||
} `xml:"Group"`
|
||||
Users []iamGroupUser `xml:"Users>member"`
|
||||
} `xml:"GetGroupResult"`
|
||||
}
|
||||
if err := c.doIAMAction(ctx, values, &response); err != nil {
|
||||
return iamGroup{}, fmt.Errorf("get group: %w", err)
|
||||
}
|
||||
return iamGroup{Name: response.Result.Group.Name, Users: response.Result.Users}, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) DeleteGroup(ctx context.Context, name string) error {
|
||||
values := iamActionValues("DeleteGroup")
|
||||
values.Set("GroupName", name)
|
||||
if err := c.doIAMAction(ctx, values, nil); err != nil {
|
||||
return fmt.Errorf("delete group: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *iamClient) AddUserToGroup(ctx context.Context, groupName, userName string) error {
|
||||
values := iamActionValues("AddUserToGroup")
|
||||
values.Set("GroupName", groupName)
|
||||
values.Set("UserName", userName)
|
||||
if err := c.doIAMAction(ctx, values, nil); err != nil {
|
||||
return fmt.Errorf("add user %q to group %q: %w", userName, groupName, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *iamClient) RemoveUserFromGroup(ctx context.Context, groupName, userName string) error {
|
||||
values := iamActionValues("RemoveUserFromGroup")
|
||||
values.Set("GroupName", groupName)
|
||||
values.Set("UserName", userName)
|
||||
if err := c.doIAMAction(ctx, values, nil); err != nil {
|
||||
return fmt.Errorf("remove user %q from group %q: %w", userName, groupName, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
type iamOIDCProvider struct {
|
||||
ARN string `xml:"OpenIDConnectProviderArn"`
|
||||
URL string `xml:"Url"`
|
||||
ClientIDs []string `xml:"ClientIDList>member"`
|
||||
Thumbprints []string `xml:"ThumbprintList>member"`
|
||||
}
|
||||
|
||||
func (c *iamClient) CreateOIDCProvider(ctx context.Context, providerURL string, clientIDs, thumbprints []string) (string, error) {
|
||||
values := iamActionValues("CreateOpenIDConnectProvider")
|
||||
values.Set("Url", providerURL)
|
||||
setIAMMembers(values, "ClientIDList", clientIDs)
|
||||
setIAMMembers(values, "ThumbprintList", thumbprints)
|
||||
var response struct {
|
||||
Result struct {
|
||||
ARN string `xml:"OpenIDConnectProviderArn"`
|
||||
} `xml:"CreateOpenIDConnectProviderResult"`
|
||||
}
|
||||
if err := c.doIAMAction(ctx, values, &response); err != nil {
|
||||
return "", fmt.Errorf("create OIDC provider: %w", err)
|
||||
}
|
||||
return response.Result.ARN, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) GetOIDCProvider(ctx context.Context, arn string) (iamOIDCProvider, error) {
|
||||
values := iamActionValues("GetOpenIDConnectProvider")
|
||||
values.Set("OpenIDConnectProviderArn", arn)
|
||||
var response struct {
|
||||
Result iamOIDCProvider `xml:"GetOpenIDConnectProviderResult"`
|
||||
}
|
||||
if err := c.doIAMAction(ctx, values, &response); err != nil {
|
||||
return iamOIDCProvider{}, fmt.Errorf("get OIDC provider: %w", err)
|
||||
}
|
||||
response.Result.ARN = arn
|
||||
return response.Result, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) DeleteOIDCProvider(ctx context.Context, arn string) error {
|
||||
values := iamActionValues("DeleteOpenIDConnectProvider")
|
||||
values.Set("OpenIDConnectProviderArn", arn)
|
||||
if err := c.doIAMAction(ctx, values, nil); err != nil {
|
||||
return fmt.Errorf("delete OIDC provider: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *iamClient) AddOIDCClientID(ctx context.Context, arn, clientID string) error {
|
||||
values := iamActionValues("AddClientIDToOpenIDConnectProvider")
|
||||
values.Set("OpenIDConnectProviderArn", arn)
|
||||
values.Set("ClientID", clientID)
|
||||
if err := c.doIAMAction(ctx, values, nil); err != nil {
|
||||
return fmt.Errorf("add OIDC client ID: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *iamClient) RemoveOIDCClientID(ctx context.Context, arn, clientID string) error {
|
||||
values := iamActionValues("RemoveClientIDFromOpenIDConnectProvider")
|
||||
values.Set("OpenIDConnectProviderArn", arn)
|
||||
values.Set("ClientID", clientID)
|
||||
if err := c.doIAMAction(ctx, values, nil); err != nil {
|
||||
return fmt.Errorf("remove OIDC client ID: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *iamClient) UpdateOIDCThumbprints(ctx context.Context, arn string, thumbprints []string) error {
|
||||
values := iamActionValues("UpdateOpenIDConnectProviderThumbprint")
|
||||
values.Set("OpenIDConnectProviderArn", arn)
|
||||
setIAMMembers(values, "ThumbprintList", thumbprints)
|
||||
if err := c.doIAMAction(ctx, values, nil); err != nil {
|
||||
return fmt.Errorf("update OIDC thumbprints: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func setIAMMembers(values url.Values, key string, members []string) {
|
||||
for index, member := range members {
|
||||
values.Set(fmt.Sprintf("%s.member.%d", key, index+1), member)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type iamManagedPolicy struct {
|
||||
Name string `xml:"PolicyName"`
|
||||
ARN string `xml:"Arn"`
|
||||
DefaultVersion string `xml:"DefaultVersionId"`
|
||||
}
|
||||
|
||||
func (c *iamClient) CreateManagedPolicy(ctx context.Context, name, document string) (iamManagedPolicy, error) {
|
||||
values := iamActionValues("CreatePolicy")
|
||||
values.Set("PolicyName", name)
|
||||
values.Set("PolicyDocument", document)
|
||||
var response struct {
|
||||
Result struct {
|
||||
Policy iamManagedPolicy `xml:"Policy"`
|
||||
} `xml:"CreatePolicyResult"`
|
||||
}
|
||||
if err := c.doIAMAction(ctx, values, &response); err != nil {
|
||||
return iamManagedPolicy{}, fmt.Errorf("create managed policy: %w", err)
|
||||
}
|
||||
return response.Result.Policy, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) GetManagedPolicy(ctx context.Context, arn string) (iamManagedPolicy, error) {
|
||||
values := iamActionValues("GetPolicy")
|
||||
values.Set("PolicyArn", arn)
|
||||
var response struct {
|
||||
Result struct {
|
||||
Policy iamManagedPolicy `xml:"Policy"`
|
||||
} `xml:"GetPolicyResult"`
|
||||
}
|
||||
if err := c.doIAMAction(ctx, values, &response); err != nil {
|
||||
return iamManagedPolicy{}, fmt.Errorf("get managed policy: %w", err)
|
||||
}
|
||||
return response.Result.Policy, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) GetManagedPolicyDocument(ctx context.Context, arn, version string) (string, error) {
|
||||
values := iamActionValues("GetPolicyVersion")
|
||||
values.Set("PolicyArn", arn)
|
||||
values.Set("VersionId", version)
|
||||
var response struct {
|
||||
Result struct {
|
||||
Version struct {
|
||||
Document string `xml:"Document"`
|
||||
} `xml:"PolicyVersion"`
|
||||
} `xml:"GetPolicyVersionResult"`
|
||||
}
|
||||
if err := c.doIAMAction(ctx, values, &response); err != nil {
|
||||
return "", fmt.Errorf("get managed policy document: %w", err)
|
||||
}
|
||||
document, err := decodeIAMDocument(response.Result.Version.Document)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("decode managed policy document: %w", err)
|
||||
}
|
||||
return document, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) UpdateManagedPolicy(ctx context.Context, arn, document string) error {
|
||||
values := iamActionValues("CreatePolicyVersion")
|
||||
values.Set("PolicyArn", arn)
|
||||
values.Set("PolicyDocument", document)
|
||||
values.Set("SetAsDefault", "true")
|
||||
if err := c.doIAMAction(ctx, values, nil); err != nil {
|
||||
return fmt.Errorf("update managed policy: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *iamClient) DeleteManagedPolicy(ctx context.Context, arn string) error {
|
||||
values := iamActionValues("DeletePolicy")
|
||||
values.Set("PolicyArn", arn)
|
||||
if err := c.doIAMAction(ctx, values, nil); err != nil {
|
||||
return fmt.Errorf("delete managed policy: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func iamPolicyARN(name string) string {
|
||||
return "arn:aws:iam:::policy/" + name
|
||||
}
|
||||
|
||||
func iamPolicyNameFromARN(arn string) (string, error) {
|
||||
const delimiter = ":policy/"
|
||||
found := strings.LastIndex(arn, delimiter)
|
||||
if found < 0 {
|
||||
return "", fmt.Errorf("invalid managed policy ARN %q", arn)
|
||||
}
|
||||
name := arn[found+len(delimiter):]
|
||||
if name == "" || strings.Contains(name, "/") {
|
||||
return "", fmt.Errorf("invalid managed policy ARN %q", arn)
|
||||
}
|
||||
return name, nil
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type iamRole struct {
|
||||
Name string `xml:"RoleName"`
|
||||
ID string `xml:"RoleId"`
|
||||
ARN string `xml:"Arn"`
|
||||
Path string `xml:"Path"`
|
||||
AssumeRolePolicy string `xml:"AssumeRolePolicyDocument"`
|
||||
Description string `xml:"Description"`
|
||||
MaxSessionDuration int64 `xml:"MaxSessionDuration"`
|
||||
}
|
||||
|
||||
func (c *iamClient) CreateRole(ctx context.Context, name, trustPolicy, description string, maxSessionDuration int64) (iamRole, error) {
|
||||
values := iamActionValues("CreateRole")
|
||||
values.Set("RoleName", name)
|
||||
values.Set("AssumeRolePolicyDocument", trustPolicy)
|
||||
if description != "" {
|
||||
values.Set("Description", description)
|
||||
}
|
||||
if maxSessionDuration != 0 {
|
||||
values.Set("MaxSessionDuration", strconv.FormatInt(maxSessionDuration, 10))
|
||||
}
|
||||
|
||||
var response struct {
|
||||
Result struct {
|
||||
Role iamRole `xml:"Role"`
|
||||
} `xml:"CreateRoleResult"`
|
||||
}
|
||||
if err := c.doIAMAction(ctx, values, &response); err != nil {
|
||||
return iamRole{}, fmt.Errorf("create role: %w", err)
|
||||
}
|
||||
decoded, err := decodeIAMDocument(response.Result.Role.AssumeRolePolicy)
|
||||
if err != nil {
|
||||
return iamRole{}, fmt.Errorf("decode role trust policy: %w", err)
|
||||
}
|
||||
response.Result.Role.AssumeRolePolicy = decoded
|
||||
return response.Result.Role, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) GetRole(ctx context.Context, name string) (iamRole, error) {
|
||||
values := iamActionValues("GetRole")
|
||||
values.Set("RoleName", name)
|
||||
|
||||
var response struct {
|
||||
Result struct {
|
||||
Role iamRole `xml:"Role"`
|
||||
} `xml:"GetRoleResult"`
|
||||
}
|
||||
if err := c.doIAMAction(ctx, values, &response); err != nil {
|
||||
return iamRole{}, fmt.Errorf("get role: %w", err)
|
||||
}
|
||||
var err error
|
||||
response.Result.Role.AssumeRolePolicy, err = decodeIAMDocument(response.Result.Role.AssumeRolePolicy)
|
||||
if err != nil {
|
||||
return iamRole{}, fmt.Errorf("decode role trust policy: %w", err)
|
||||
}
|
||||
return response.Result.Role, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) UpdateAssumeRolePolicy(ctx context.Context, name, trustPolicy string) error {
|
||||
values := iamActionValues("UpdateAssumeRolePolicy")
|
||||
values.Set("RoleName", name)
|
||||
values.Set("PolicyDocument", trustPolicy)
|
||||
if err := c.doIAMAction(ctx, values, nil); err != nil {
|
||||
return fmt.Errorf("update role trust policy: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *iamClient) DeleteRole(ctx context.Context, name string) error {
|
||||
values := iamActionValues("DeleteRole")
|
||||
values.Set("RoleName", name)
|
||||
if err := c.doIAMAction(ctx, values, nil); err != nil {
|
||||
return fmt.Errorf("delete role: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func iamActionValues(action string) url.Values {
|
||||
values := url.Values{}
|
||||
values.Set("Action", action)
|
||||
values.Set("Version", "2010-05-08")
|
||||
return values
|
||||
}
|
||||
|
||||
func parseIAMImportID(id string) (string, error) {
|
||||
if id == "" || strings.TrimSpace(id) != id {
|
||||
return "", fmt.Errorf("expected a non-empty IAM resource name")
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func decodeIAMDocument(document string) (string, error) {
|
||||
if document == "" {
|
||||
return "", nil
|
||||
}
|
||||
decoded, err := url.QueryUnescape(document)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return decoded, nil
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type iamServiceAccount struct {
|
||||
ID string `xml:"ServiceAccountId"`
|
||||
ParentUser string `xml:"ParentUser"`
|
||||
Description string `xml:"Description"`
|
||||
AccessKeyID string `xml:"AccessKeyId"`
|
||||
SecretAccessKey string `xml:"SecretAccessKey"`
|
||||
Status string `xml:"Status"`
|
||||
CreateDate string `xml:"CreateDate"`
|
||||
Expiration string `xml:"Expiration"`
|
||||
}
|
||||
|
||||
func (c *iamClient) CreateServiceAccount(ctx context.Context, parentUser, description, expiration string) (iamServiceAccount, error) {
|
||||
values := iamActionValues("CreateServiceAccount")
|
||||
values.Set("ParentUser", parentUser)
|
||||
values.Set("Description", description)
|
||||
if expiration != "" {
|
||||
values.Set("Expiration", expiration)
|
||||
}
|
||||
var response struct {
|
||||
Result struct {
|
||||
Account iamServiceAccount `xml:"ServiceAccount"`
|
||||
} `xml:"CreateServiceAccountResult"`
|
||||
}
|
||||
if err := c.doIAMAction(ctx, values, &response); err != nil {
|
||||
return iamServiceAccount{}, fmt.Errorf("create service account: %w", err)
|
||||
}
|
||||
return response.Result.Account, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) GetServiceAccount(ctx context.Context, id string) (iamServiceAccount, error) {
|
||||
values := iamActionValues("GetServiceAccount")
|
||||
values.Set("ServiceAccountId", id)
|
||||
var response struct {
|
||||
Result struct {
|
||||
Account iamServiceAccount `xml:"ServiceAccount"`
|
||||
} `xml:"GetServiceAccountResult"`
|
||||
}
|
||||
if err := c.doIAMAction(ctx, values, &response); err != nil {
|
||||
return iamServiceAccount{}, fmt.Errorf("get service account: %w", err)
|
||||
}
|
||||
return response.Result.Account, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) UpdateServiceAccount(ctx context.Context, id, status, description, expiration string) error {
|
||||
values := iamActionValues("UpdateServiceAccount")
|
||||
values.Set("ServiceAccountId", id)
|
||||
if status != "" {
|
||||
values.Set("Status", status)
|
||||
}
|
||||
values.Set("Description", description)
|
||||
values.Set("Expiration", expiration)
|
||||
if err := c.doIAMAction(ctx, values, nil); err != nil {
|
||||
return fmt.Errorf("update service account: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *iamClient) DeleteServiceAccount(ctx context.Context, id string) error {
|
||||
values := iamActionValues("DeleteServiceAccount")
|
||||
values.Set("ServiceAccountId", id)
|
||||
if err := c.doIAMAction(ctx, values, nil); err != nil {
|
||||
return fmt.Errorf("delete service account: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
const (
|
||||
s3TableMaintenanceCompaction = "icebergCompaction"
|
||||
s3TableMaintenanceSnapshotManagement = "icebergSnapshotManagement"
|
||||
s3TableMaintenanceUnreferencedFiles = "icebergUnreferencedFileRemoval"
|
||||
)
|
||||
|
||||
type s3TableMaintenanceSettings struct {
|
||||
IcebergCompaction *s3TableCompactionSettings `json:"icebergCompaction,omitempty"`
|
||||
IcebergSnapshotManagement *s3TableSnapshotManagementSettings `json:"icebergSnapshotManagement,omitempty"`
|
||||
IcebergUnreferencedFileRemoval *s3TableUnreferencedFileRemovalSettings `json:"icebergUnreferencedFileRemoval,omitempty"`
|
||||
}
|
||||
|
||||
type s3TableCompactionSettings struct {
|
||||
Strategy string `json:"strategy,omitempty"`
|
||||
TargetFileSizeMB *int64 `json:"targetFileSizeMB,omitempty"`
|
||||
}
|
||||
|
||||
type s3TableSnapshotManagementSettings struct {
|
||||
MinSnapshotsToKeep *int64 `json:"minSnapshotsToKeep,omitempty"`
|
||||
MaxSnapshotAgeHours *int64 `json:"maxSnapshotAgeHours,omitempty"`
|
||||
}
|
||||
|
||||
type s3TableUnreferencedFileRemovalSettings struct {
|
||||
UnreferencedDays *int64 `json:"unreferencedDays,omitempty"`
|
||||
NonCurrentDays *int64 `json:"nonCurrentDays,omitempty"`
|
||||
}
|
||||
|
||||
type s3TableMaintenanceValue struct {
|
||||
Status string `json:"status"`
|
||||
Settings *s3TableMaintenanceSettings `json:"settings,omitempty"`
|
||||
}
|
||||
|
||||
type s3TableMaintenanceResponse struct {
|
||||
Configuration map[string]*s3TableMaintenanceValue `json:"configuration"`
|
||||
}
|
||||
|
||||
func (c *iamClient) PutS3TableBucketMaintenanceConfiguration(ctx context.Context, arn string, value s3TableMaintenanceValue) error {
|
||||
request := struct {
|
||||
Value s3TableMaintenanceValue `json:"value"`
|
||||
}{Value: value}
|
||||
path := "/buckets/" + arn + "/maintenance/" + s3TableMaintenanceUnreferencedFiles
|
||||
if err := c.S3TablesRequest(ctx, http.MethodPut, path, nil, request, nil); err != nil {
|
||||
return fmt.Errorf("put S3 table bucket maintenance configuration: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *iamClient) GetS3TableBucketMaintenanceConfiguration(ctx context.Context, arn string) (map[string]*s3TableMaintenanceValue, error) {
|
||||
var response s3TableMaintenanceResponse
|
||||
path := "/buckets/" + arn + "/maintenance"
|
||||
if err := c.S3TablesRequest(ctx, http.MethodGet, path, nil, nil, &response); err != nil {
|
||||
return nil, fmt.Errorf("get S3 table bucket maintenance configuration: %w", err)
|
||||
}
|
||||
return response.Configuration, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) PutS3TableMaintenanceConfiguration(ctx context.Context, arn, namespace, name, maintenanceType string, value s3TableMaintenanceValue) error {
|
||||
request := struct {
|
||||
Value s3TableMaintenanceValue `json:"value"`
|
||||
}{Value: value}
|
||||
path := "/tables/" + arn + "/" + url.PathEscape(namespace) + "/" + url.PathEscape(name) + "/maintenance/" + url.PathEscape(maintenanceType)
|
||||
if err := c.S3TablesRequest(ctx, http.MethodPut, path, nil, request, nil); err != nil {
|
||||
return fmt.Errorf("put S3 table maintenance configuration: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *iamClient) GetS3TableMaintenanceConfiguration(ctx context.Context, arn, namespace, name string) (map[string]*s3TableMaintenanceValue, error) {
|
||||
var response s3TableMaintenanceResponse
|
||||
path := "/tables/" + arn + "/" + url.PathEscape(namespace) + "/" + url.PathEscape(name) + "/maintenance"
|
||||
if err := c.S3TablesRequest(ctx, http.MethodGet, path, nil, nil, &response); err != nil {
|
||||
return nil, fmt.Errorf("get S3 table maintenance configuration: %w", err)
|
||||
}
|
||||
return response.Configuration, nil
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type s3TableBucket struct {
|
||||
ARN string `json:"arn"`
|
||||
Name string `json:"name"`
|
||||
OwnerAccountID string `json:"ownerAccountId"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
Format string `json:"format"`
|
||||
Tags map[string]string
|
||||
}
|
||||
|
||||
type s3TableNamespace struct {
|
||||
Namespace []string `json:"namespace"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
OwnerAccountID string `json:"ownerAccountId"`
|
||||
Properties map[string]string `json:"properties"`
|
||||
}
|
||||
|
||||
type s3Table struct {
|
||||
Name string `json:"name"`
|
||||
TableARN string `json:"tableARN"`
|
||||
Namespace []string `json:"namespace"`
|
||||
Format string `json:"format"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
ModifiedAt time.Time `json:"modifiedAt"`
|
||||
OwnerAccountID string `json:"ownerAccountId"`
|
||||
MetadataLocation string `json:"metadataLocation"`
|
||||
VersionToken string `json:"versionToken"`
|
||||
Metadata json.RawMessage `json:"metadata"`
|
||||
Tags map[string]string
|
||||
}
|
||||
|
||||
func (c *iamClient) S3TablesRequest(ctx context.Context, method, requestPath string, query url.Values, body, out any) error {
|
||||
bodyString := ""
|
||||
contentType := ""
|
||||
if body != nil {
|
||||
encoded, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode S3 Tables request: %w", err)
|
||||
}
|
||||
bodyString = string(encoded)
|
||||
contentType = "application/json"
|
||||
}
|
||||
requestURL := c.endpoint + requestPath
|
||||
if len(query) > 0 {
|
||||
requestURL += "?" + query.Encode()
|
||||
}
|
||||
response, err := c.doSignedRequest(ctx, "s3tables", method, requestURL, contentType, bodyString, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if out != nil && len(response) > 0 {
|
||||
if err := json.Unmarshal(response, out); err != nil {
|
||||
return fmt.Errorf("decode S3 Tables response: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *iamClient) CreateS3TableBucket(ctx context.Context, name, format string, tags map[string]string) (string, error) {
|
||||
request := struct {
|
||||
Name string `json:"name"`
|
||||
Format string `json:"format,omitempty"`
|
||||
Tags map[string]string `json:"tags,omitempty"`
|
||||
}{Name: name, Format: format, Tags: tags}
|
||||
var response struct {
|
||||
ARN string `json:"arn"`
|
||||
}
|
||||
err := c.S3TablesRequest(ctx, http.MethodPut, "/buckets", nil, request, &response)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("create S3 table bucket: %w", err)
|
||||
}
|
||||
return response.ARN, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) GetS3TableBucket(ctx context.Context, arn string) (s3TableBucket, error) {
|
||||
var response s3TableBucket
|
||||
if err := c.S3TablesRequest(ctx, http.MethodGet, "/buckets/"+url.PathEscape(arn), nil, nil, &response); err != nil {
|
||||
return s3TableBucket{}, fmt.Errorf("get S3 table bucket: %w", err)
|
||||
}
|
||||
tags, err := c.GetS3TableTags(ctx, arn)
|
||||
if err != nil {
|
||||
return s3TableBucket{}, err
|
||||
}
|
||||
response.Tags = tags
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) DeleteS3TableBucket(ctx context.Context, arn string) error {
|
||||
if err := c.S3TablesRequest(ctx, http.MethodDelete, "/buckets/"+url.PathEscape(arn), nil, nil, nil); err != nil {
|
||||
return fmt.Errorf("delete S3 table bucket: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *iamClient) CreateS3TableNamespace(ctx context.Context, bucketARN, namespace string) error {
|
||||
request := struct {
|
||||
Namespace []string `json:"namespace"`
|
||||
}{Namespace: []string{namespace}}
|
||||
if err := c.S3TablesRequest(ctx, http.MethodPut, "/namespaces/"+url.PathEscape(bucketARN), nil, request, nil); err != nil {
|
||||
return fmt.Errorf("create S3 table namespace: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *iamClient) GetS3TableNamespace(ctx context.Context, bucketARN, namespace string) (s3TableNamespace, error) {
|
||||
var response s3TableNamespace
|
||||
if err := c.S3TablesRequest(ctx, http.MethodGet, "/namespaces/"+url.PathEscape(bucketARN)+"/"+url.PathEscape(namespace), nil, nil, &response); err != nil {
|
||||
return s3TableNamespace{}, fmt.Errorf("get S3 table namespace: %w", err)
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) DeleteS3TableNamespace(ctx context.Context, bucketARN, namespace string) error {
|
||||
if err := c.S3TablesRequest(ctx, http.MethodDelete, "/namespaces/"+url.PathEscape(bucketARN)+"/"+url.PathEscape(namespace), nil, nil, nil); err != nil {
|
||||
return fmt.Errorf("delete S3 table namespace: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *iamClient) CreateS3Table(ctx context.Context, bucketARN, namespace, name, format string, metadata json.RawMessage, tags map[string]string) (s3Table, error) {
|
||||
request := struct {
|
||||
Name string `json:"name"`
|
||||
Format string `json:"format"`
|
||||
Metadata json.RawMessage `json:"metadata,omitempty"`
|
||||
Tags map[string]string `json:"tags,omitempty"`
|
||||
}{Name: name, Format: format, Metadata: metadata, Tags: tags}
|
||||
var response struct {
|
||||
TableARN string `json:"tableARN"`
|
||||
VersionToken string `json:"versionToken"`
|
||||
}
|
||||
requestPath := "/tables/" + url.PathEscape(bucketARN) + "/" + url.PathEscape(namespace)
|
||||
if err := c.S3TablesRequest(ctx, http.MethodPut, requestPath, nil, request, &response); err != nil {
|
||||
return s3Table{}, fmt.Errorf("create S3 table: %w", err)
|
||||
}
|
||||
return s3Table{TableARN: response.TableARN, VersionToken: response.VersionToken}, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) GetS3Table(ctx context.Context, bucketARN, namespace, name string) (s3Table, error) {
|
||||
query := url.Values{}
|
||||
query.Set("tableBucketARN", bucketARN)
|
||||
query.Set("namespace", namespace)
|
||||
query.Set("name", name)
|
||||
var response s3Table
|
||||
if err := c.S3TablesRequest(ctx, http.MethodGet, "/get-table", query, nil, &response); err != nil {
|
||||
return s3Table{}, fmt.Errorf("get S3 table: %w", err)
|
||||
}
|
||||
tags, err := c.GetS3TableTags(ctx, response.TableARN)
|
||||
if err != nil {
|
||||
return s3Table{}, err
|
||||
}
|
||||
response.Tags = tags
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) DeleteS3Table(ctx context.Context, bucketARN, namespace, name, versionToken string) error {
|
||||
query := url.Values{}
|
||||
if versionToken != "" {
|
||||
query.Set("versionToken", versionToken)
|
||||
}
|
||||
requestPath := "/tables/" + url.PathEscape(bucketARN) + "/" + url.PathEscape(namespace) + "/" + url.PathEscape(name)
|
||||
if err := c.S3TablesRequest(ctx, http.MethodDelete, requestPath, query, nil, nil); err != nil {
|
||||
return fmt.Errorf("delete S3 table: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *iamClient) PutS3TablePolicy(ctx context.Context, bucketARN, namespace, name, policy string) error {
|
||||
request := struct {
|
||||
ResourcePolicy string `json:"resourcePolicy"`
|
||||
}{ResourcePolicy: policy}
|
||||
if namespace == "" {
|
||||
if err := c.S3TablesRequest(ctx, http.MethodPut, "/buckets/"+url.PathEscape(bucketARN)+"/policy", nil, request, nil); err != nil {
|
||||
return fmt.Errorf("put S3 table bucket policy: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
requestPath := "/tables/" + url.PathEscape(bucketARN) + "/" + url.PathEscape(namespace) + "/" + url.PathEscape(name) + "/policy"
|
||||
if err := c.S3TablesRequest(ctx, http.MethodPut, requestPath, nil, request, nil); err != nil {
|
||||
return fmt.Errorf("put S3 table policy: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *iamClient) GetS3TablePolicy(ctx context.Context, bucketARN, namespace, name string) (string, error) {
|
||||
requestPath := "/buckets/" + url.PathEscape(bucketARN) + "/policy"
|
||||
if namespace != "" {
|
||||
requestPath = "/tables/" + url.PathEscape(bucketARN) + "/" + url.PathEscape(namespace) + "/" + url.PathEscape(name) + "/policy"
|
||||
}
|
||||
var response struct {
|
||||
ResourcePolicy string `json:"resourcePolicy"`
|
||||
}
|
||||
if err := c.S3TablesRequest(ctx, http.MethodGet, requestPath, nil, nil, &response); err != nil {
|
||||
return "", fmt.Errorf("get S3 table policy: %w", err)
|
||||
}
|
||||
return response.ResourcePolicy, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) DeleteS3TablePolicy(ctx context.Context, bucketARN, namespace, name string) error {
|
||||
requestPath := "/buckets/" + url.PathEscape(bucketARN) + "/policy"
|
||||
if namespace != "" {
|
||||
requestPath = "/tables/" + url.PathEscape(bucketARN) + "/" + url.PathEscape(namespace) + "/" + url.PathEscape(name) + "/policy"
|
||||
}
|
||||
if err := c.S3TablesRequest(ctx, http.MethodDelete, requestPath, nil, nil, nil); err != nil {
|
||||
return fmt.Errorf("delete S3 table policy: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *iamClient) GetS3TableTags(ctx context.Context, arn string) (map[string]string, error) {
|
||||
var response struct {
|
||||
Tags map[string]string `json:"tags"`
|
||||
}
|
||||
if err := c.S3TablesRequest(ctx, http.MethodGet, "/tag/"+url.PathEscape(arn), nil, nil, &response); err != nil {
|
||||
return nil, fmt.Errorf("list S3 Tables tags: %w", err)
|
||||
}
|
||||
if response.Tags == nil {
|
||||
response.Tags = map[string]string{}
|
||||
}
|
||||
return response.Tags, nil
|
||||
}
|
||||
|
||||
func (c *iamClient) TagS3TableResource(ctx context.Context, arn string, tags map[string]string) error {
|
||||
request := struct {
|
||||
ResourceARN string `json:"resourceArn"`
|
||||
Tags map[string]string `json:"tags"`
|
||||
}{ResourceARN: arn, Tags: tags}
|
||||
if err := c.S3TablesRequest(ctx, http.MethodPost, "/tag/"+url.PathEscape(arn), nil, request, nil); err != nil {
|
||||
return fmt.Errorf("tag S3 Tables resource: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *iamClient) UntagS3TableResource(ctx context.Context, arn string, keys []string) error {
|
||||
query := url.Values{}
|
||||
for _, key := range keys {
|
||||
query.Add("tagKeys", key)
|
||||
}
|
||||
if err := c.S3TablesRequest(ctx, http.MethodDelete, "/tag/"+url.PathEscape(arn), query, nil, nil); err != nil {
|
||||
return fmt.Errorf("untag S3 Tables resource: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *iamClient) SetS3TableTags(ctx context.Context, arn string, desired map[string]string) error {
|
||||
current, err := c.GetS3TableTags(ctx, arn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var remove []string
|
||||
for key := range current {
|
||||
if _, exists := desired[key]; !exists {
|
||||
remove = append(remove, key)
|
||||
}
|
||||
}
|
||||
sort.Strings(remove)
|
||||
if len(remove) > 0 {
|
||||
if err := c.UntagS3TableResource(ctx, arn, remove); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if len(desired) > 0 {
|
||||
if err := c.TagS3TableResource(ctx, arn, desired); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isNoSuchS3TablesEntityError(err error) bool {
|
||||
var apiErr iamError
|
||||
if !errors.As(err, &apiErr) {
|
||||
return false
|
||||
}
|
||||
return strings.HasPrefix(apiErr.Code, "NoSuch")
|
||||
}
|
||||
@@ -0,0 +1,505 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestIAMClientUserLifecycle(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
users := map[string]bool{}
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
t.Fatalf("unexpected method: %s", r.Method)
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read request body: %v", err)
|
||||
}
|
||||
_ = r.Body.Close()
|
||||
|
||||
form, err := url.ParseQuery(string(body))
|
||||
if err != nil {
|
||||
t.Fatalf("parse form body: %v", err)
|
||||
}
|
||||
|
||||
action := form.Get("Action")
|
||||
name := form.Get("UserName")
|
||||
|
||||
switch action {
|
||||
case "CreateUser":
|
||||
users[name] = true
|
||||
w.Header().Set("Content-Type", "application/xml")
|
||||
_, _ = w.Write([]byte(`<CreateUserResponse xmlns="https://iam.amazonaws.com/doc/2010-05-08/"><CreateUserResult><User><Path>/</Path><UserName>` + name + `</UserName><UserId>uid-123</UserId><Arn>arn:aws:iam::123456789012:user/` + name + `</Arn></User></CreateUserResult></CreateUserResponse>`))
|
||||
case "GetUser":
|
||||
if !users[name] {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = w.Write([]byte(`<ErrorResponse xmlns="https://iam.amazonaws.com/doc/2010-05-08/"><Error><Code>NoSuchEntity</Code><Message>Not found</Message></Error></ErrorResponse>`))
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/xml")
|
||||
_, _ = w.Write([]byte(`<GetUserResponse xmlns="https://iam.amazonaws.com/doc/2010-05-08/"><GetUserResult><User><Path>/</Path><UserName>` + name + `</UserName><UserId>uid-123</UserId><Arn>arn:aws:iam::123456789012:user/` + name + `</Arn></User></GetUserResult></GetUserResponse>`))
|
||||
case "DeleteUser":
|
||||
delete(users, name)
|
||||
w.Header().Set("Content-Type", "application/xml")
|
||||
_, _ = w.Write([]byte(`<DeleteUserResponse xmlns="https://iam.amazonaws.com/doc/2010-05-08/"><ResponseMetadata><RequestId>req-1</RequestId></ResponseMetadata></DeleteUserResponse>`))
|
||||
default:
|
||||
t.Fatalf("unexpected action: %s", action)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
client, err := newIAMClient(iamClientConfig{
|
||||
Endpoint: srv.URL,
|
||||
Region: "us-east-1",
|
||||
AccessKey: "test-key",
|
||||
SecretKey: "test-secret",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("new client: %v", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
userName := "test-user"
|
||||
|
||||
created, err := client.CreateUser(ctx, userName, "/")
|
||||
if err != nil {
|
||||
t.Fatalf("create user: %v", err)
|
||||
}
|
||||
if created.User.UserName != userName {
|
||||
t.Fatalf("expected created username %q, got %q", userName, created.User.UserName)
|
||||
}
|
||||
|
||||
readUser, err := client.GetUser(ctx, userName)
|
||||
if err != nil {
|
||||
t.Fatalf("get user: %v", err)
|
||||
}
|
||||
if readUser.User.UserName != userName {
|
||||
t.Fatalf("expected read username %q, got %q", userName, readUser.User.UserName)
|
||||
}
|
||||
|
||||
if err := client.DeleteUser(ctx, userName); err != nil {
|
||||
t.Fatalf("delete user: %v", err)
|
||||
}
|
||||
|
||||
_, err = client.GetUser(ctx, userName)
|
||||
if err == nil {
|
||||
t.Fatal("expected no-such-entity error after delete, got nil")
|
||||
}
|
||||
if !isNoSuchEntityError(err) {
|
||||
t.Fatalf("expected NoSuchEntity error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIAMClientCreateFromServiceFailure(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_, _ = w.Write([]byte(`<ErrorResponse xmlns="https://iam.amazonaws.com/doc/2010-05-08/"><Error><Code>ServiceFailure</Code><Message>Internal server error</Message></Error></ErrorResponse>`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
client, err := newIAMClient(iamClientConfig{
|
||||
Endpoint: srv.URL,
|
||||
Region: "us-east-1",
|
||||
AccessKey: "test-key",
|
||||
SecretKey: "test-secret",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("new client: %v", err)
|
||||
}
|
||||
|
||||
_, err = client.CreateUser(context.Background(), "x", "/")
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "ServiceFailure") {
|
||||
t.Fatalf("expected ServiceFailure in error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsNoSuchBucketError(t *testing.T) {
|
||||
for _, code := range []string{"NoSuchBucket", "NotFound", "HTTP404"} {
|
||||
t.Run(code, func(t *testing.T) {
|
||||
if !isNoSuchBucketError(iamError{Code: code}) {
|
||||
t.Fatalf("isNoSuchBucketError(%q) = false, want true", code)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if isNoSuchBucketError(iamError{Code: "AccessDenied"}) {
|
||||
t.Fatal("isNoSuchBucketError(AccessDenied) = true, want false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIAMClientAccessKeyPolicyAndBucket(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
users := map[string]bool{"alice": true}
|
||||
keys := map[string]string{}
|
||||
policies := map[string]string{}
|
||||
buckets := map[string]bool{}
|
||||
bucketTags := map[string]map[string]string{}
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, hasTagging := r.URL.Query()["tagging"]
|
||||
if hasTagging {
|
||||
bucket := strings.TrimPrefix(r.URL.Path, "/")
|
||||
if !buckets[bucket] {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = w.Write([]byte(`<Error><Code>NoSuchBucket</Code><Message>Not Found</Message></Error>`))
|
||||
return
|
||||
}
|
||||
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
tags := bucketTags[bucket]
|
||||
if len(tags) == 0 {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = w.Write([]byte(`<Error><Code>NoSuchTagSet</Code><Message>No tags</Message></Error>`))
|
||||
return
|
||||
}
|
||||
var out s3Tagging
|
||||
for key, value := range tags {
|
||||
out.TagSet = append(out.TagSet, s3Tag{
|
||||
Key: key,
|
||||
Value: value,
|
||||
})
|
||||
}
|
||||
data, err := xml.Marshal(out)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal tagging xml: %v", err)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/xml")
|
||||
_, _ = w.Write(data)
|
||||
case http.MethodPut:
|
||||
var in s3Tagging
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read tagging body: %v", err)
|
||||
}
|
||||
if err := xml.Unmarshal(body, &in); err != nil {
|
||||
t.Fatalf("unmarshal tagging body: %v", err)
|
||||
}
|
||||
tags := map[string]string{}
|
||||
for _, tag := range in.TagSet {
|
||||
tags[tag.Key] = tag.Value
|
||||
}
|
||||
bucketTags[bucket] = tags
|
||||
w.WriteHeader(http.StatusOK)
|
||||
case http.MethodDelete:
|
||||
delete(bucketTags, bucket)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
default:
|
||||
t.Fatalf("unexpected tagging method: %s", r.Method)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if r.Method == http.MethodPut || r.Method == http.MethodHead || r.Method == http.MethodDelete {
|
||||
bucket := strings.TrimPrefix(r.URL.Path, "/")
|
||||
switch r.Method {
|
||||
case http.MethodPut:
|
||||
buckets[bucket] = true
|
||||
w.WriteHeader(http.StatusOK)
|
||||
case http.MethodHead:
|
||||
if !buckets[bucket] {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = w.Write([]byte(`<Error><Code>NoSuchBucket</Code><Message>Not Found</Message></Error>`))
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
case http.MethodDelete:
|
||||
delete(buckets, bucket)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read request body: %v", err)
|
||||
}
|
||||
_ = r.Body.Close()
|
||||
|
||||
form, err := url.ParseQuery(string(body))
|
||||
if err != nil {
|
||||
t.Fatalf("parse form body: %v", err)
|
||||
}
|
||||
|
||||
action := form.Get("Action")
|
||||
user := form.Get("UserName")
|
||||
|
||||
switch action {
|
||||
case "CreateAccessKey":
|
||||
if !users[user] {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = w.Write([]byte(`<ErrorResponse><Error><Code>NoSuchEntity</Code><Message>Not found</Message></Error></ErrorResponse>`))
|
||||
return
|
||||
}
|
||||
keys[user] = "AKIA_TEST"
|
||||
_, _ = w.Write([]byte(`<CreateAccessKeyResponse><CreateAccessKeyResult><AccessKey><UserName>` + user + `</UserName><AccessKeyId>AKIA_TEST</AccessKeyId><Status>Active</Status><SecretAccessKey>SECRET123</SecretAccessKey></AccessKey></CreateAccessKeyResult></CreateAccessKeyResponse>`))
|
||||
case "ListAccessKeys":
|
||||
if keys[user] == "" {
|
||||
_, _ = w.Write([]byte(`<ListAccessKeysResponse><ListAccessKeysResult><AccessKeyMetadata></AccessKeyMetadata></ListAccessKeysResult></ListAccessKeysResponse>`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`<ListAccessKeysResponse><ListAccessKeysResult><AccessKeyMetadata><member><UserName>` + user + `</UserName><AccessKeyId>` + keys[user] + `</AccessKeyId><Status>Active</Status></member></AccessKeyMetadata></ListAccessKeysResult></ListAccessKeysResponse>`))
|
||||
case "DeleteAccessKey":
|
||||
delete(keys, user)
|
||||
_, _ = w.Write([]byte(`<DeleteAccessKeyResponse/>`))
|
||||
case "PutUserPolicy":
|
||||
policies[user+":"+form.Get("PolicyName")] = form.Get("PolicyDocument")
|
||||
_, _ = w.Write([]byte(`<PutUserPolicyResponse/>`))
|
||||
case "GetUserPolicy":
|
||||
key := user + ":" + form.Get("PolicyName")
|
||||
val, ok := policies[key]
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = w.Write([]byte(`<ErrorResponse><Error><Code>NoSuchEntity</Code><Message>Not found</Message></Error></ErrorResponse>`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`<GetUserPolicyResponse><GetUserPolicyResult><UserName>` + user + `</UserName><PolicyName>` + form.Get("PolicyName") + `</PolicyName><PolicyDocument>` + val + `</PolicyDocument></GetUserPolicyResult></GetUserPolicyResponse>`))
|
||||
case "DeleteUserPolicy":
|
||||
delete(policies, user+":"+form.Get("PolicyName"))
|
||||
_, _ = w.Write([]byte(`<DeleteUserPolicyResponse/>`))
|
||||
default:
|
||||
t.Fatalf("unexpected action: %s", action)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
client, err := newIAMClient(iamClientConfig{
|
||||
Endpoint: srv.URL,
|
||||
Region: "us-east-1",
|
||||
AccessKey: "test-key",
|
||||
SecretKey: "test-secret",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("new client: %v", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
ak, err := client.CreateAccessKey(ctx, "alice")
|
||||
if err != nil {
|
||||
t.Fatalf("create access key: %v", err)
|
||||
}
|
||||
if ak.AccessKeyID != "AKIA_TEST" || ak.SecretAccessKey != "SECRET123" {
|
||||
t.Fatalf("unexpected access key response: %+v", ak)
|
||||
}
|
||||
|
||||
list, err := client.ListAccessKeys(ctx, "alice")
|
||||
if err != nil {
|
||||
t.Fatalf("list access keys: %v", err)
|
||||
}
|
||||
if len(list) != 1 || list[0].AccessKeyID != "AKIA_TEST" {
|
||||
t.Fatalf("unexpected key list: %+v", list)
|
||||
}
|
||||
|
||||
if err := client.PutUserPolicy(ctx, "alice", "p1", "%7B%22Version%22%3A%222012-10-17%22%7D"); err != nil {
|
||||
t.Fatalf("put user policy: %v", err)
|
||||
}
|
||||
pol, err := client.GetUserPolicy(ctx, "alice", "p1")
|
||||
if err != nil {
|
||||
t.Fatalf("get user policy: %v", err)
|
||||
}
|
||||
if !strings.Contains(pol, "Version") {
|
||||
t.Fatalf("unexpected policy decode: %s", pol)
|
||||
}
|
||||
if err := client.DeleteUserPolicy(ctx, "alice", "p1"); err != nil {
|
||||
t.Fatalf("delete user policy: %v", err)
|
||||
}
|
||||
|
||||
if err := client.CreateBucket(ctx, "b1"); err != nil {
|
||||
t.Fatalf("create bucket: %v", err)
|
||||
}
|
||||
if err := client.HeadBucket(ctx, "b1"); err != nil {
|
||||
t.Fatalf("head bucket: %v", err)
|
||||
}
|
||||
|
||||
tags, err := client.GetBucketTags(ctx, "b1")
|
||||
if err != nil {
|
||||
t.Fatalf("get empty bucket tags: %v", err)
|
||||
}
|
||||
if len(tags) != 0 {
|
||||
t.Fatalf("expected no tags, got: %+v", tags)
|
||||
}
|
||||
|
||||
if err := client.PutBucketTags(ctx, "b1", map[string]string{
|
||||
"env": "prod",
|
||||
"team": "platform",
|
||||
}); err != nil {
|
||||
t.Fatalf("put bucket tags: %v", err)
|
||||
}
|
||||
tags, err = client.GetBucketTags(ctx, "b1")
|
||||
if err != nil {
|
||||
t.Fatalf("get bucket tags: %v", err)
|
||||
}
|
||||
if tags["env"] != "prod" || tags["team"] != "platform" {
|
||||
t.Fatalf("unexpected tags: %+v", tags)
|
||||
}
|
||||
|
||||
if err := client.DeleteBucketTags(ctx, "b1"); err != nil {
|
||||
t.Fatalf("delete bucket tags: %v", err)
|
||||
}
|
||||
tags, err = client.GetBucketTags(ctx, "b1")
|
||||
if err != nil {
|
||||
t.Fatalf("get empty bucket tags after delete: %v", err)
|
||||
}
|
||||
if len(tags) != 0 {
|
||||
t.Fatalf("expected no tags after delete, got: %+v", tags)
|
||||
}
|
||||
|
||||
if err := client.DeleteBucket(ctx, "b1"); err != nil {
|
||||
t.Fatalf("delete bucket: %v", err)
|
||||
}
|
||||
|
||||
if err := client.DeleteAccessKey(ctx, "alice", "AKIA_TEST"); err != nil {
|
||||
t.Fatalf("delete access key: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoliciesSemanticallyEqual(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
a := `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:*"],"Resource":"*"}]}`
|
||||
b := `{
|
||||
"Statement": [
|
||||
{
|
||||
"Resource": "*",
|
||||
"Action": [
|
||||
"s3:*"
|
||||
],
|
||||
"Effect": "Allow"
|
||||
}
|
||||
],
|
||||
"Version": "2012-10-17"
|
||||
}`
|
||||
|
||||
if !policiesSemanticallyEqual(a, b) {
|
||||
t.Fatalf("expected policies to be semantically equal")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoliciesNormalizeSingletonStatementValues(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
configured := `{"Statement":[{"Action":"sts:AssumeRole","Effect":"Allow","Principal":{"AWS":"*"},"Resource":"*"}],"Version":"2012-10-17"}`
|
||||
seaweedFS := `{"Statement":[{"Action":["sts:AssumeRole"],"Effect":"Allow","Principal":{"AWS":"*"},"Resource":["*"]}],"Version":"2012-10-17"}`
|
||||
if !policiesSemanticallyEqual(configured, seaweedFS) {
|
||||
t.Fatal("expected equivalent policy documents to compare equal")
|
||||
}
|
||||
|
||||
trustPolicy := `{"Statement":[{"Action":"sts:AssumeRole","Effect":"Allow","Principal":{"AWS":"*"}}],"Version":"2012-10-17"}`
|
||||
seaweedFSTrustPolicy := `{"Statement":[{"Action":["sts:AssumeRole"],"Effect":"Allow","Principal":{"AWS":"*"},"Resource":[""]}],"Version":"2012-10-17"}`
|
||||
if !policiesSemanticallyEqual(trustPolicy, seaweedFSTrustPolicy) {
|
||||
t.Fatal("expected empty server-generated trust-policy resource to be ignored")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignedS3RequestIncludesPayloadHash(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||
if got := req.Header.Get("X-Amz-Content-Sha256"); got == "" {
|
||||
t.Error("expected X-Amz-Content-Sha256 header")
|
||||
}
|
||||
if !strings.Contains(req.Header.Get("Authorization"), "x-amz-content-sha256") {
|
||||
t.Error("expected payload hash header to be signed")
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client, err := newIAMClient(iamClientConfig{
|
||||
Endpoint: server.URL,
|
||||
Region: "us-east-1",
|
||||
AccessKey: "test-key",
|
||||
SecretKey: "test-secret",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("new client: %v", err)
|
||||
}
|
||||
if _, err := client.doSignedRequest(context.Background(), "s3", http.MethodPut,
|
||||
server.URL+"/bucket?seaweedfs-quota=", "application/json", `{"quota_size":1}`, nil); err != nil {
|
||||
t.Fatalf("signed S3 request: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryIAMEventuallyConsistent(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
attempts := 0
|
||||
err := retryIAMEventuallyConsistent(context.Background(), 4, func() error {
|
||||
attempts++
|
||||
if attempts < 3 {
|
||||
return iamError{Code: "ServiceFailure", Message: "temporary"}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("expected success after retries, got: %v", err)
|
||||
}
|
||||
if attempts != 3 {
|
||||
t.Fatalf("expected 3 attempts, got %d", attempts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryIAMEventuallyConsistentStopsOnNonRetryableError(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
nonRetryable := errors.New("boom")
|
||||
attempts := 0
|
||||
err := retryIAMEventuallyConsistent(context.Background(), 5, func() error {
|
||||
attempts++
|
||||
return nonRetryable
|
||||
})
|
||||
if !errors.Is(err, nonRetryable) {
|
||||
t.Fatalf("expected non-retryable error, got: %v", err)
|
||||
}
|
||||
if attempts != 1 {
|
||||
t.Fatalf("expected 1 attempt, got %d", attempts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryIAMReadDoesNotRetryNoSuchEntity(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
attempts := 0
|
||||
err := retryIAMRead(context.Background(), 5, func() error {
|
||||
attempts++
|
||||
return iamError{Code: "NoSuchEntity", Message: "missing"}
|
||||
})
|
||||
if !isNoSuchEntityError(err) {
|
||||
t.Fatalf("expected NoSuchEntity, got: %v", err)
|
||||
}
|
||||
if attempts != 1 {
|
||||
t.Fatalf("expected 1 attempt, got %d", attempts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIAMErrorHelpers(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
if !isEntityAlreadyExistsError(iamError{Code: "EntityAlreadyExists", Message: "exists"}) {
|
||||
t.Fatalf("expected EntityAlreadyExists helper to match")
|
||||
}
|
||||
if !isBucketAlreadyExistsError(iamError{Code: "BucketAlreadyOwnedByYou", Message: "exists"}) {
|
||||
t.Fatalf("expected BucketAlreadyOwnedByYou helper to match")
|
||||
}
|
||||
if !isRetryableIAMError(iamError{Code: "ServiceFailure", Message: "temporary"}) {
|
||||
t.Fatalf("expected ServiceFailure to be retryable")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestS3TablesRequestUsesS3TablesSigningScope(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||
if req.Method != http.MethodPut || req.URL.Path != "/buckets" {
|
||||
t.Errorf("request = %s %s, want PUT /buckets", req.Method, req.URL.Path)
|
||||
}
|
||||
if !strings.Contains(req.Header.Get("Authorization"), "/s3tables/aws4_request") {
|
||||
t.Errorf("Authorization scope = %q, want s3tables service", req.Header.Get("Authorization"))
|
||||
}
|
||||
body, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
t.Errorf("read request body: %v", err)
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
Name string `json:"name"`
|
||||
Format string `json:"format"`
|
||||
Tags map[string]string `json:"tags"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &request); err != nil {
|
||||
t.Errorf("decode request body: %v", err)
|
||||
return
|
||||
}
|
||||
if request.Name != "lake" || request.Format != "ICEBERG" || request.Tags["env"] != "test" {
|
||||
t.Errorf("request body = %#v", request)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"arn":"arn:aws:s3tables:us-east-1:123456789012:bucket/lake"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client, err := newIAMClient(iamClientConfig{
|
||||
Endpoint: server.URL,
|
||||
Region: "us-east-1",
|
||||
AccessKey: "test-key",
|
||||
SecretKey: "test-secret",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("new client: %v", err)
|
||||
}
|
||||
arn, err := client.CreateS3TableBucket(context.Background(), "lake", "ICEBERG", map[string]string{"env": "test"})
|
||||
if err != nil {
|
||||
t.Fatalf("create table bucket: %v", err)
|
||||
}
|
||||
if arn != "arn:aws:s3tables:us-east-1:123456789012:bucket/lake" {
|
||||
t.Fatalf("ARN = %q", arn)
|
||||
}
|
||||
}
|
||||
|
||||
func TestS3TablesJSONNotFoundErrorsAreRecognized(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
err := parseAPIError(http.StatusNotFound, []byte(`{"__type":"com.amazonaws.s3tables#NoSuchTable","message":"not found"}`))
|
||||
if !isNoSuchS3TablesEntityError(err) {
|
||||
t.Fatalf("expected S3 Tables not-found error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIAMGroupAndRoleClientResponses(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
trustPolicy := `{"Version":"2012-10-17","Statement":[]}`
|
||||
encodedTrustPolicy := url.QueryEscape(trustPolicy)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||
body, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
t.Errorf("read request body: %v", err)
|
||||
return
|
||||
}
|
||||
values, err := url.ParseQuery(string(body))
|
||||
if err != nil {
|
||||
t.Errorf("parse IAM request: %v", err)
|
||||
return
|
||||
}
|
||||
switch values.Get("Action") {
|
||||
case "GetGroup":
|
||||
_, _ = fmt.Fprint(w, `<GetGroupResponse><GetGroupResult><Group><GroupName>operators</GroupName></Group><Users><member><UserName>alice</UserName></member><member><UserName>bob</UserName></member></Users></GetGroupResult></GetGroupResponse>`)
|
||||
case "GetRole":
|
||||
_, _ = fmt.Fprintf(w, `<GetRoleResponse><GetRoleResult><Role><RoleName>reader</RoleName><Arn>arn:aws:iam:::role/reader</Arn><AssumeRolePolicyDocument>%s</AssumeRolePolicyDocument><MaxSessionDuration>3600</MaxSessionDuration></Role></GetRoleResult></GetRoleResponse>`, encodedTrustPolicy)
|
||||
default:
|
||||
t.Errorf("unexpected IAM action %q", values.Get("Action"))
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client, err := newIAMClient(iamClientConfig{
|
||||
Endpoint: server.URL,
|
||||
Region: "us-east-1",
|
||||
AccessKey: "test-key",
|
||||
SecretKey: "test-secret",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("new client: %v", err)
|
||||
}
|
||||
group, err := client.GetGroup(context.Background(), "operators")
|
||||
if err != nil {
|
||||
t.Fatalf("get group: %v", err)
|
||||
}
|
||||
if group.Name != "operators" || len(group.Users) != 2 || group.Users[1].Name != "bob" {
|
||||
t.Fatalf("group response = %#v", group)
|
||||
}
|
||||
role, err := client.GetRole(context.Background(), "reader")
|
||||
if err != nil {
|
||||
t.Fatalf("get role: %v", err)
|
||||
}
|
||||
if role.Name != "reader" || role.AssumeRolePolicy != trustPolicy || role.MaxSessionDuration != 3600 {
|
||||
t.Fatalf("role response = %#v", role)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIAMImportIDParsers(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
if name, err := parseIAMImportID("reader-role"); err != nil || name != "reader-role" {
|
||||
t.Fatalf("parse IAM ID = %q, %v", name, err)
|
||||
}
|
||||
if _, err := iamPolicyNameFromARN("arn:aws:iam:::policy/"); err == nil {
|
||||
t.Fatal("expected invalid empty policy name error")
|
||||
}
|
||||
if name, err := iamPolicyNameFromARN("arn:aws:iam:::policy/ReadOnly"); err != nil || name != "ReadOnly" {
|
||||
t.Fatalf("parse policy ARN = %q, %v", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpirationToUnix(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
unix, err := expirationToUnix("2030-01-02T03:04:05Z")
|
||||
if err != nil {
|
||||
t.Fatalf("expirationToUnix() error = %v", err)
|
||||
}
|
||||
if unix != "1893553445" {
|
||||
t.Fatalf("expiration = %s, want 1893553445", unix)
|
||||
}
|
||||
if _, err := expirationToUnix("not-a-time"); err == nil {
|
||||
t.Fatal("expected malformed expiration error")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func normalizeJSONString(raw string) (string, error) {
|
||||
var value any
|
||||
if err := json.Unmarshal([]byte(raw), &value); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
normalized, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return string(normalized), nil
|
||||
}
|
||||
|
||||
func policiesSemanticallyEqual(a string, b string) bool {
|
||||
na, errA := normalizePolicyDocument(a)
|
||||
nb, errB := normalizePolicyDocument(b)
|
||||
if errA == nil && errB == nil {
|
||||
return na == nb
|
||||
}
|
||||
|
||||
return strings.TrimSpace(a) == strings.TrimSpace(b)
|
||||
}
|
||||
|
||||
func normalizePolicyDocument(raw string) (string, error) {
|
||||
var value any
|
||||
if err := json.Unmarshal([]byte(raw), &value); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
value = omitNullJSONValues(value)
|
||||
document, ok := value.(map[string]any)
|
||||
if !ok {
|
||||
return "", errors.New("policy document must be a JSON object")
|
||||
}
|
||||
statements, ok := document["Statement"].([]any)
|
||||
if !ok {
|
||||
if statement, isObject := document["Statement"].(map[string]any); isObject {
|
||||
statements = []any{statement}
|
||||
}
|
||||
}
|
||||
for _, rawStatement := range statements {
|
||||
statement, ok := rawStatement.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
for _, key := range []string{"Action", "NotAction", "Resource", "NotResource"} {
|
||||
if item, ok := statement[key].(string); ok {
|
||||
if key == "Resource" && item == "" {
|
||||
delete(statement, key)
|
||||
continue
|
||||
}
|
||||
statement[key] = []any{item}
|
||||
}
|
||||
if key == "Resource" {
|
||||
if items, ok := statement[key].([]any); ok && len(items) == 1 && items[0] == "" {
|
||||
delete(statement, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
normalized, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(normalized), nil
|
||||
}
|
||||
|
||||
func omitNullJSONValues(value any) any {
|
||||
switch typed := value.(type) {
|
||||
case map[string]any:
|
||||
for key, child := range typed {
|
||||
if child == nil {
|
||||
delete(typed, key)
|
||||
continue
|
||||
}
|
||||
typed[key] = omitNullJSONValues(child)
|
||||
}
|
||||
case []any:
|
||||
for i, child := range typed {
|
||||
typed[i] = omitNullJSONValues(child)
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/provider"
|
||||
"github.com/hashicorp/terraform-plugin-framework/provider/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
)
|
||||
|
||||
var _ provider.Provider = &seaweedfsProvider{}
|
||||
|
||||
func NewProvider() provider.Provider {
|
||||
return &seaweedfsProvider{}
|
||||
}
|
||||
|
||||
type seaweedfsProvider struct{}
|
||||
|
||||
type seaweedfsProviderModel struct {
|
||||
Endpoint types.String `tfsdk:"endpoint"`
|
||||
Region types.String `tfsdk:"region"`
|
||||
AccessKey types.String `tfsdk:"access_key"`
|
||||
SecretKey types.String `tfsdk:"secret_key"`
|
||||
Insecure types.Bool `tfsdk:"insecure"`
|
||||
}
|
||||
|
||||
type providerData struct {
|
||||
client *iamClient
|
||||
lockMu sync.Mutex
|
||||
userLocks map[string]*sync.Mutex
|
||||
iamLocks map[string]*sync.Mutex
|
||||
bucketLocks map[string]*sync.Mutex
|
||||
}
|
||||
|
||||
func (d *providerData) withUserLock(userName string, fn func() error) error {
|
||||
lock := d.getUserLock(userName)
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
return fn()
|
||||
}
|
||||
|
||||
func (d *providerData) getUserLock(userName string) *sync.Mutex {
|
||||
d.lockMu.Lock()
|
||||
defer d.lockMu.Unlock()
|
||||
|
||||
if d.userLocks == nil {
|
||||
d.userLocks = map[string]*sync.Mutex{}
|
||||
}
|
||||
|
||||
if lock, ok := d.userLocks[userName]; ok {
|
||||
return lock
|
||||
}
|
||||
|
||||
lock := &sync.Mutex{}
|
||||
d.userLocks[userName] = lock
|
||||
return lock
|
||||
}
|
||||
|
||||
func (d *providerData) getBucketLock(bucket string) *sync.Mutex {
|
||||
d.lockMu.Lock()
|
||||
defer d.lockMu.Unlock()
|
||||
|
||||
if d.bucketLocks == nil {
|
||||
d.bucketLocks = map[string]*sync.Mutex{}
|
||||
}
|
||||
|
||||
if lock, ok := d.bucketLocks[bucket]; ok {
|
||||
return lock
|
||||
}
|
||||
|
||||
lock := &sync.Mutex{}
|
||||
d.bucketLocks[bucket] = lock
|
||||
return lock
|
||||
}
|
||||
|
||||
func (d *providerData) getIAMPrincipalLock(kind, name string) *sync.Mutex {
|
||||
key := kind + "/" + name
|
||||
d.lockMu.Lock()
|
||||
defer d.lockMu.Unlock()
|
||||
|
||||
if d.iamLocks == nil {
|
||||
d.iamLocks = map[string]*sync.Mutex{}
|
||||
}
|
||||
|
||||
if lock, ok := d.iamLocks[key]; ok {
|
||||
return lock
|
||||
}
|
||||
|
||||
lock := &sync.Mutex{}
|
||||
d.iamLocks[key] = lock
|
||||
return lock
|
||||
}
|
||||
|
||||
func (p *seaweedfsProvider) Metadata(_ context.Context, _ provider.MetadataRequest, resp *provider.MetadataResponse) {
|
||||
resp.TypeName = "seaweedfs"
|
||||
}
|
||||
|
||||
func (p *seaweedfsProvider) Schema(_ context.Context, _ provider.SchemaRequest, resp *provider.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"endpoint": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Description: "SeaweedFS S3/IAM endpoint. Falls back to SEAWEEDFS_ENDPOINT.",
|
||||
},
|
||||
"region": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Description: "Signing region. Falls back to SEAWEEDFS_REGION. Default: us-east-1.",
|
||||
},
|
||||
"access_key": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Sensitive: true,
|
||||
Description: "Admin access key. Falls back to SEAWEEDFS_ACCESS_KEY.",
|
||||
},
|
||||
"secret_key": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Sensitive: true,
|
||||
Description: "Admin secret key. Falls back to SEAWEEDFS_SECRET_KEY.",
|
||||
},
|
||||
"insecure": schema.BoolAttribute{
|
||||
Optional: true,
|
||||
Description: "Skip TLS verification. Falls back to SEAWEEDFS_INSECURE.",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (p *seaweedfsProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) {
|
||||
var config seaweedfsProviderModel
|
||||
|
||||
resp.Diagnostics.Append(req.Config.Get(ctx, &config)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
region := stringConfigValue(config.Region, "SEAWEEDFS_REGION", os.Getenv)
|
||||
if region == "" {
|
||||
region = "us-east-1"
|
||||
}
|
||||
|
||||
insecure, err := boolConfigValue(config.Insecure, "SEAWEEDFS_INSECURE", os.Getenv)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError(
|
||||
"Invalid SeaweedFS provider configuration",
|
||||
fmt.Sprintf("SEAWEEDFS_INSECURE must be a boolean: %s", err),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
endpoint := stringConfigValue(config.Endpoint, "SEAWEEDFS_ENDPOINT", os.Getenv)
|
||||
accessKey := stringConfigValue(config.AccessKey, "SEAWEEDFS_ACCESS_KEY", os.Getenv)
|
||||
secretKey := stringConfigValue(config.SecretKey, "SEAWEEDFS_SECRET_KEY", os.Getenv)
|
||||
|
||||
client, err := newIAMClient(iamClientConfig{
|
||||
Endpoint: endpoint,
|
||||
Region: region,
|
||||
AccessKey: accessKey,
|
||||
SecretKey: secretKey,
|
||||
Insecure: insecure,
|
||||
})
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError(
|
||||
"Unable to configure SeaweedFS IAM client",
|
||||
fmt.Sprintf("Failed to build client: %s", err),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
data := &providerData{
|
||||
client: client,
|
||||
userLocks: map[string]*sync.Mutex{},
|
||||
iamLocks: map[string]*sync.Mutex{},
|
||||
bucketLocks: map[string]*sync.Mutex{},
|
||||
}
|
||||
resp.ResourceData = data
|
||||
resp.DataSourceData = data
|
||||
}
|
||||
|
||||
func stringConfigValue(value types.String, envName string, getenv func(string) string) string {
|
||||
if !value.IsNull() && !value.IsUnknown() && value.ValueString() != "" {
|
||||
return value.ValueString()
|
||||
}
|
||||
return getenv(envName)
|
||||
}
|
||||
|
||||
func boolConfigValue(value types.Bool, envName string, getenv func(string) string) (bool, error) {
|
||||
if !value.IsNull() && !value.IsUnknown() {
|
||||
return value.ValueBool(), nil
|
||||
}
|
||||
|
||||
raw := getenv(envName)
|
||||
if raw == "" {
|
||||
return false, nil
|
||||
}
|
||||
return strconv.ParseBool(raw)
|
||||
}
|
||||
|
||||
func (p *seaweedfsProvider) Resources(_ context.Context) []func() resource.Resource {
|
||||
return []func() resource.Resource{
|
||||
NewBucketResource,
|
||||
NewBucketCORSConfigurationResource,
|
||||
NewBucketLifecycleConfigurationResource,
|
||||
NewBucketVersioningResource,
|
||||
NewBucketPolicyResource,
|
||||
NewBucketEncryptionResource,
|
||||
NewBucketPublicAccessBlockResource,
|
||||
NewBucketOwnershipControlsResource,
|
||||
NewBucketRequestPaymentResource,
|
||||
NewBucketQuotaResource,
|
||||
NewS3TableBucketResource,
|
||||
NewS3TableBucketPolicyResource,
|
||||
NewS3TableBucketMaintenanceConfigurationResource,
|
||||
NewS3TableNamespaceResource,
|
||||
NewS3TableResource,
|
||||
NewS3TablePolicyResource,
|
||||
NewS3TableMaintenanceConfigurationResource,
|
||||
NewIAMUserResource,
|
||||
NewIAMGroupResource,
|
||||
NewIAMGroupMembershipResource,
|
||||
NewIAMGroupPolicyResource,
|
||||
NewIAMRoleResource,
|
||||
NewIAMPolicyResource,
|
||||
NewIAMOIDCProviderResource,
|
||||
NewIAMServiceAccountResource,
|
||||
NewIAMUserPolicyAttachmentResource,
|
||||
NewIAMGroupPolicyAttachmentResource,
|
||||
NewIAMRolePolicyAttachmentResource,
|
||||
NewIAMAccessKeyResource,
|
||||
NewIAMUserPolicyResource,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *seaweedfsProvider) DataSources(_ context.Context) []func() datasource.DataSource {
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
)
|
||||
|
||||
func TestStringConfigValue(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
getenv := func(key string) string {
|
||||
if key == "SEAWEEDFS_ENDPOINT" {
|
||||
return "http://localhost:8333"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
if got := stringConfigValue(types.StringNull(), "SEAWEEDFS_ENDPOINT", getenv); got != "http://localhost:8333" {
|
||||
t.Fatalf("environment fallback = %q", got)
|
||||
}
|
||||
if got := stringConfigValue(types.StringValue("https://s3.example.test"), "SEAWEEDFS_ENDPOINT", getenv); got != "https://s3.example.test" {
|
||||
t.Fatalf("explicit value = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBoolConfigValue(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
value types.Bool
|
||||
env string
|
||||
want bool
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "default false", value: types.BoolNull(), want: false},
|
||||
{name: "environment true", value: types.BoolNull(), env: "true", want: true},
|
||||
{name: "explicit false overrides environment", value: types.BoolValue(false), env: "true", want: false},
|
||||
{name: "invalid environment value", value: types.BoolNull(), env: "yes", wantErr: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
got, err := boolConfigValue(tt.value, "SEAWEEDFS_INSECURE", func(string) string {
|
||||
return tt.env
|
||||
})
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("error = %v, wantErr %v", err, tt.wantErr)
|
||||
}
|
||||
if err == nil && got != tt.want {
|
||||
t.Fatalf("value = %t, want %t", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisteredResourcesHaveSchemasAndImport(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
provider := &seaweedfsProvider{}
|
||||
constructors := provider.Resources(t.Context())
|
||||
if len(constructors) == 0 {
|
||||
t.Fatal("provider registered no resources")
|
||||
}
|
||||
for _, construct := range constructors {
|
||||
r := construct()
|
||||
if _, ok := r.(resource.ResourceWithImportState); !ok {
|
||||
t.Errorf("%T does not support import", r)
|
||||
}
|
||||
|
||||
var metadata resource.MetadataResponse
|
||||
r.Metadata(t.Context(), resource.MetadataRequest{ProviderTypeName: "seaweedfs"}, &metadata)
|
||||
if metadata.TypeName == "" {
|
||||
t.Errorf("%T returned an empty resource type name", r)
|
||||
}
|
||||
|
||||
var schemaResponse resource.SchemaResponse
|
||||
r.Schema(t.Context(), resource.SchemaRequest{}, &schemaResponse)
|
||||
if schemaResponse.Diagnostics.HasError() {
|
||||
t.Errorf("%s schema diagnostics: %v", metadata.TypeName, schemaResponse.Diagnostics)
|
||||
}
|
||||
if len(schemaResponse.Schema.Attributes) == 0 {
|
||||
t.Errorf("%s schema has no attributes", metadata.TypeName)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/diag"
|
||||
"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/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
)
|
||||
|
||||
var (
|
||||
_ resource.Resource = &bucketResource{}
|
||||
_ resource.ResourceWithConfigure = &bucketResource{}
|
||||
_ resource.ResourceWithImportState = &bucketResource{}
|
||||
)
|
||||
|
||||
func NewBucketResource() resource.Resource {
|
||||
return &bucketResource{}
|
||||
}
|
||||
|
||||
type bucketResource struct {
|
||||
client *iamClient
|
||||
data *providerData
|
||||
}
|
||||
|
||||
type bucketResourceModel struct {
|
||||
ID types.String `tfsdk:"id"`
|
||||
Bucket types.String `tfsdk:"bucket"`
|
||||
ARN types.String `tfsdk:"arn"`
|
||||
Tags types.Map `tfsdk:"tags"`
|
||||
}
|
||||
|
||||
func (r *bucketResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_bucket"
|
||||
}
|
||||
|
||||
func (r *bucketResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "Manages a SeaweedFS S3 bucket.",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"bucket": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "Bucket name.",
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"arn": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Description: "Bucket ARN.",
|
||||
},
|
||||
"tags": schema.MapAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
ElementType: types.StringType,
|
||||
Description: "Bucket tags.",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *bucketResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
data, ok := req.ProviderData.(*providerData)
|
||||
if !ok {
|
||||
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
r.client = data.client
|
||||
r.data = data
|
||||
}
|
||||
|
||||
func (r *bucketResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
var plan bucketResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getBucketLock(plan.Bucket.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.client.CreateBucket(ctx, plan.Bucket.ValueString()); err != nil {
|
||||
if !isBucketAlreadyExistsError(err) {
|
||||
resp.Diagnostics.AddError("Failed to create bucket", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if headErr := r.client.HeadBucket(ctx, plan.Bucket.ValueString()); headErr != nil {
|
||||
resp.Diagnostics.AddError("Failed to verify existing bucket", headErr.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
planTags, diags := stringMapFromTerraformMap(ctx, plan.Tags)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
if len(planTags) > 0 {
|
||||
if err := r.client.PutBucketTags(ctx, plan.Bucket.ValueString(), planTags); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to set bucket tags", err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
remoteTags, err := r.client.GetBucketTags(ctx, plan.Bucket.ValueString())
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Failed to read bucket tags", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
tagsValue, diags := terraformMapFromStringMap(ctx, remoteTags)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
state := bucketResourceModel{
|
||||
ID: types.StringValue(plan.Bucket.ValueString()),
|
||||
Bucket: types.StringValue(plan.Bucket.ValueString()),
|
||||
ARN: types.StringValue("arn:aws:s3:::" + plan.Bucket.ValueString()),
|
||||
Tags: tagsValue,
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *bucketResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
var state bucketResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getBucketLock(state.Bucket.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.client.HeadBucket(ctx, state.Bucket.ValueString()); err != nil {
|
||||
if isNoSuchBucketError(err) {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.AddError("Failed to read bucket", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
tags, err := r.client.GetBucketTags(ctx, state.Bucket.ValueString())
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Failed to read bucket tags", err.Error())
|
||||
return
|
||||
}
|
||||
tagsValue, diags := terraformMapFromStringMap(ctx, tags)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
state.ID = types.StringValue(state.Bucket.ValueString())
|
||||
state.ARN = types.StringValue("arn:aws:s3:::" + state.Bucket.ValueString())
|
||||
state.Tags = tagsValue
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *bucketResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
var plan bucketResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getBucketLock(plan.Bucket.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
tags, diags := stringMapFromTerraformMap(ctx, plan.Tags)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
if len(tags) == 0 {
|
||||
if err := r.client.DeleteBucketTags(ctx, plan.Bucket.ValueString()); err != nil && !isNoSuchBucketError(err) {
|
||||
resp.Diagnostics.AddError("Failed to delete bucket tags", err.Error())
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if err := r.client.PutBucketTags(ctx, plan.Bucket.ValueString(), tags); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to update bucket tags", err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
remoteTags, err := r.client.GetBucketTags(ctx, plan.Bucket.ValueString())
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Failed to read bucket tags", err.Error())
|
||||
return
|
||||
}
|
||||
tagsValue, diags := terraformMapFromStringMap(ctx, remoteTags)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
state := bucketResourceModel{
|
||||
ID: types.StringValue(plan.Bucket.ValueString()),
|
||||
Bucket: types.StringValue(plan.Bucket.ValueString()),
|
||||
ARN: types.StringValue("arn:aws:s3:::" + plan.Bucket.ValueString()),
|
||||
Tags: tagsValue,
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *bucketResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
var state bucketResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getBucketLock(state.Bucket.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.client.DeleteBucket(ctx, state.Bucket.ValueString()); err != nil && !isNoSuchBucketError(err) {
|
||||
resp.Diagnostics.AddError("Failed to delete bucket", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (r *bucketResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), req.ID)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("bucket"), req.ID)...)
|
||||
}
|
||||
|
||||
func stringMapFromTerraformMap(ctx context.Context, value types.Map) (map[string]string, diag.Diagnostics) {
|
||||
if value.IsNull() || value.IsUnknown() {
|
||||
return map[string]string{}, nil
|
||||
}
|
||||
|
||||
out := map[string]string{}
|
||||
diags := value.ElementsAs(ctx, &out, false)
|
||||
return out, diags
|
||||
}
|
||||
|
||||
func terraformMapFromStringMap(ctx context.Context, values map[string]string) (types.Map, diag.Diagnostics) {
|
||||
if values == nil {
|
||||
values = map[string]string{}
|
||||
}
|
||||
return types.MapValueFrom(ctx, types.StringType, values)
|
||||
}
|
||||
@@ -0,0 +1,549 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
s3types "github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
"github.com/aws/smithy-go"
|
||||
"github.com/hashicorp/terraform-plugin-framework/diag"
|
||||
"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/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
)
|
||||
|
||||
type bucketConfigurationModel struct {
|
||||
ID types.String `tfsdk:"id"`
|
||||
Bucket types.String `tfsdk:"bucket"`
|
||||
Configuration types.String `tfsdk:"configuration"`
|
||||
}
|
||||
|
||||
type bucketConfigurationOperations struct {
|
||||
suffix string
|
||||
description string
|
||||
normalize func(string) (string, error)
|
||||
get func(context.Context, *iamClient, string) (string, error)
|
||||
put func(context.Context, *iamClient, string, string) error
|
||||
delete func(context.Context, *iamClient, string) error
|
||||
}
|
||||
|
||||
type bucketConfigurationResource struct {
|
||||
client *iamClient
|
||||
data *providerData
|
||||
ops bucketConfigurationOperations
|
||||
}
|
||||
|
||||
var (
|
||||
_ resource.Resource = &bucketConfigurationResource{}
|
||||
_ resource.ResourceWithConfigure = &bucketConfigurationResource{}
|
||||
_ resource.ResourceWithImportState = &bucketConfigurationResource{}
|
||||
)
|
||||
|
||||
func NewBucketCORSConfigurationResource() resource.Resource {
|
||||
return newBucketConfigurationResource(bucketConfigurationOperations{
|
||||
suffix: "bucket_cors_configuration",
|
||||
description: "Manages a SeaweedFS S3 bucket CORS configuration. Configuration is JSON encoded.",
|
||||
normalize: normalizeBucketConfiguration[s3types.CORSConfiguration],
|
||||
get: getBucketCORSConfiguration,
|
||||
put: putBucketCORSConfiguration,
|
||||
delete: deleteBucketCORSConfiguration,
|
||||
})
|
||||
}
|
||||
|
||||
func NewBucketLifecycleConfigurationResource() resource.Resource {
|
||||
return newBucketConfigurationResource(bucketConfigurationOperations{
|
||||
suffix: "bucket_lifecycle_configuration",
|
||||
description: "Manages a SeaweedFS S3 bucket lifecycle configuration. Configuration is JSON encoded.",
|
||||
normalize: normalizeBucketConfiguration[s3types.BucketLifecycleConfiguration],
|
||||
get: getBucketLifecycleConfiguration,
|
||||
put: putBucketLifecycleConfiguration,
|
||||
delete: deleteBucketLifecycleConfiguration,
|
||||
})
|
||||
}
|
||||
|
||||
func NewBucketVersioningResource() resource.Resource {
|
||||
return newBucketConfigurationResource(bucketConfigurationOperations{
|
||||
suffix: "bucket_versioning",
|
||||
description: "Manages SeaweedFS S3 bucket versioning. Configuration is JSON encoded; destroy suspends versioning because S3 cannot unset it.",
|
||||
normalize: normalizeBucketConfiguration[s3types.VersioningConfiguration],
|
||||
get: getBucketVersioning,
|
||||
put: putBucketVersioning,
|
||||
delete: suspendBucketVersioning,
|
||||
})
|
||||
}
|
||||
|
||||
func NewBucketEncryptionResource() resource.Resource {
|
||||
return newBucketConfigurationResource(bucketConfigurationOperations{
|
||||
suffix: "bucket_encryption",
|
||||
description: "Manages a SeaweedFS S3 bucket default encryption configuration. Configuration is JSON encoded.",
|
||||
normalize: normalizeBucketEncryptionConfiguration,
|
||||
get: getBucketEncryption,
|
||||
put: putBucketEncryption,
|
||||
delete: deleteBucketEncryption,
|
||||
})
|
||||
}
|
||||
|
||||
func NewBucketPublicAccessBlockResource() resource.Resource {
|
||||
return newBucketConfigurationResource(bucketConfigurationOperations{
|
||||
suffix: "bucket_public_access_block",
|
||||
description: "Manages a SeaweedFS S3 bucket public access block configuration where supported. SeaweedFS 4.51.0 returns NotImplemented for this API.",
|
||||
normalize: normalizeBucketConfiguration[s3types.PublicAccessBlockConfiguration],
|
||||
get: getBucketPublicAccessBlock,
|
||||
put: putBucketPublicAccessBlock,
|
||||
delete: deleteBucketPublicAccessBlock,
|
||||
})
|
||||
}
|
||||
|
||||
func NewBucketOwnershipControlsResource() resource.Resource {
|
||||
return newBucketConfigurationResource(bucketConfigurationOperations{
|
||||
suffix: "bucket_ownership_controls",
|
||||
description: "Manages SeaweedFS S3 bucket ownership controls. Configuration is JSON encoded.",
|
||||
normalize: normalizeBucketConfiguration[s3types.OwnershipControls],
|
||||
get: getBucketOwnershipControls,
|
||||
put: putBucketOwnershipControls,
|
||||
delete: deleteBucketOwnershipControls,
|
||||
})
|
||||
}
|
||||
|
||||
func NewBucketRequestPaymentResource() resource.Resource {
|
||||
return newBucketConfigurationResource(bucketConfigurationOperations{
|
||||
suffix: "bucket_request_payment",
|
||||
description: "Manages a SeaweedFS S3 bucket request payment configuration. Destroy resets the payer to BucketOwner.",
|
||||
normalize: normalizeBucketConfiguration[s3types.RequestPaymentConfiguration],
|
||||
get: getBucketRequestPayment,
|
||||
put: putBucketRequestPayment,
|
||||
delete: resetBucketRequestPayment,
|
||||
})
|
||||
}
|
||||
|
||||
func newBucketConfigurationResource(ops bucketConfigurationOperations) resource.Resource {
|
||||
return &bucketConfigurationResource{ops: ops}
|
||||
}
|
||||
|
||||
func (r *bucketConfigurationResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_" + r.ops.suffix
|
||||
}
|
||||
|
||||
func (r *bucketConfigurationResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: r.ops.description,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{Computed: true},
|
||||
"bucket": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Description: "S3 bucket name.",
|
||||
},
|
||||
"configuration": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "JSON encoded configuration document.",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *bucketConfigurationResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
data, ok := req.ProviderData.(*providerData)
|
||||
if !ok {
|
||||
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
r.client = data.client
|
||||
r.data = data
|
||||
}
|
||||
|
||||
func (r *bucketConfigurationResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
var plan bucketConfigurationModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getBucketLock(plan.Bucket.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.ops.put(ctx, r.client, plan.Bucket.ValueString(), plan.Configuration.ValueString()); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to create bucket configuration", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
state := plan
|
||||
if !r.refresh(ctx, &state, &resp.Diagnostics) {
|
||||
if !resp.Diagnostics.HasError() {
|
||||
resp.Diagnostics.AddError("Bucket configuration not found after create", "SeaweedFS accepted the write but did not return the configuration on read.")
|
||||
}
|
||||
return
|
||||
}
|
||||
state.Configuration = plan.Configuration
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *bucketConfigurationResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
var state bucketConfigurationModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getBucketLock(state.Bucket.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if !r.refresh(ctx, &state, &resp.Diagnostics) {
|
||||
if !resp.Diagnostics.HasError() {
|
||||
resp.State.RemoveResource(ctx)
|
||||
}
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *bucketConfigurationResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
var plan bucketConfigurationModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getBucketLock(plan.Bucket.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.ops.put(ctx, r.client, plan.Bucket.ValueString(), plan.Configuration.ValueString()); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to update bucket configuration", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
state := plan
|
||||
if !r.refresh(ctx, &state, &resp.Diagnostics) {
|
||||
if !resp.Diagnostics.HasError() {
|
||||
resp.Diagnostics.AddError("Bucket configuration not found after update", "SeaweedFS accepted the write but did not return the configuration on read.")
|
||||
}
|
||||
return
|
||||
}
|
||||
state.Configuration = plan.Configuration
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *bucketConfigurationResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
var state bucketConfigurationModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getBucketLock(state.Bucket.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.ops.delete(ctx, r.client, state.Bucket.ValueString()); err != nil && !isMissingBucketConfiguration(err) {
|
||||
resp.Diagnostics.AddError("Failed to delete bucket configuration", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (r *bucketConfigurationResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
bucket, err := parseBucketImportID(req.ID)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid import ID", err.Error())
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), bucket)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("bucket"), bucket)...)
|
||||
}
|
||||
|
||||
func parseBucketImportID(id string) (string, error) {
|
||||
if id == "" || strings.TrimSpace(id) != id || strings.Contains(id, ",") {
|
||||
return "", errors.New("expected import ID in the format `bucket_name`")
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (r *bucketConfigurationResource) refresh(ctx context.Context, state *bucketConfigurationModel, diags *diag.Diagnostics) bool {
|
||||
raw, err := r.ops.get(ctx, r.client, state.Bucket.ValueString())
|
||||
if err != nil {
|
||||
if isMissingBucketConfiguration(err) {
|
||||
return false
|
||||
}
|
||||
diags.AddError("Failed to read bucket configuration", err.Error())
|
||||
return false
|
||||
}
|
||||
|
||||
normalized, err := normalizeBucketConfigurationForComparison(r.ops.normalize, raw)
|
||||
if err != nil {
|
||||
diags.AddError("Failed to normalize bucket configuration", err.Error())
|
||||
return false
|
||||
}
|
||||
|
||||
if state.Configuration.IsNull() || state.Configuration.IsUnknown() {
|
||||
state.Configuration = types.StringValue(normalized)
|
||||
} else {
|
||||
desired, err := normalizeBucketConfigurationForComparison(r.ops.normalize, state.Configuration.ValueString())
|
||||
if err != nil {
|
||||
diags.AddError("Failed to normalize configured bucket configuration", err.Error())
|
||||
return false
|
||||
}
|
||||
if desired != normalized {
|
||||
state.Configuration = types.StringValue(normalized)
|
||||
}
|
||||
}
|
||||
|
||||
state.ID = types.StringValue(state.Bucket.ValueString())
|
||||
return true
|
||||
}
|
||||
|
||||
func decodeBucketConfiguration(raw string, value any) error {
|
||||
decoder := json.NewDecoder(strings.NewReader(raw))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(value); err != nil {
|
||||
return fmt.Errorf("decode JSON configuration: %w", err)
|
||||
}
|
||||
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
|
||||
return errors.New("configuration must contain exactly one JSON value")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeBucketConfiguration(value any) (string, error) {
|
||||
encoded, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("encode bucket configuration: %w", err)
|
||||
}
|
||||
return string(encoded), nil
|
||||
}
|
||||
|
||||
func normalizeBucketConfiguration[T any](raw string) (string, error) {
|
||||
var configuration T
|
||||
if err := decodeBucketConfiguration(raw, &configuration); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return encodeBucketConfiguration(configuration)
|
||||
}
|
||||
|
||||
func normalizeBucketEncryptionConfiguration(raw string) (string, error) {
|
||||
var configuration s3types.ServerSideEncryptionConfiguration
|
||||
if err := decodeBucketConfiguration(raw, &configuration); err != nil {
|
||||
return "", err
|
||||
}
|
||||
for i := range configuration.Rules {
|
||||
if configuration.Rules[i].BucketKeyEnabled != nil && !*configuration.Rules[i].BucketKeyEnabled {
|
||||
configuration.Rules[i].BucketKeyEnabled = nil
|
||||
}
|
||||
}
|
||||
return encodeBucketConfiguration(configuration)
|
||||
}
|
||||
|
||||
func normalizeBucketConfigurationForComparison(normalize func(string) (string, error), raw string) (string, error) {
|
||||
typed, err := normalize(raw)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return normalizeJSONString(typed)
|
||||
}
|
||||
|
||||
func isMissingBucketConfiguration(err error) bool {
|
||||
var iamErr iamError
|
||||
if errors.As(err, &iamErr) && (iamErr.Code == "NoSuchBucket" || iamErr.Code == "HTTP404") {
|
||||
return true
|
||||
}
|
||||
|
||||
var apiErr smithy.APIError
|
||||
if !errors.As(err, &apiErr) {
|
||||
return false
|
||||
}
|
||||
switch apiErr.ErrorCode() {
|
||||
case "NoSuchBucket", "NotFound", "NoSuchBucketPolicy", "NoSuchCORSConfiguration", "NoSuchLifecycleConfiguration",
|
||||
"ServerSideEncryptionConfigurationNotFoundError", "NoSuchPublicAccessBlockConfiguration",
|
||||
"NoSuchOwnershipControls", "OwnershipControlsNotFoundError", "NoSuchConfiguration":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func putBucketCORSConfiguration(ctx context.Context, client *iamClient, bucket, raw string) error {
|
||||
var configuration s3types.CORSConfiguration
|
||||
if err := decodeBucketConfiguration(raw, &configuration); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := client.s3.PutBucketCors(ctx, &s3.PutBucketCorsInput{
|
||||
Bucket: aws.String(bucket),
|
||||
CORSConfiguration: &configuration,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func getBucketCORSConfiguration(ctx context.Context, client *iamClient, bucket string) (string, error) {
|
||||
output, err := client.s3.GetBucketCors(ctx, &s3.GetBucketCorsInput{Bucket: aws.String(bucket)})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return encodeBucketConfiguration(s3types.CORSConfiguration{CORSRules: output.CORSRules})
|
||||
}
|
||||
|
||||
func deleteBucketCORSConfiguration(ctx context.Context, client *iamClient, bucket string) error {
|
||||
_, err := client.s3.DeleteBucketCors(ctx, &s3.DeleteBucketCorsInput{Bucket: aws.String(bucket)})
|
||||
return err
|
||||
}
|
||||
|
||||
func putBucketLifecycleConfiguration(ctx context.Context, client *iamClient, bucket, raw string) error {
|
||||
var configuration s3types.BucketLifecycleConfiguration
|
||||
if err := decodeBucketConfiguration(raw, &configuration); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := client.s3.PutBucketLifecycleConfiguration(ctx, &s3.PutBucketLifecycleConfigurationInput{
|
||||
Bucket: aws.String(bucket),
|
||||
LifecycleConfiguration: &configuration,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func getBucketLifecycleConfiguration(ctx context.Context, client *iamClient, bucket string) (string, error) {
|
||||
output, err := client.s3.GetBucketLifecycleConfiguration(ctx, &s3.GetBucketLifecycleConfigurationInput{Bucket: aws.String(bucket)})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return encodeBucketConfiguration(s3types.BucketLifecycleConfiguration{Rules: output.Rules})
|
||||
}
|
||||
|
||||
func deleteBucketLifecycleConfiguration(ctx context.Context, client *iamClient, bucket string) error {
|
||||
_, err := client.s3.DeleteBucketLifecycle(ctx, &s3.DeleteBucketLifecycleInput{Bucket: aws.String(bucket)})
|
||||
return err
|
||||
}
|
||||
|
||||
func putBucketVersioning(ctx context.Context, client *iamClient, bucket, raw string) error {
|
||||
var configuration s3types.VersioningConfiguration
|
||||
if err := decodeBucketConfiguration(raw, &configuration); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := client.s3.PutBucketVersioning(ctx, &s3.PutBucketVersioningInput{
|
||||
Bucket: aws.String(bucket),
|
||||
VersioningConfiguration: &configuration,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func getBucketVersioning(ctx context.Context, client *iamClient, bucket string) (string, error) {
|
||||
output, err := client.s3.GetBucketVersioning(ctx, &s3.GetBucketVersioningInput{Bucket: aws.String(bucket)})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return encodeBucketConfiguration(s3types.VersioningConfiguration{Status: output.Status, MFADelete: s3types.MFADelete(output.MFADelete)})
|
||||
}
|
||||
|
||||
func suspendBucketVersioning(ctx context.Context, client *iamClient, bucket string) error {
|
||||
return putBucketVersioning(ctx, client, bucket, `{"Status":"Suspended"}`)
|
||||
}
|
||||
|
||||
func putBucketEncryption(ctx context.Context, client *iamClient, bucket, raw string) error {
|
||||
var configuration s3types.ServerSideEncryptionConfiguration
|
||||
if err := decodeBucketConfiguration(raw, &configuration); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := client.s3.PutBucketEncryption(ctx, &s3.PutBucketEncryptionInput{
|
||||
Bucket: aws.String(bucket),
|
||||
ServerSideEncryptionConfiguration: &configuration,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func getBucketEncryption(ctx context.Context, client *iamClient, bucket string) (string, error) {
|
||||
output, err := client.s3.GetBucketEncryption(ctx, &s3.GetBucketEncryptionInput{Bucket: aws.String(bucket)})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return encodeBucketConfiguration(output.ServerSideEncryptionConfiguration)
|
||||
}
|
||||
|
||||
func deleteBucketEncryption(ctx context.Context, client *iamClient, bucket string) error {
|
||||
_, err := client.s3.DeleteBucketEncryption(ctx, &s3.DeleteBucketEncryptionInput{Bucket: aws.String(bucket)})
|
||||
return err
|
||||
}
|
||||
|
||||
func putBucketPublicAccessBlock(ctx context.Context, client *iamClient, bucket, raw string) error {
|
||||
var configuration s3types.PublicAccessBlockConfiguration
|
||||
if err := decodeBucketConfiguration(raw, &configuration); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := client.s3.PutPublicAccessBlock(ctx, &s3.PutPublicAccessBlockInput{
|
||||
Bucket: aws.String(bucket),
|
||||
PublicAccessBlockConfiguration: &configuration,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func getBucketPublicAccessBlock(ctx context.Context, client *iamClient, bucket string) (string, error) {
|
||||
output, err := client.s3.GetPublicAccessBlock(ctx, &s3.GetPublicAccessBlockInput{Bucket: aws.String(bucket)})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return encodeBucketConfiguration(output.PublicAccessBlockConfiguration)
|
||||
}
|
||||
|
||||
func deleteBucketPublicAccessBlock(ctx context.Context, client *iamClient, bucket string) error {
|
||||
_, err := client.s3.DeletePublicAccessBlock(ctx, &s3.DeletePublicAccessBlockInput{Bucket: aws.String(bucket)})
|
||||
return err
|
||||
}
|
||||
|
||||
func putBucketOwnershipControls(ctx context.Context, client *iamClient, bucket, raw string) error {
|
||||
var configuration s3types.OwnershipControls
|
||||
if err := decodeBucketConfiguration(raw, &configuration); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := client.s3.PutBucketOwnershipControls(ctx, &s3.PutBucketOwnershipControlsInput{
|
||||
Bucket: aws.String(bucket),
|
||||
OwnershipControls: &configuration,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func getBucketOwnershipControls(ctx context.Context, client *iamClient, bucket string) (string, error) {
|
||||
output, err := client.s3.GetBucketOwnershipControls(ctx, &s3.GetBucketOwnershipControlsInput{Bucket: aws.String(bucket)})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return encodeBucketConfiguration(output.OwnershipControls)
|
||||
}
|
||||
|
||||
func deleteBucketOwnershipControls(ctx context.Context, client *iamClient, bucket string) error {
|
||||
_, err := client.s3.DeleteBucketOwnershipControls(ctx, &s3.DeleteBucketOwnershipControlsInput{Bucket: aws.String(bucket)})
|
||||
return err
|
||||
}
|
||||
|
||||
func putBucketRequestPayment(ctx context.Context, client *iamClient, bucket, raw string) error {
|
||||
var configuration s3types.RequestPaymentConfiguration
|
||||
if err := decodeBucketConfiguration(raw, &configuration); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := client.s3.PutBucketRequestPayment(ctx, &s3.PutBucketRequestPaymentInput{
|
||||
Bucket: aws.String(bucket),
|
||||
RequestPaymentConfiguration: &configuration,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func getBucketRequestPayment(ctx context.Context, client *iamClient, bucket string) (string, error) {
|
||||
output, err := client.s3.GetBucketRequestPayment(ctx, &s3.GetBucketRequestPaymentInput{Bucket: aws.String(bucket)})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return encodeBucketConfiguration(s3types.RequestPaymentConfiguration{Payer: output.Payer})
|
||||
}
|
||||
|
||||
func resetBucketRequestPayment(ctx context.Context, client *iamClient, bucket string) error {
|
||||
return putBucketRequestPayment(ctx, client, bucket, `{"Payer":"BucketOwner"}`)
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
s3types "github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
)
|
||||
|
||||
func TestDecodeBucketConfiguration(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
raw string
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "valid CORS document",
|
||||
raw: `{"CORSRules":[{"AllowedMethods":["GET"],"AllowedOrigins":["https://example.com"]}]}`,
|
||||
},
|
||||
{
|
||||
name: "malformed JSON",
|
||||
raw: `{"CORSRules":`,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "unknown field",
|
||||
raw: `{"CORSRules":[],"unexpected":true}`,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "multiple JSON values",
|
||||
raw: `{"CORSRules":[]} {}`,
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var configuration s3types.CORSConfiguration
|
||||
err := decodeBucketConfiguration(test.raw, &configuration)
|
||||
if (err != nil) != test.wantErr {
|
||||
t.Fatalf("decodeBucketConfiguration() error = %v, wantErr %v", err, test.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeBucketConfiguration(t *testing.T) {
|
||||
raw := `{"CORSRules":[{"AllowedOrigins":["https://example.com"],"AllowedMethods":["GET"]}]}`
|
||||
|
||||
got, err := normalizeBucketConfiguration[s3types.CORSConfiguration](raw)
|
||||
if err != nil {
|
||||
t.Fatalf("normalizeBucketConfiguration() error = %v", err)
|
||||
}
|
||||
|
||||
var configuration s3types.CORSConfiguration
|
||||
if err := decodeBucketConfiguration(got, &configuration); err != nil {
|
||||
t.Fatalf("normalized configuration did not decode: %v", err)
|
||||
}
|
||||
if len(configuration.CORSRules) != 1 ||
|
||||
len(configuration.CORSRules[0].AllowedMethods) != 1 ||
|
||||
configuration.CORSRules[0].AllowedMethods[0] != "GET" ||
|
||||
len(configuration.CORSRules[0].AllowedOrigins) != 1 ||
|
||||
configuration.CORSRules[0].AllowedOrigins[0] != "https://example.com" {
|
||||
t.Fatalf("normalized configuration lost values: %s", got)
|
||||
}
|
||||
|
||||
again, err := normalizeBucketConfiguration[s3types.CORSConfiguration](got)
|
||||
if err != nil {
|
||||
t.Fatalf("normalizing the canonical configuration again: %v", err)
|
||||
}
|
||||
if again != got {
|
||||
t.Fatalf("normalization is not stable: first %s, then %s", got, again)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBucketConfigurationComparisonUsesTypedValues(t *testing.T) {
|
||||
desired := `{"corsRules":[{"allowedOrigins":["https://example.com"],"allowedMethods":["GET"]}]}`
|
||||
remote := `{"CORSRules":[{"AllowedMethods":["GET"],"AllowedOrigins":["https://example.com"],"ExposeHeaders":null,"ID":null,"MaxAgeSeconds":null,"AllowedHeaders":null}]}`
|
||||
|
||||
desiredNormalized, err := normalizeBucketConfigurationForComparison(normalizeBucketConfiguration[s3types.CORSConfiguration], desired)
|
||||
if err != nil {
|
||||
t.Fatalf("normalize desired configuration: %v", err)
|
||||
}
|
||||
remoteNormalized, err := normalizeBucketConfigurationForComparison(normalizeBucketConfiguration[s3types.CORSConfiguration], remote)
|
||||
if err != nil {
|
||||
t.Fatalf("normalize remote configuration: %v", err)
|
||||
}
|
||||
if desiredNormalized != remoteNormalized {
|
||||
t.Fatalf("typed configurations differ:\nwant %s\ngot %s", desiredNormalized, remoteNormalized)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsMissingBucketConfigurationWhenBucketIsGone(t *testing.T) {
|
||||
for _, code := range []string{"NoSuchBucket", "HTTP404"} {
|
||||
if !isMissingBucketConfiguration(iamError{Code: code}) {
|
||||
t.Errorf("isMissingBucketConfiguration(%q) = false, want true", code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseBucketImportID(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
id string
|
||||
want string
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "bucket name", id: "media-bucket", want: "media-bucket"},
|
||||
{name: "empty", id: "", wantErr: true},
|
||||
{name: "whitespace", id: " media-bucket ", wantErr: true},
|
||||
{name: "composite", id: "media-bucket,extra", wantErr: true},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
got, err := parseBucketImportID(test.id)
|
||||
if (err != nil) != test.wantErr {
|
||||
t.Fatalf("parseBucketImportID() error = %v, wantErr %v", err, test.wantErr)
|
||||
}
|
||||
if got != test.want {
|
||||
t.Fatalf("parseBucketImportID() = %q, want %q", got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBucketQuotaURL(t *testing.T) {
|
||||
endpoint := "http://localhost:8333"
|
||||
parsed, err := url.Parse(bucketQuotaURL(endpoint, "media-bucket"))
|
||||
if err != nil {
|
||||
t.Fatalf("url.Parse() error = %v", err)
|
||||
}
|
||||
if parsed.Path != "/media-bucket" {
|
||||
t.Errorf("path = %q, want %q", parsed.Path, "/media-bucket")
|
||||
}
|
||||
if parsed.Query().Get("seaweedfs-quota") != "" || !parsed.Query().Has("seaweedfs-quota") {
|
||||
t.Errorf("query = %q, want seaweedfs-quota selector", parsed.RawQuery)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/smithy-go"
|
||||
"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/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
)
|
||||
|
||||
var (
|
||||
_ resource.Resource = &bucketPolicyResource{}
|
||||
_ resource.ResourceWithConfigure = &bucketPolicyResource{}
|
||||
_ resource.ResourceWithImportState = &bucketPolicyResource{}
|
||||
)
|
||||
|
||||
type bucketPolicyResource struct {
|
||||
client *iamClient
|
||||
data *providerData
|
||||
}
|
||||
|
||||
type bucketPolicyResourceModel struct {
|
||||
ID types.String `tfsdk:"id"`
|
||||
Bucket types.String `tfsdk:"bucket"`
|
||||
Policy types.String `tfsdk:"policy"`
|
||||
}
|
||||
|
||||
func NewBucketPolicyResource() resource.Resource {
|
||||
return &bucketPolicyResource{}
|
||||
}
|
||||
|
||||
func (r *bucketPolicyResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_bucket_policy"
|
||||
}
|
||||
|
||||
func (r *bucketPolicyResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "Manages the S3 bucket policy in SeaweedFS. Import using the bucket name.",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{Computed: true},
|
||||
"bucket": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Description: "S3 bucket name.",
|
||||
},
|
||||
"policy": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "JSON bucket policy document.",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *bucketPolicyResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
data, ok := req.ProviderData.(*providerData)
|
||||
if !ok {
|
||||
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
r.client = data.client
|
||||
r.data = data
|
||||
}
|
||||
|
||||
func (r *bucketPolicyResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
var plan bucketPolicyResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getBucketLock(plan.Bucket.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
normalized, err := normalizeJSONString(plan.Policy.ValueString())
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid bucket policy", err.Error())
|
||||
return
|
||||
}
|
||||
_, err = r.client.s3.PutBucketPolicy(ctx, &s3.PutBucketPolicyInput{
|
||||
Bucket: aws.String(plan.Bucket.ValueString()),
|
||||
Policy: aws.String(normalized),
|
||||
})
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Failed to create bucket policy", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
plan.ID = types.StringValue(plan.Bucket.ValueString())
|
||||
plan.Policy = types.StringValue(normalized)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *bucketPolicyResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
var state bucketPolicyResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getBucketLock(state.Bucket.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
output, err := r.client.s3.GetBucketPolicy(ctx, &s3.GetBucketPolicyInput{Bucket: aws.String(state.Bucket.ValueString())})
|
||||
if err != nil {
|
||||
if isMissingBucketPolicy(err) {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.AddError("Failed to read bucket policy", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
state.ID = types.StringValue(state.Bucket.ValueString())
|
||||
remotePolicy := aws.ToString(output.Policy)
|
||||
if !policiesSemanticallyEqual(state.Policy.ValueString(), remotePolicy) {
|
||||
state.Policy = types.StringValue(remotePolicy)
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *bucketPolicyResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
var plan bucketPolicyResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getBucketLock(plan.Bucket.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
normalized, err := normalizeJSONString(plan.Policy.ValueString())
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid bucket policy", err.Error())
|
||||
return
|
||||
}
|
||||
_, err = r.client.s3.PutBucketPolicy(ctx, &s3.PutBucketPolicyInput{
|
||||
Bucket: aws.String(plan.Bucket.ValueString()),
|
||||
Policy: aws.String(normalized),
|
||||
})
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Failed to update bucket policy", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
plan.ID = types.StringValue(plan.Bucket.ValueString())
|
||||
plan.Policy = types.StringValue(normalized)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *bucketPolicyResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
var state bucketPolicyResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getBucketLock(state.Bucket.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
_, err := r.client.s3.DeleteBucketPolicy(ctx, &s3.DeleteBucketPolicyInput{Bucket: aws.String(state.Bucket.ValueString())})
|
||||
if err != nil && !isMissingBucketPolicy(err) {
|
||||
resp.Diagnostics.AddError("Failed to delete bucket policy", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (r *bucketPolicyResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
bucket, err := parseBucketImportID(req.ID)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid import ID", err.Error())
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), bucket)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("bucket"), bucket)...)
|
||||
}
|
||||
|
||||
func isMissingBucketPolicy(err error) bool {
|
||||
var apiErr smithy.APIError
|
||||
if !errors.As(err, &apiErr) {
|
||||
return false
|
||||
}
|
||||
switch apiErr.ErrorCode() {
|
||||
case "NoSuchBucket", "NoSuchBucketPolicy":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/diag"
|
||||
"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/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
)
|
||||
|
||||
var (
|
||||
_ resource.Resource = &bucketQuotaResource{}
|
||||
_ resource.ResourceWithConfigure = &bucketQuotaResource{}
|
||||
_ resource.ResourceWithImportState = &bucketQuotaResource{}
|
||||
)
|
||||
|
||||
type bucketQuotaResource struct {
|
||||
client *iamClient
|
||||
data *providerData
|
||||
}
|
||||
|
||||
type bucketQuotaResourceModel struct {
|
||||
ID types.String `tfsdk:"id"`
|
||||
Bucket types.String `tfsdk:"bucket"`
|
||||
QuotaBytes types.Int64 `tfsdk:"quota_bytes"`
|
||||
Enabled types.Bool `tfsdk:"enabled"`
|
||||
}
|
||||
|
||||
type bucketQuotaConfiguration struct {
|
||||
QuotaSize int64 `json:"quota_size"`
|
||||
QuotaUnit string `json:"quota_unit"`
|
||||
QuotaEnabled bool `json:"quota_enabled"`
|
||||
}
|
||||
|
||||
func NewBucketQuotaResource() resource.Resource {
|
||||
return &bucketQuotaResource{}
|
||||
}
|
||||
|
||||
func (r *bucketQuotaResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_bucket_quota"
|
||||
}
|
||||
|
||||
func (r *bucketQuotaResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "Manages a SeaweedFS-specific S3 bucket storage quota. Import using the bucket name.",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{Computed: true},
|
||||
"bucket": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Description: "S3 bucket name.",
|
||||
},
|
||||
"quota_bytes": schema.Int64Attribute{
|
||||
Required: true,
|
||||
Description: "Maximum bucket size in bytes. Use zero only when the quota is disabled.",
|
||||
},
|
||||
"enabled": schema.BoolAttribute{
|
||||
Required: true,
|
||||
Description: "Whether SeaweedFS enforces the quota.",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *bucketQuotaResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
data, ok := req.ProviderData.(*providerData)
|
||||
if !ok {
|
||||
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
r.client = data.client
|
||||
r.data = data
|
||||
}
|
||||
|
||||
func (r *bucketQuotaResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
var plan bucketQuotaResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getBucketLock(plan.Bucket.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.put(ctx, plan); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to create bucket quota", err.Error())
|
||||
return
|
||||
}
|
||||
if !r.refresh(ctx, &plan, &resp.Diagnostics) {
|
||||
if !resp.Diagnostics.HasError() {
|
||||
resp.Diagnostics.AddError("Bucket quota not found after create", "SeaweedFS accepted the write but did not return the quota on read.")
|
||||
}
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *bucketQuotaResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
var state bucketQuotaResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getBucketLock(state.Bucket.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if !r.refresh(ctx, &state, &resp.Diagnostics) {
|
||||
if !resp.Diagnostics.HasError() {
|
||||
resp.State.RemoveResource(ctx)
|
||||
}
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *bucketQuotaResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
var plan bucketQuotaResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getBucketLock(plan.Bucket.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.put(ctx, plan); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to update bucket quota", err.Error())
|
||||
return
|
||||
}
|
||||
if !r.refresh(ctx, &plan, &resp.Diagnostics) {
|
||||
if !resp.Diagnostics.HasError() {
|
||||
resp.Diagnostics.AddError("Bucket quota not found after update", "SeaweedFS accepted the write but did not return the quota on read.")
|
||||
}
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *bucketQuotaResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
var state bucketQuotaResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getBucketLock(state.Bucket.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
_, err := r.client.doSignedRequest(ctx, "s3", http.MethodPut,
|
||||
bucketQuotaURL(r.client.endpoint, state.Bucket.ValueString()), "application/json",
|
||||
`{"quota_size":0,"quota_unit":"B","quota_enabled":false}`, nil)
|
||||
if err != nil && !isNoSuchBucketError(err) {
|
||||
resp.Diagnostics.AddError("Failed to delete bucket quota", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (r *bucketQuotaResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
bucket, err := parseBucketImportID(req.ID)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid import ID", err.Error())
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), bucket)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("bucket"), bucket)...)
|
||||
}
|
||||
|
||||
func (r *bucketQuotaResource) put(ctx context.Context, model bucketQuotaResourceModel) error {
|
||||
if model.QuotaBytes.ValueInt64() < 0 {
|
||||
return fmt.Errorf("quota_bytes must not be negative")
|
||||
}
|
||||
configuration, err := json.Marshal(bucketQuotaConfiguration{
|
||||
QuotaSize: model.QuotaBytes.ValueInt64(),
|
||||
QuotaUnit: "B",
|
||||
QuotaEnabled: model.Enabled.ValueBool(),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode bucket quota: %w", err)
|
||||
}
|
||||
_, err = r.client.doSignedRequest(ctx, "s3", http.MethodPut,
|
||||
bucketQuotaURL(r.client.endpoint, model.Bucket.ValueString()), "application/json",
|
||||
string(configuration), nil)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *bucketQuotaResource) refresh(ctx context.Context, state *bucketQuotaResourceModel, diags *diag.Diagnostics) bool {
|
||||
response, err := r.client.doSignedRequest(ctx, "s3", http.MethodGet,
|
||||
bucketQuotaURL(r.client.endpoint, state.Bucket.ValueString()), "", "", nil)
|
||||
if err != nil {
|
||||
if isNoSuchBucketError(err) {
|
||||
return false
|
||||
}
|
||||
diags.AddError("Failed to read bucket quota", err.Error())
|
||||
return false
|
||||
}
|
||||
|
||||
var configuration bucketQuotaConfiguration
|
||||
if err := json.Unmarshal(response, &configuration); err != nil {
|
||||
diags.AddError("Failed to decode bucket quota", err.Error())
|
||||
return false
|
||||
}
|
||||
if configuration.QuotaUnit != "B" {
|
||||
diags.AddError("Unexpected bucket quota unit", fmt.Sprintf("Expected SeaweedFS to return quota_unit B, got %q", configuration.QuotaUnit))
|
||||
return false
|
||||
}
|
||||
state.ID = types.StringValue(state.Bucket.ValueString())
|
||||
state.QuotaBytes = types.Int64Value(configuration.QuotaSize)
|
||||
state.Enabled = types.BoolValue(configuration.QuotaEnabled)
|
||||
return true
|
||||
}
|
||||
|
||||
func bucketQuotaURL(endpoint, bucket string) string {
|
||||
query := url.Values{}
|
||||
query.Set("seaweedfs-quota", "")
|
||||
return endpoint + "/" + url.PathEscape(bucket) + "?" + query.Encode()
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"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/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
)
|
||||
|
||||
var (
|
||||
_ resource.Resource = &iamAccessKeyResource{}
|
||||
_ resource.ResourceWithConfigure = &iamAccessKeyResource{}
|
||||
_ resource.ResourceWithImportState = &iamAccessKeyResource{}
|
||||
)
|
||||
|
||||
func NewIAMAccessKeyResource() resource.Resource {
|
||||
return &iamAccessKeyResource{}
|
||||
}
|
||||
|
||||
type iamAccessKeyResource struct {
|
||||
client *iamClient
|
||||
data *providerData
|
||||
}
|
||||
|
||||
type iamAccessKeyResourceModel struct {
|
||||
ID types.String `tfsdk:"id"`
|
||||
UserName types.String `tfsdk:"user_name"`
|
||||
AccessKeyID types.String `tfsdk:"access_key_id"`
|
||||
SecretAccessKey types.String `tfsdk:"secret_access_key"`
|
||||
Status types.String `tfsdk:"status"`
|
||||
}
|
||||
|
||||
func (r *iamAccessKeyResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_iam_access_key"
|
||||
}
|
||||
|
||||
func (r *iamAccessKeyResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "Manages a SeaweedFS IAM access key for a user.",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{Computed: true},
|
||||
"user_name": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"access_key_id": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"secret_access_key": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Sensitive: true,
|
||||
},
|
||||
"status": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *iamAccessKeyResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
data, ok := req.ProviderData.(*providerData)
|
||||
if !ok {
|
||||
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
r.client = data.client
|
||||
r.data = data
|
||||
}
|
||||
|
||||
func (r *iamAccessKeyResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
var plan iamAccessKeyResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
var key iamAccessKey
|
||||
err := r.data.withUserLock(plan.UserName.ValueString(), func() error {
|
||||
return retryIAMEventuallyConsistent(ctx, 20, func() error {
|
||||
var innerErr error
|
||||
key, innerErr = r.client.CreateAccessKey(ctx, plan.UserName.ValueString())
|
||||
return innerErr
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Failed to create IAM access key", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
state := iamAccessKeyResourceModel{
|
||||
ID: types.StringValue(key.AccessKeyID),
|
||||
UserName: types.StringValue(plan.UserName.ValueString()),
|
||||
AccessKeyID: types.StringValue(key.AccessKeyID),
|
||||
SecretAccessKey: types.StringValue(key.SecretAccessKey),
|
||||
Status: types.StringValue(key.Status),
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *iamAccessKeyResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
var state iamAccessKeyResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
var keys []iamAccessKeyMetadata
|
||||
err := retryIAMEventuallyConsistent(ctx, 10, func() error {
|
||||
var innerErr error
|
||||
keys, innerErr = r.client.ListAccessKeys(ctx, state.UserName.ValueString())
|
||||
return innerErr
|
||||
})
|
||||
if err != nil {
|
||||
if isNoSuchEntityError(err) {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.AddError("Failed to read IAM access key", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
found := false
|
||||
status := ""
|
||||
for _, key := range keys {
|
||||
if key.AccessKeyID == state.AccessKeyID.ValueString() {
|
||||
found = true
|
||||
status = key.Status
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
|
||||
state.ID = types.StringValue(state.AccessKeyID.ValueString())
|
||||
state.Status = types.StringValue(status)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *iamAccessKeyResource) Update(_ context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
resp.Diagnostics.AddError("Update not supported", "seaweedfs_iam_access_key supports replacement only.")
|
||||
}
|
||||
|
||||
func (r *iamAccessKeyResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
var state iamAccessKeyResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.data.withUserLock(state.UserName.ValueString(), func() error {
|
||||
return retryIAMEventuallyConsistent(ctx, 20, func() error {
|
||||
return r.client.DeleteAccessKey(ctx, state.UserName.ValueString(), state.AccessKeyID.ValueString())
|
||||
})
|
||||
}); err != nil && !isNoSuchEntityError(err) {
|
||||
resp.Diagnostics.AddError("Failed to delete IAM access key", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (r *iamAccessKeyResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
parts := strings.Split(req.ID, ",")
|
||||
if len(parts) != 2 {
|
||||
resp.Diagnostics.AddError("Invalid import ID", "Expected import id in format `user_name,access_key_id`.")
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), parts[1])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("user_name"), parts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("access_key_id"), parts[1])...)
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/diag"
|
||||
"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/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
)
|
||||
|
||||
var (
|
||||
_ resource.Resource = &iamGroupResource{}
|
||||
_ resource.ResourceWithConfigure = &iamGroupResource{}
|
||||
_ resource.ResourceWithImportState = &iamGroupResource{}
|
||||
)
|
||||
|
||||
type iamGroupResource struct {
|
||||
client *iamClient
|
||||
data *providerData
|
||||
}
|
||||
|
||||
type iamGroupResourceModel struct {
|
||||
ID types.String `tfsdk:"id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
}
|
||||
|
||||
func NewIAMGroupResource() resource.Resource {
|
||||
return &iamGroupResource{}
|
||||
}
|
||||
|
||||
func (r *iamGroupResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_iam_group"
|
||||
}
|
||||
|
||||
func (r *iamGroupResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "Manages a SeaweedFS IAM group. Group membership and attached policies are managed by separate resources. Import using the group name.",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{Computed: true},
|
||||
"name": schema.StringAttribute{Required: true, PlanModifiers: []planmodifier.String{stringplanmodifier.RequiresReplace()}},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *iamGroupResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
data, ok := req.ProviderData.(*providerData)
|
||||
if !ok {
|
||||
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
r.client = data.client
|
||||
r.data = data
|
||||
}
|
||||
|
||||
func (r *iamGroupResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
var plan iamGroupResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getIAMPrincipalLock("group", plan.Name.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.client.CreateGroup(ctx, plan.Name.ValueString()); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to create IAM group", err.Error())
|
||||
return
|
||||
}
|
||||
plan.ID = types.StringValue(plan.Name.ValueString())
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *iamGroupResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
var state iamGroupResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getIAMPrincipalLock("group", state.Name.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
group, err := r.client.GetGroup(ctx, state.Name.ValueString())
|
||||
if err != nil {
|
||||
if isNoSuchEntityError(err) {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.AddError("Failed to read IAM group", err.Error())
|
||||
return
|
||||
}
|
||||
state.ID = types.StringValue(group.Name)
|
||||
state.Name = types.StringValue(group.Name)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *iamGroupResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
var plan iamGroupResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.AddError("Unsupported IAM group update", "Group names are immutable; Terraform should replace the group.")
|
||||
}
|
||||
|
||||
func (r *iamGroupResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
var state iamGroupResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getIAMPrincipalLock("group", state.Name.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.client.DeleteGroup(ctx, state.Name.ValueString()); err != nil && !isNoSuchEntityError(err) {
|
||||
resp.Diagnostics.AddError("Failed to delete IAM group", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (r *iamGroupResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
name, err := parseIAMImportID(req.ID)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid import ID", err.Error())
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), name)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), name)...)
|
||||
}
|
||||
|
||||
var (
|
||||
_ resource.Resource = &iamGroupMembershipResource{}
|
||||
_ resource.ResourceWithConfigure = &iamGroupMembershipResource{}
|
||||
_ resource.ResourceWithImportState = &iamGroupMembershipResource{}
|
||||
)
|
||||
|
||||
type iamGroupMembershipResource struct {
|
||||
client *iamClient
|
||||
data *providerData
|
||||
}
|
||||
|
||||
type iamGroupMembershipResourceModel struct {
|
||||
ID types.String `tfsdk:"id"`
|
||||
GroupName types.String `tfsdk:"group_name"`
|
||||
Users types.Set `tfsdk:"users"`
|
||||
}
|
||||
|
||||
func NewIAMGroupMembershipResource() resource.Resource {
|
||||
return &iamGroupMembershipResource{}
|
||||
}
|
||||
|
||||
func (r *iamGroupMembershipResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_iam_group_membership"
|
||||
}
|
||||
|
||||
func (r *iamGroupMembershipResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "Manages the complete user membership set for a SeaweedFS IAM group. Import using the group name.",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{Computed: true},
|
||||
"group_name": schema.StringAttribute{Required: true, PlanModifiers: []planmodifier.String{stringplanmodifier.RequiresReplace()}},
|
||||
"users": schema.SetAttribute{
|
||||
Required: true,
|
||||
ElementType: types.StringType,
|
||||
Description: "IAM user names that belong to the group.",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *iamGroupMembershipResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
data, ok := req.ProviderData.(*providerData)
|
||||
if !ok {
|
||||
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
r.client = data.client
|
||||
r.data = data
|
||||
}
|
||||
|
||||
func (r *iamGroupMembershipResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
var plan iamGroupMembershipResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
users, diags := stringSetElements(ctx, plan.Users)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getIAMPrincipalLock("group", plan.GroupName.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.reconcile(ctx, plan.GroupName.ValueString(), users); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to create IAM group membership", err.Error())
|
||||
return
|
||||
}
|
||||
plan.ID = types.StringValue(plan.GroupName.ValueString())
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *iamGroupMembershipResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
var state iamGroupMembershipResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getIAMPrincipalLock("group", state.GroupName.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
group, err := r.client.GetGroup(ctx, state.GroupName.ValueString())
|
||||
if err != nil {
|
||||
if isNoSuchEntityError(err) {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.AddError("Failed to read IAM group membership", err.Error())
|
||||
return
|
||||
}
|
||||
users := make([]string, 0, len(group.Users))
|
||||
for _, user := range group.Users {
|
||||
users = append(users, user.Name)
|
||||
}
|
||||
sort.Strings(users)
|
||||
state.ID = types.StringValue(group.Name)
|
||||
state.GroupName = types.StringValue(group.Name)
|
||||
var diags diag.Diagnostics
|
||||
state.Users, diags = types.SetValueFrom(ctx, types.StringType, users)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *iamGroupMembershipResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
var plan iamGroupMembershipResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
users, diags := stringSetElements(ctx, plan.Users)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getIAMPrincipalLock("group", plan.GroupName.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.reconcile(ctx, plan.GroupName.ValueString(), users); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to update IAM group membership", err.Error())
|
||||
return
|
||||
}
|
||||
group, err := r.client.GetGroup(ctx, plan.GroupName.ValueString())
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Failed to read updated IAM group membership", err.Error())
|
||||
return
|
||||
}
|
||||
plan.ID = types.StringValue(group.Name)
|
||||
plan.Users, diags = groupUsersToSet(ctx, group.Users)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *iamGroupMembershipResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
var state iamGroupMembershipResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getIAMPrincipalLock("group", state.GroupName.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
group, err := r.client.GetGroup(ctx, state.GroupName.ValueString())
|
||||
if err != nil {
|
||||
if isNoSuchEntityError(err) {
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.AddError("Failed to read IAM group before removing membership", err.Error())
|
||||
return
|
||||
}
|
||||
for _, user := range group.Users {
|
||||
if err := r.client.RemoveUserFromGroup(ctx, state.GroupName.ValueString(), user.Name); err != nil && !isNoSuchEntityError(err) {
|
||||
resp.Diagnostics.AddError("Failed to remove IAM group member", err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *iamGroupMembershipResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
groupName, err := parseIAMImportID(req.ID)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid import ID", err.Error())
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), groupName)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("group_name"), groupName)...)
|
||||
}
|
||||
|
||||
func (r *iamGroupMembershipResource) reconcile(ctx context.Context, groupName string, desired []string) error {
|
||||
group, err := r.client.GetGroup(ctx, groupName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
desiredSet := make(map[string]struct{}, len(desired))
|
||||
for _, user := range desired {
|
||||
desiredSet[user] = struct{}{}
|
||||
}
|
||||
currentSet := make(map[string]struct{}, len(group.Users))
|
||||
for _, user := range group.Users {
|
||||
currentSet[user.Name] = struct{}{}
|
||||
if _, ok := desiredSet[user.Name]; !ok {
|
||||
if err := r.client.RemoveUserFromGroup(ctx, groupName, user.Name); err != nil && !isNoSuchEntityError(err) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Strings(desired)
|
||||
for _, user := range desired {
|
||||
if _, ok := currentSet[user]; ok {
|
||||
continue
|
||||
}
|
||||
if err := r.client.AddUserToGroup(ctx, groupName, user); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func stringSetElements(ctx context.Context, value types.Set) ([]string, diag.Diagnostics) {
|
||||
if value.IsNull() || value.IsUnknown() {
|
||||
return []string{}, nil
|
||||
}
|
||||
var elements []string
|
||||
diags := value.ElementsAs(ctx, &elements, false)
|
||||
return elements, diags
|
||||
}
|
||||
|
||||
func groupUsersToSet(ctx context.Context, users []iamGroupUser) (types.Set, diag.Diagnostics) {
|
||||
elements := make([]string, 0, len(users))
|
||||
for _, user := range users {
|
||||
elements = append(elements, user.Name)
|
||||
}
|
||||
sort.Strings(elements)
|
||||
return types.SetValueFrom(ctx, types.StringType, elements)
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"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/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
)
|
||||
|
||||
var (
|
||||
_ resource.Resource = &iamGroupPolicyResource{}
|
||||
_ resource.ResourceWithConfigure = &iamGroupPolicyResource{}
|
||||
_ resource.ResourceWithImportState = &iamGroupPolicyResource{}
|
||||
)
|
||||
|
||||
type iamGroupPolicyResource struct {
|
||||
client *iamClient
|
||||
data *providerData
|
||||
}
|
||||
|
||||
type iamGroupPolicyResourceModel struct {
|
||||
ID types.String `tfsdk:"id"`
|
||||
GroupName types.String `tfsdk:"group_name"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Policy types.String `tfsdk:"policy"`
|
||||
}
|
||||
|
||||
func NewIAMGroupPolicyResource() resource.Resource {
|
||||
return &iamGroupPolicyResource{}
|
||||
}
|
||||
|
||||
func (r *iamGroupPolicyResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_iam_group_policy"
|
||||
}
|
||||
|
||||
func (r *iamGroupPolicyResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "Manages an inline IAM group policy in SeaweedFS. Import using `group_name,policy_name`.",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{Computed: true},
|
||||
"group_name": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"policy": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "JSON policy document.",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *iamGroupPolicyResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
data, ok := req.ProviderData.(*providerData)
|
||||
if !ok {
|
||||
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
r.client = data.client
|
||||
r.data = data
|
||||
}
|
||||
|
||||
func (r *iamGroupPolicyResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
var plan iamGroupPolicyResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
policy, err := normalizeJSONString(plan.Policy.ValueString())
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid IAM group policy", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getIAMPrincipalLock("group", plan.GroupName.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := retryIAMEventuallyConsistent(ctx, 20, func() error {
|
||||
return r.client.PutGroupPolicy(ctx, plan.GroupName.ValueString(), plan.Name.ValueString(), policy)
|
||||
}); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to create IAM group policy", err.Error())
|
||||
return
|
||||
}
|
||||
plan.ID = types.StringValue(plan.GroupName.ValueString() + ":" + plan.Name.ValueString())
|
||||
plan.Policy = types.StringValue(policy)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *iamGroupPolicyResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
var state iamGroupPolicyResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getIAMPrincipalLock("group", state.GroupName.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
var remotePolicy string
|
||||
err := retryIAMRead(ctx, 6, func() error {
|
||||
var innerErr error
|
||||
remotePolicy, innerErr = r.client.GetGroupPolicy(ctx, state.GroupName.ValueString(), state.Name.ValueString())
|
||||
return innerErr
|
||||
})
|
||||
if err != nil {
|
||||
if isNoSuchEntityError(err) {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.AddError("Failed to read IAM group policy", err.Error())
|
||||
return
|
||||
}
|
||||
state.ID = types.StringValue(state.GroupName.ValueString() + ":" + state.Name.ValueString())
|
||||
if !policiesSemanticallyEqual(state.Policy.ValueString(), remotePolicy) {
|
||||
state.Policy = types.StringValue(remotePolicy)
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *iamGroupPolicyResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
var plan iamGroupPolicyResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
policy, err := normalizeJSONString(plan.Policy.ValueString())
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid IAM group policy", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getIAMPrincipalLock("group", plan.GroupName.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := retryIAMEventuallyConsistent(ctx, 20, func() error {
|
||||
return r.client.PutGroupPolicy(ctx, plan.GroupName.ValueString(), plan.Name.ValueString(), policy)
|
||||
}); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to update IAM group policy", err.Error())
|
||||
return
|
||||
}
|
||||
plan.ID = types.StringValue(plan.GroupName.ValueString() + ":" + plan.Name.ValueString())
|
||||
plan.Policy = types.StringValue(policy)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *iamGroupPolicyResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
var state iamGroupPolicyResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getIAMPrincipalLock("group", state.GroupName.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := retryIAMEventuallyConsistent(ctx, 20, func() error {
|
||||
return r.client.DeleteGroupPolicy(ctx, state.GroupName.ValueString(), state.Name.ValueString())
|
||||
}); err != nil && !isNoSuchEntityError(err) {
|
||||
resp.Diagnostics.AddError("Failed to delete IAM group policy", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (r *iamGroupPolicyResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
parts := strings.SplitN(req.ID, ",", 2)
|
||||
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
||||
resp.Diagnostics.AddError("Invalid import ID", "Expected import ID in the format `group_name,policy_name`.")
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), parts[0]+":"+parts[1])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("group_name"), parts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), parts[1])...)
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"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/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
)
|
||||
|
||||
var (
|
||||
_ resource.Resource = &iamOIDCProviderResource{}
|
||||
_ resource.ResourceWithConfigure = &iamOIDCProviderResource{}
|
||||
_ resource.ResourceWithImportState = &iamOIDCProviderResource{}
|
||||
)
|
||||
|
||||
type iamOIDCProviderResource struct {
|
||||
client *iamClient
|
||||
data *providerData
|
||||
}
|
||||
|
||||
type iamOIDCProviderResourceModel struct {
|
||||
ID types.String `tfsdk:"id"`
|
||||
ARN types.String `tfsdk:"arn"`
|
||||
URL types.String `tfsdk:"url"`
|
||||
ClientIDs types.Set `tfsdk:"client_ids"`
|
||||
Thumbprints types.Set `tfsdk:"thumbprints"`
|
||||
}
|
||||
|
||||
func NewIAMOIDCProviderResource() resource.Resource {
|
||||
return &iamOIDCProviderResource{}
|
||||
}
|
||||
|
||||
func (r *iamOIDCProviderResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_iam_oidc_provider"
|
||||
}
|
||||
|
||||
func (r *iamOIDCProviderResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "Manages a SeaweedFS IAM OpenID Connect provider. Import using the provider ARN.",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{Computed: true},
|
||||
"arn": schema.StringAttribute{Computed: true},
|
||||
"url": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Description: "Issuer URL for the OIDC provider.",
|
||||
},
|
||||
"client_ids": schema.SetAttribute{
|
||||
Required: true,
|
||||
ElementType: types.StringType,
|
||||
Description: "Client IDs allowed to use the provider.",
|
||||
},
|
||||
"thumbprints": schema.SetAttribute{
|
||||
Required: true,
|
||||
ElementType: types.StringType,
|
||||
Description: "TLS certificate thumbprints trusted for the provider. At least one is required.",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *iamOIDCProviderResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
data, ok := req.ProviderData.(*providerData)
|
||||
if !ok {
|
||||
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
r.client = data.client
|
||||
r.data = data
|
||||
}
|
||||
|
||||
func (r *iamOIDCProviderResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
var plan iamOIDCProviderResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
clientIDs, diags := stringSetElements(ctx, plan.ClientIDs)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
thumbprints, thumbDiags := stringSetElements(ctx, plan.Thumbprints)
|
||||
resp.Diagnostics.Append(thumbDiags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
if len(thumbprints) == 0 {
|
||||
resp.Diagnostics.AddError("Invalid OIDC thumbprints", "At least one TLS certificate thumbprint must be configured.")
|
||||
return
|
||||
}
|
||||
sort.Strings(clientIDs)
|
||||
sort.Strings(thumbprints)
|
||||
|
||||
lock := r.data.getIAMPrincipalLock("oidc", plan.URL.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
arn, err := r.client.CreateOIDCProvider(ctx, plan.URL.ValueString(), clientIDs, thumbprints)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Failed to create IAM OIDC provider", err.Error())
|
||||
return
|
||||
}
|
||||
if arn == "" {
|
||||
resp.Diagnostics.AddError("Invalid OIDC provider response", "SeaweedFS did not return the created provider ARN.")
|
||||
return
|
||||
}
|
||||
plan.ID = types.StringValue(arn)
|
||||
plan.ARN = types.StringValue(arn)
|
||||
plan.ClientIDs, diags = types.SetValueFrom(ctx, types.StringType, clientIDs)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
plan.Thumbprints, thumbDiags = types.SetValueFrom(ctx, types.StringType, thumbprints)
|
||||
resp.Diagnostics.Append(thumbDiags...)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *iamOIDCProviderResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
var state iamOIDCProviderResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
arn := state.ARN.ValueString()
|
||||
if arn == "" {
|
||||
arn = state.ID.ValueString()
|
||||
}
|
||||
|
||||
lock := r.data.getIAMPrincipalLock("oidc", arn)
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
provider, err := r.client.GetOIDCProvider(ctx, arn)
|
||||
if err != nil {
|
||||
if isNoSuchEntityError(err) {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.AddError("Failed to read IAM OIDC provider", err.Error())
|
||||
return
|
||||
}
|
||||
state.ID = types.StringValue(arn)
|
||||
state.ARN = types.StringValue(arn)
|
||||
state.URL = types.StringValue(provider.URL)
|
||||
clientIDs, diags := types.SetValueFrom(ctx, types.StringType, provider.ClientIDs)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
state.ClientIDs = clientIDs
|
||||
thumbprints, thumbDiags := types.SetValueFrom(ctx, types.StringType, provider.Thumbprints)
|
||||
resp.Diagnostics.Append(thumbDiags...)
|
||||
state.Thumbprints = thumbprints
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *iamOIDCProviderResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
var plan iamOIDCProviderResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
desiredClientIDs, diags := stringSetElements(ctx, plan.ClientIDs)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
desiredThumbprints, thumbDiags := stringSetElements(ctx, plan.Thumbprints)
|
||||
resp.Diagnostics.Append(thumbDiags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
if len(desiredThumbprints) == 0 {
|
||||
resp.Diagnostics.AddError("Invalid OIDC thumbprints", "At least one TLS certificate thumbprint must be configured.")
|
||||
return
|
||||
}
|
||||
sort.Strings(desiredClientIDs)
|
||||
sort.Strings(desiredThumbprints)
|
||||
|
||||
arn := plan.ARN.ValueString()
|
||||
if plan.ARN.IsUnknown() || arn == "" {
|
||||
var state iamOIDCProviderResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
arn = state.ARN.ValueString()
|
||||
if arn == "" {
|
||||
arn = state.ID.ValueString()
|
||||
}
|
||||
}
|
||||
if arn == "" {
|
||||
resp.Diagnostics.AddError("Missing OIDC provider ARN", "Terraform state and plan do not contain the provider ARN.")
|
||||
return
|
||||
}
|
||||
lock := r.data.getIAMPrincipalLock("oidc", arn)
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
current, err := r.client.GetOIDCProvider(ctx, arn)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Failed to read IAM OIDC provider before update", err.Error())
|
||||
return
|
||||
}
|
||||
currentClientIDs := make(map[string]struct{}, len(current.ClientIDs))
|
||||
desiredClientSet := make(map[string]struct{}, len(desiredClientIDs))
|
||||
for _, id := range current.ClientIDs {
|
||||
currentClientIDs[id] = struct{}{}
|
||||
}
|
||||
for _, id := range desiredClientIDs {
|
||||
desiredClientSet[id] = struct{}{}
|
||||
if _, exists := currentClientIDs[id]; !exists {
|
||||
if err := r.client.AddOIDCClientID(ctx, arn, id); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to add OIDC client ID", err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, id := range current.ClientIDs {
|
||||
if _, exists := desiredClientSet[id]; !exists {
|
||||
if err := r.client.RemoveOIDCClientID(ctx, arn, id); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to remove OIDC client ID", err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
if !sameStringSet(current.Thumbprints, desiredThumbprints) {
|
||||
if err := r.client.UpdateOIDCThumbprints(ctx, arn, desiredThumbprints); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to update OIDC thumbprints", err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
provider, err := r.client.GetOIDCProvider(ctx, arn)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Failed to read updated IAM OIDC provider", err.Error())
|
||||
return
|
||||
}
|
||||
plan.ID = types.StringValue(arn)
|
||||
plan.ARN = types.StringValue(arn)
|
||||
plan.URL = types.StringValue(provider.URL)
|
||||
clientIDs, diags := types.SetValueFrom(ctx, types.StringType, provider.ClientIDs)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
plan.ClientIDs = clientIDs
|
||||
thumbprints, thumbDiags := types.SetValueFrom(ctx, types.StringType, provider.Thumbprints)
|
||||
resp.Diagnostics.Append(thumbDiags...)
|
||||
plan.Thumbprints = thumbprints
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *iamOIDCProviderResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
var state iamOIDCProviderResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
arn := state.ARN.ValueString()
|
||||
if arn == "" {
|
||||
arn = state.ID.ValueString()
|
||||
}
|
||||
|
||||
lock := r.data.getIAMPrincipalLock("oidc", arn)
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.client.DeleteOIDCProvider(ctx, arn); err != nil && !isNoSuchEntityError(err) {
|
||||
resp.Diagnostics.AddError("Failed to delete IAM OIDC provider", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (r *iamOIDCProviderResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
arn, err := parseIAMImportID(req.ID)
|
||||
if err != nil || !strings.HasPrefix(arn, "arn:") {
|
||||
if err == nil {
|
||||
err = fmt.Errorf("expected an OIDC provider ARN")
|
||||
}
|
||||
resp.Diagnostics.AddError("Invalid import ID", err.Error())
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), arn)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("arn"), arn)...)
|
||||
}
|
||||
|
||||
func sameStringSet(left, right []string) bool {
|
||||
if len(left) != len(right) {
|
||||
return false
|
||||
}
|
||||
leftSorted := append([]string(nil), left...)
|
||||
rightSorted := append([]string(nil), right...)
|
||||
sort.Strings(leftSorted)
|
||||
sort.Strings(rightSorted)
|
||||
for i := range leftSorted {
|
||||
if leftSorted[i] != rightSorted[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"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/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
)
|
||||
|
||||
var (
|
||||
_ resource.Resource = &iamPolicyResource{}
|
||||
_ resource.ResourceWithConfigure = &iamPolicyResource{}
|
||||
_ resource.ResourceWithImportState = &iamPolicyResource{}
|
||||
)
|
||||
|
||||
type iamPolicyResource struct {
|
||||
client *iamClient
|
||||
data *providerData
|
||||
}
|
||||
|
||||
type iamPolicyResourceModel struct {
|
||||
ID types.String `tfsdk:"id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
ARN types.String `tfsdk:"arn"`
|
||||
Policy types.String `tfsdk:"policy"`
|
||||
}
|
||||
|
||||
func NewIAMPolicyResource() resource.Resource {
|
||||
return &iamPolicyResource{}
|
||||
}
|
||||
|
||||
func (r *iamPolicyResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_iam_policy"
|
||||
}
|
||||
|
||||
func (r *iamPolicyResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "Manages a SeaweedFS IAM managed policy. SeaweedFS stores one active policy version; updates replace that document in place. Import using the policy ARN or name.",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{Computed: true},
|
||||
"name": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Description: "Managed policy name.",
|
||||
},
|
||||
"arn": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Description: "Managed policy ARN.",
|
||||
},
|
||||
"policy": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "JSON policy document.",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *iamPolicyResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
data, ok := req.ProviderData.(*providerData)
|
||||
if !ok {
|
||||
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
r.client = data.client
|
||||
r.data = data
|
||||
}
|
||||
|
||||
func (r *iamPolicyResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
var plan iamPolicyResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
policy, err := normalizeJSONString(plan.Policy.ValueString())
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid IAM policy", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
managedPolicy, err := r.client.CreateManagedPolicy(ctx, plan.Name.ValueString(), policy)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Failed to create IAM policy", err.Error())
|
||||
return
|
||||
}
|
||||
arn := managedPolicy.ARN
|
||||
if arn == "" {
|
||||
arn = iamPolicyARN(plan.Name.ValueString())
|
||||
}
|
||||
plan.ID = types.StringValue(arn)
|
||||
plan.ARN = types.StringValue(arn)
|
||||
plan.Policy = types.StringValue(policy)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *iamPolicyResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
var state iamPolicyResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
arn := state.ARN.ValueString()
|
||||
if arn == "" {
|
||||
arn = state.ID.ValueString()
|
||||
}
|
||||
if !strings.HasPrefix(arn, "arn:") {
|
||||
arn = iamPolicyARN(state.Name.ValueString())
|
||||
}
|
||||
|
||||
policy, err := r.client.GetManagedPolicy(ctx, arn)
|
||||
if err != nil {
|
||||
if isNoSuchEntityError(err) {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.AddError("Failed to read IAM policy", err.Error())
|
||||
return
|
||||
}
|
||||
document, err := r.client.GetManagedPolicyDocument(ctx, arn, policy.DefaultVersion)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Failed to read IAM policy document", err.Error())
|
||||
return
|
||||
}
|
||||
normalized, err := normalizeJSONString(document)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid IAM policy returned by SeaweedFS", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
state.ID = types.StringValue(policy.ARN)
|
||||
state.ARN = types.StringValue(policy.ARN)
|
||||
state.Name = types.StringValue(policy.Name)
|
||||
if !policiesSemanticallyEqual(state.Policy.ValueString(), normalized) {
|
||||
state.Policy = types.StringValue(normalized)
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *iamPolicyResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
var plan iamPolicyResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
var state iamPolicyResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
policy, err := normalizeJSONString(plan.Policy.ValueString())
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid IAM policy", err.Error())
|
||||
return
|
||||
}
|
||||
arn := plan.ARN.ValueString()
|
||||
if plan.ARN.IsUnknown() || arn == "" {
|
||||
arn = state.ARN.ValueString()
|
||||
}
|
||||
if arn == "" {
|
||||
arn = iamPolicyARN(plan.Name.ValueString())
|
||||
}
|
||||
if err := r.client.UpdateManagedPolicy(ctx, arn, policy); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to update IAM policy", err.Error())
|
||||
return
|
||||
}
|
||||
plan.ID = types.StringValue(arn)
|
||||
plan.ARN = types.StringValue(arn)
|
||||
plan.Policy = types.StringValue(policy)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *iamPolicyResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
var state iamPolicyResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
arn := state.ARN.ValueString()
|
||||
if arn == "" {
|
||||
arn = iamPolicyARN(state.Name.ValueString())
|
||||
}
|
||||
if err := r.client.DeleteManagedPolicy(ctx, arn); err != nil && !isNoSuchEntityError(err) {
|
||||
resp.Diagnostics.AddError("Failed to delete IAM policy", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (r *iamPolicyResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
id := req.ID
|
||||
name := id
|
||||
arn := id
|
||||
if strings.HasPrefix(id, "arn:") {
|
||||
var err error
|
||||
name, err = iamPolicyNameFromARN(id)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid import ID", err.Error())
|
||||
return
|
||||
}
|
||||
} else {
|
||||
var err error
|
||||
name, err = parseIAMImportID(id)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid import ID", err.Error())
|
||||
return
|
||||
}
|
||||
arn = iamPolicyARN(name)
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), arn)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("arn"), arn)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), name)...)
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/diag"
|
||||
"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/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/tfsdk"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
)
|
||||
|
||||
type iamPolicyAttachmentOperations struct {
|
||||
suffix string
|
||||
principalType string
|
||||
principalAttr string
|
||||
}
|
||||
|
||||
type iamPolicyAttachmentResource struct {
|
||||
client *iamClient
|
||||
data *providerData
|
||||
ops iamPolicyAttachmentOperations
|
||||
}
|
||||
|
||||
type iamPolicyAttachmentResourceModel struct {
|
||||
ID types.String
|
||||
PrincipalName types.String
|
||||
PolicyARN types.String
|
||||
}
|
||||
|
||||
type iamPolicyAttachmentTerraformData interface {
|
||||
GetAttribute(context.Context, path.Path, interface{}) diag.Diagnostics
|
||||
}
|
||||
|
||||
var (
|
||||
_ resource.Resource = &iamPolicyAttachmentResource{}
|
||||
_ resource.ResourceWithConfigure = &iamPolicyAttachmentResource{}
|
||||
_ resource.ResourceWithImportState = &iamPolicyAttachmentResource{}
|
||||
)
|
||||
|
||||
func NewIAMUserPolicyAttachmentResource() resource.Resource {
|
||||
return newIAMPolicyAttachmentResource(iamPolicyAttachmentOperations{
|
||||
suffix: "iam_user_policy_attachment", principalType: "user", principalAttr: "user_name",
|
||||
})
|
||||
}
|
||||
|
||||
func NewIAMGroupPolicyAttachmentResource() resource.Resource {
|
||||
return newIAMPolicyAttachmentResource(iamPolicyAttachmentOperations{
|
||||
suffix: "iam_group_policy_attachment", principalType: "group", principalAttr: "group_name",
|
||||
})
|
||||
}
|
||||
|
||||
func NewIAMRolePolicyAttachmentResource() resource.Resource {
|
||||
return newIAMPolicyAttachmentResource(iamPolicyAttachmentOperations{
|
||||
suffix: "iam_role_policy_attachment", principalType: "role", principalAttr: "role_name",
|
||||
})
|
||||
}
|
||||
|
||||
func newIAMPolicyAttachmentResource(ops iamPolicyAttachmentOperations) resource.Resource {
|
||||
return &iamPolicyAttachmentResource{ops: ops}
|
||||
}
|
||||
|
||||
func (r *iamPolicyAttachmentResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_" + r.ops.suffix
|
||||
}
|
||||
|
||||
func (r *iamPolicyAttachmentResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: fmt.Sprintf("Manages attachment of an existing managed IAM policy to a SeaweedFS IAM %s. Import using `%s,policy_arn`.", r.ops.principalType, r.ops.principalAttr),
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{Computed: true},
|
||||
r.ops.principalAttr: schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Description: fmt.Sprintf("IAM %s name.", r.ops.principalType),
|
||||
},
|
||||
"policy_arn": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Description: "ARN of the managed IAM policy.",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *iamPolicyAttachmentResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
data, ok := req.ProviderData.(*providerData)
|
||||
if !ok {
|
||||
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
r.client = data.client
|
||||
r.data = data
|
||||
}
|
||||
|
||||
func (r *iamPolicyAttachmentResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
plan, diags := r.modelFromData(ctx, req.Plan)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
principal := plan.PrincipalName.ValueString()
|
||||
lock := r.principalLock(principal)
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := retryIAMEventuallyConsistent(ctx, 20, func() error {
|
||||
return r.client.AttachManagedPolicy(ctx, r.ops.principalType, principal, plan.PolicyARN.ValueString(), true)
|
||||
}); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to attach IAM policy", err.Error())
|
||||
return
|
||||
}
|
||||
plan.ID = types.StringValue(principal + "," + plan.PolicyARN.ValueString())
|
||||
resp.Diagnostics.Append(r.writeState(ctx, &resp.State, plan)...)
|
||||
}
|
||||
|
||||
func (r *iamPolicyAttachmentResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
state, diags := r.modelFromData(ctx, req.State)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
principal := state.PrincipalName.ValueString()
|
||||
lock := r.principalLock(principal)
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
var attachedPolicies []iamAttachedPolicy
|
||||
err := retryIAMRead(ctx, 6, func() error {
|
||||
var innerErr error
|
||||
attachedPolicies, innerErr = r.client.ListAttachedManagedPolicies(ctx, r.ops.principalType, principal)
|
||||
return innerErr
|
||||
})
|
||||
if err != nil {
|
||||
if isNoSuchEntityError(err) {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.AddError("Failed to read IAM policy attachment", err.Error())
|
||||
return
|
||||
}
|
||||
found := false
|
||||
for _, attached := range attachedPolicies {
|
||||
if attached.ARN == state.PolicyARN.ValueString() {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
|
||||
state.ID = types.StringValue(principal + "," + state.PolicyARN.ValueString())
|
||||
resp.Diagnostics.Append(r.writeState(ctx, &resp.State, state)...)
|
||||
}
|
||||
|
||||
func (r *iamPolicyAttachmentResource) Update(_ context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
resp.Diagnostics.AddError("Unsupported IAM policy attachment update", "Changing the IAM principal or policy requires replacing this attachment.")
|
||||
}
|
||||
|
||||
func (r *iamPolicyAttachmentResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
state, diags := r.modelFromData(ctx, req.State)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
principal := state.PrincipalName.ValueString()
|
||||
lock := r.principalLock(principal)
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.client.AttachManagedPolicy(ctx, r.ops.principalType, principal, state.PolicyARN.ValueString(), false); err != nil && !isNoSuchEntityError(err) {
|
||||
resp.Diagnostics.AddError("Failed to detach IAM policy", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (r *iamPolicyAttachmentResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
parts := strings.SplitN(req.ID, ",", 2)
|
||||
if len(parts) != 2 || parts[0] == "" || parts[1] == "" || strings.TrimSpace(parts[0]) != parts[0] || strings.TrimSpace(parts[1]) != parts[1] {
|
||||
resp.Diagnostics.AddError("Invalid import ID", "Expected import ID in the format `principal_name,policy_arn`.")
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), types.StringValue(req.ID))...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root(r.ops.principalAttr), parts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("policy_arn"), parts[1])...)
|
||||
}
|
||||
|
||||
func (r *iamPolicyAttachmentResource) modelFromData(ctx context.Context, data iamPolicyAttachmentTerraformData) (iamPolicyAttachmentResourceModel, diag.Diagnostics) {
|
||||
var model iamPolicyAttachmentResourceModel
|
||||
var diags diag.Diagnostics
|
||||
diags.Append(data.GetAttribute(ctx, path.Root("id"), &model.ID)...)
|
||||
diags.Append(data.GetAttribute(ctx, path.Root(r.ops.principalAttr), &model.PrincipalName)...)
|
||||
diags.Append(data.GetAttribute(ctx, path.Root("policy_arn"), &model.PolicyARN)...)
|
||||
return model, diags
|
||||
}
|
||||
|
||||
func (r *iamPolicyAttachmentResource) writeState(ctx context.Context, state *tfsdk.State, model iamPolicyAttachmentResourceModel) diag.Diagnostics {
|
||||
var diags diag.Diagnostics
|
||||
diags.Append(state.SetAttribute(ctx, path.Root("id"), model.ID)...)
|
||||
diags.Append(state.SetAttribute(ctx, path.Root(r.ops.principalAttr), model.PrincipalName)...)
|
||||
diags.Append(state.SetAttribute(ctx, path.Root("policy_arn"), model.PolicyARN)...)
|
||||
return diags
|
||||
}
|
||||
|
||||
func (r *iamPolicyAttachmentResource) principalLock(name string) interface {
|
||||
Lock()
|
||||
Unlock()
|
||||
} {
|
||||
if r.ops.principalType == "user" {
|
||||
return r.data.getUserLock(name)
|
||||
}
|
||||
return r.data.getIAMPrincipalLock(r.ops.principalType, name)
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/diag"
|
||||
"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/int64planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
)
|
||||
|
||||
var (
|
||||
_ resource.Resource = &iamRoleResource{}
|
||||
_ resource.ResourceWithConfigure = &iamRoleResource{}
|
||||
_ resource.ResourceWithImportState = &iamRoleResource{}
|
||||
)
|
||||
|
||||
type iamRoleResource struct {
|
||||
client *iamClient
|
||||
data *providerData
|
||||
}
|
||||
|
||||
type iamRoleResourceModel struct {
|
||||
ID types.String `tfsdk:"id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
AssumeRolePolicy types.String `tfsdk:"assume_role_policy"`
|
||||
Description types.String `tfsdk:"description"`
|
||||
MaxSessionDuration types.Int64 `tfsdk:"max_session_duration"`
|
||||
}
|
||||
|
||||
func NewIAMRoleResource() resource.Resource {
|
||||
return &iamRoleResource{}
|
||||
}
|
||||
|
||||
func (r *iamRoleResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_iam_role"
|
||||
}
|
||||
|
||||
func (r *iamRoleResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "Manages a SeaweedFS IAM role. SeaweedFS roles do not support paths or mutable descriptions/session duration; changing those attributes replaces the role. Import using the role name.",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{Computed: true},
|
||||
"name": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Description: "IAM role name.",
|
||||
},
|
||||
"assume_role_policy": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "JSON trust policy document.",
|
||||
},
|
||||
"description": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Description: "Role description.",
|
||||
},
|
||||
"max_session_duration": schema.Int64Attribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.Int64{
|
||||
int64planmodifier.RequiresReplace(),
|
||||
},
|
||||
Description: "Maximum role session duration in seconds.",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *iamRoleResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
data, ok := req.ProviderData.(*providerData)
|
||||
if !ok {
|
||||
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
r.client = data.client
|
||||
r.data = data
|
||||
}
|
||||
|
||||
func (r *iamRoleResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
var plan iamRoleResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
normalized, err := normalizeJSONString(plan.AssumeRolePolicy.ValueString())
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid role trust policy", err.Error())
|
||||
return
|
||||
}
|
||||
maxSession := int64(0)
|
||||
if !plan.MaxSessionDuration.IsNull() && !plan.MaxSessionDuration.IsUnknown() {
|
||||
maxSession = plan.MaxSessionDuration.ValueInt64()
|
||||
}
|
||||
|
||||
lock := r.data.getIAMPrincipalLock("role", plan.Name.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
role, err := r.client.CreateRole(ctx, plan.Name.ValueString(), normalized, plan.Description.ValueString(), maxSession)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Failed to create IAM role", err.Error())
|
||||
return
|
||||
}
|
||||
if err := r.setState(&plan, role, &resp.Diagnostics); err != nil {
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *iamRoleResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
var state iamRoleResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getIAMPrincipalLock("role", state.Name.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
role, err := r.client.GetRole(ctx, state.Name.ValueString())
|
||||
if err != nil {
|
||||
if isNoSuchEntityError(err) {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.AddError("Failed to read IAM role", err.Error())
|
||||
return
|
||||
}
|
||||
if err := r.setState(&state, role, &resp.Diagnostics); err != nil {
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *iamRoleResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
var plan iamRoleResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
normalized, err := normalizeJSONString(plan.AssumeRolePolicy.ValueString())
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid role trust policy", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getIAMPrincipalLock("role", plan.Name.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.client.UpdateAssumeRolePolicy(ctx, plan.Name.ValueString(), normalized); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to update IAM role trust policy", err.Error())
|
||||
return
|
||||
}
|
||||
role, err := r.client.GetRole(ctx, plan.Name.ValueString())
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Failed to read updated IAM role", err.Error())
|
||||
return
|
||||
}
|
||||
if err := r.setState(&plan, role, &resp.Diagnostics); err != nil {
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *iamRoleResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
var state iamRoleResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getIAMPrincipalLock("role", state.Name.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.client.DeleteRole(ctx, state.Name.ValueString()); err != nil && !isNoSuchEntityError(err) {
|
||||
resp.Diagnostics.AddError("Failed to delete IAM role", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (r *iamRoleResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
name, err := parseIAMImportID(req.ID)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid import ID", err.Error())
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), name)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), name)...)
|
||||
}
|
||||
|
||||
func (r *iamRoleResource) setState(state *iamRoleResourceModel, role iamRole, diags *diag.Diagnostics) error {
|
||||
policy, err := normalizeJSONString(role.AssumeRolePolicy)
|
||||
if err != nil {
|
||||
diags.AddError("Invalid role trust policy returned by SeaweedFS", err.Error())
|
||||
return err
|
||||
}
|
||||
if !state.AssumeRolePolicy.IsNull() && !state.AssumeRolePolicy.IsUnknown() &&
|
||||
policiesSemanticallyEqual(state.AssumeRolePolicy.ValueString(), policy) {
|
||||
policy = state.AssumeRolePolicy.ValueString()
|
||||
}
|
||||
state.ID = types.StringValue(role.Name)
|
||||
state.Name = types.StringValue(role.Name)
|
||||
state.AssumeRolePolicy = types.StringValue(policy)
|
||||
state.Description = types.StringValue(role.Description)
|
||||
state.MaxSessionDuration = types.Int64Value(role.MaxSessionDuration)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"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/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
)
|
||||
|
||||
var (
|
||||
_ resource.Resource = &iamServiceAccountResource{}
|
||||
_ resource.ResourceWithConfigure = &iamServiceAccountResource{}
|
||||
_ resource.ResourceWithImportState = &iamServiceAccountResource{}
|
||||
)
|
||||
|
||||
type iamServiceAccountResource struct {
|
||||
client *iamClient
|
||||
data *providerData
|
||||
}
|
||||
|
||||
type iamServiceAccountResourceModel struct {
|
||||
ID types.String `tfsdk:"id"`
|
||||
ServiceAccountID types.String `tfsdk:"service_account_id"`
|
||||
ParentUser types.String `tfsdk:"parent_user"`
|
||||
Description types.String `tfsdk:"description"`
|
||||
Expiration types.String `tfsdk:"expiration"`
|
||||
Status types.String `tfsdk:"status"`
|
||||
AccessKeyID types.String `tfsdk:"access_key_id"`
|
||||
SecretAccessKey types.String `tfsdk:"secret_key"`
|
||||
}
|
||||
|
||||
func NewIAMServiceAccountResource() resource.Resource {
|
||||
return &iamServiceAccountResource{}
|
||||
}
|
||||
|
||||
func (r *iamServiceAccountResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_iam_service_account"
|
||||
}
|
||||
|
||||
func (r *iamServiceAccountResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "Manages a SeaweedFS IAM service account. The secret key is returned only at creation and is retained in Terraform state; mark state storage as sensitive. Import using the service account ID.",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{Computed: true},
|
||||
"service_account_id": schema.StringAttribute{Computed: true},
|
||||
"parent_user": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Description: "IAM user that owns this service account.",
|
||||
},
|
||||
"description": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Description: "Service account description. Set to an empty string to clear it.",
|
||||
},
|
||||
"expiration": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Description: "Expiration time in RFC3339 format. Set to an empty string to remove expiration.",
|
||||
},
|
||||
"status": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Description: "Credential status: Active or Inactive.",
|
||||
},
|
||||
"access_key_id": schema.StringAttribute{Computed: true},
|
||||
"secret_key": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Sensitive: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *iamServiceAccountResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
data, ok := req.ProviderData.(*providerData)
|
||||
if !ok {
|
||||
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
r.client = data.client
|
||||
r.data = data
|
||||
}
|
||||
|
||||
func (r *iamServiceAccountResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
var plan iamServiceAccountResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
expiration, err := expirationToUnix(plan.Expiration.ValueString())
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid service account expiration", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getUserLock(plan.ParentUser.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
account, err := r.client.CreateServiceAccount(ctx, plan.ParentUser.ValueString(), plan.Description.ValueString(), expiration)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Failed to create IAM service account", err.Error())
|
||||
return
|
||||
}
|
||||
if account.ID == "" || account.AccessKeyID == "" || account.SecretAccessKey == "" {
|
||||
cleanupErr := r.client.DeleteServiceAccount(ctx, account.ID)
|
||||
message := "SeaweedFS did not return the service account ID and credentials."
|
||||
if cleanupErr != nil && !isNoSuchEntityError(cleanupErr) {
|
||||
message += " Cleanup also failed: " + cleanupErr.Error()
|
||||
}
|
||||
resp.Diagnostics.AddError("Invalid service account response", message)
|
||||
return
|
||||
}
|
||||
if !plan.Status.IsNull() && plan.Status.ValueString() != "" && plan.Status.ValueString() != account.Status {
|
||||
if err := r.client.UpdateServiceAccount(ctx, account.ID, plan.Status.ValueString(), account.Description, expiration); err != nil {
|
||||
cleanupErr := r.client.DeleteServiceAccount(ctx, account.ID)
|
||||
message := err.Error()
|
||||
if cleanupErr != nil && !isNoSuchEntityError(cleanupErr) {
|
||||
message += "; cleanup failed: " + cleanupErr.Error()
|
||||
}
|
||||
resp.Diagnostics.AddError("Failed to set initial service account status", message)
|
||||
return
|
||||
}
|
||||
account.Status = plan.Status.ValueString()
|
||||
}
|
||||
r.setServiceAccountState(&plan, account)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *iamServiceAccountResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
var state iamServiceAccountResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
accountID := state.ServiceAccountID.ValueString()
|
||||
if accountID == "" {
|
||||
accountID = state.ID.ValueString()
|
||||
}
|
||||
|
||||
lock := r.data.getUserLock(state.ParentUser.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
account, err := r.client.GetServiceAccount(ctx, accountID)
|
||||
if err != nil {
|
||||
if isNoSuchEntityError(err) {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.AddError("Failed to read IAM service account", err.Error())
|
||||
return
|
||||
}
|
||||
secret := state.SecretAccessKey
|
||||
r.setServiceAccountState(&state, account)
|
||||
state.SecretAccessKey = secret
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *iamServiceAccountResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
var plan iamServiceAccountResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
var state iamServiceAccountResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
accountID := plan.ServiceAccountID.ValueString()
|
||||
if plan.ServiceAccountID.IsUnknown() || accountID == "" {
|
||||
accountID = state.ServiceAccountID.ValueString()
|
||||
}
|
||||
if accountID == "" {
|
||||
accountID = state.ID.ValueString()
|
||||
}
|
||||
if accountID == "" {
|
||||
resp.Diagnostics.AddError("Missing service account ID", "Terraform state and plan do not contain the service account ID.")
|
||||
return
|
||||
}
|
||||
plan.ID = types.StringValue(accountID)
|
||||
plan.ServiceAccountID = types.StringValue(accountID)
|
||||
if plan.SecretAccessKey.IsUnknown() || plan.SecretAccessKey.IsNull() {
|
||||
plan.SecretAccessKey = state.SecretAccessKey
|
||||
}
|
||||
expiration, err := expirationToUnix(plan.Expiration.ValueString())
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid service account expiration", err.Error())
|
||||
return
|
||||
}
|
||||
if plan.Status.ValueString() != "" && plan.Status.ValueString() != "Active" && plan.Status.ValueString() != "Inactive" {
|
||||
resp.Diagnostics.AddError("Invalid service account status", "Status must be Active or Inactive.")
|
||||
return
|
||||
}
|
||||
|
||||
lock := r.data.getUserLock(plan.ParentUser.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.client.UpdateServiceAccount(ctx, accountID, plan.Status.ValueString(), plan.Description.ValueString(), expiration); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to update IAM service account", err.Error())
|
||||
return
|
||||
}
|
||||
account, err := r.client.GetServiceAccount(ctx, accountID)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Failed to read updated IAM service account", err.Error())
|
||||
return
|
||||
}
|
||||
secret := plan.SecretAccessKey
|
||||
r.setServiceAccountState(&plan, account)
|
||||
plan.SecretAccessKey = secret
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *iamServiceAccountResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
var state iamServiceAccountResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
accountID := state.ServiceAccountID.ValueString()
|
||||
if accountID == "" {
|
||||
accountID = state.ID.ValueString()
|
||||
}
|
||||
|
||||
lock := r.data.getUserLock(state.ParentUser.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.client.DeleteServiceAccount(ctx, accountID); err != nil && !isNoSuchEntityError(err) {
|
||||
resp.Diagnostics.AddError("Failed to delete IAM service account", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (r *iamServiceAccountResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
id := req.ID
|
||||
if !strings.HasPrefix(id, "sa:") || strings.TrimSpace(id) != id {
|
||||
resp.Diagnostics.AddError("Invalid import ID", "Expected import ID in the format `sa:parent_user:identifier`.")
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), id)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("service_account_id"), id)...)
|
||||
}
|
||||
|
||||
func (r *iamServiceAccountResource) setServiceAccountState(state *iamServiceAccountResourceModel, account iamServiceAccount) {
|
||||
state.ID = types.StringValue(account.ID)
|
||||
state.ServiceAccountID = types.StringValue(account.ID)
|
||||
state.ParentUser = types.StringValue(account.ParentUser)
|
||||
state.Description = types.StringValue(account.Description)
|
||||
state.Expiration = types.StringValue(account.Expiration)
|
||||
state.Status = types.StringValue(account.Status)
|
||||
state.AccessKeyID = types.StringValue(account.AccessKeyID)
|
||||
if account.SecretAccessKey != "" {
|
||||
state.SecretAccessKey = types.StringValue(account.SecretAccessKey)
|
||||
}
|
||||
}
|
||||
|
||||
func expirationToUnix(value string) (string, error) {
|
||||
if value == "" {
|
||||
return "", nil
|
||||
}
|
||||
expiration, err := time.Parse(time.RFC3339, value)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("expiration must use RFC3339 format: %w", err)
|
||||
}
|
||||
return strconv.FormatInt(expiration.Unix(), 10), nil
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package seaweedfs
|
||||
|
||||
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 = &iamUserResource{}
|
||||
_ resource.ResourceWithConfigure = &iamUserResource{}
|
||||
_ resource.ResourceWithImportState = &iamUserResource{}
|
||||
)
|
||||
|
||||
func NewIAMUserResource() resource.Resource {
|
||||
return &iamUserResource{}
|
||||
}
|
||||
|
||||
type iamUserResource struct {
|
||||
client *iamClient
|
||||
data *providerData
|
||||
}
|
||||
|
||||
type iamUserResourceModel struct {
|
||||
ID types.String `tfsdk:"id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Path types.String `tfsdk:"path"`
|
||||
ARN types.String `tfsdk:"arn"`
|
||||
UserID types.String `tfsdk:"user_id"`
|
||||
}
|
||||
|
||||
func (r *iamUserResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_iam_user"
|
||||
}
|
||||
|
||||
func (r *iamUserResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "Manages a SeaweedFS IAM user using IAM query API calls.",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Description: "Terraform identifier for this resource. Equals user name.",
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "IAM user name.",
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"path": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Default: stringdefault.StaticString("/"),
|
||||
Description: "IAM path for the user. SeaweedFS 4.51.0 supports only `/`.",
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"arn": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Description: "ARN returned by SeaweedFS.",
|
||||
},
|
||||
"user_id": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Description: "Unique user identifier returned by SeaweedFS.",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *iamUserResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
data, ok := req.ProviderData.(*providerData)
|
||||
if !ok {
|
||||
resp.Diagnostics.AddError(
|
||||
"Unexpected provider data type",
|
||||
fmt.Sprintf("Expected *providerData, got %T", req.ProviderData),
|
||||
)
|
||||
return
|
||||
}
|
||||
r.client = data.client
|
||||
r.data = data
|
||||
}
|
||||
|
||||
func (r *iamUserResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
var plan iamUserResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
if plan.Path.ValueString() != "/" {
|
||||
resp.Diagnostics.AddError("Unsupported IAM user path", "SeaweedFS 4.51.0 supports only the root IAM path `/`.")
|
||||
return
|
||||
}
|
||||
|
||||
var user getUserResponse
|
||||
err := r.data.withUserLock(plan.Name.ValueString(), func() error {
|
||||
return retryIAMEventuallyConsistent(ctx, 8, func() error {
|
||||
var innerErr error
|
||||
user, innerErr = r.client.CreateUser(ctx, plan.Name.ValueString(), plan.Path.ValueString())
|
||||
return innerErr
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
if isEntityAlreadyExistsError(err) {
|
||||
readErr := retryIAMEventuallyConsistent(ctx, 6, func() error {
|
||||
var innerErr error
|
||||
user, innerErr = r.client.GetUser(ctx, plan.Name.ValueString())
|
||||
return innerErr
|
||||
})
|
||||
if readErr != nil {
|
||||
resp.Diagnostics.AddError(
|
||||
"Failed to read existing IAM user",
|
||||
readErr.Error(),
|
||||
)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
resp.Diagnostics.AddError(
|
||||
"Failed to create IAM user",
|
||||
err.Error(),
|
||||
)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
userPath := user.User.Path
|
||||
if userPath == "" {
|
||||
userPath = plan.Path.ValueString()
|
||||
if userPath == "" {
|
||||
userPath = "/"
|
||||
}
|
||||
}
|
||||
|
||||
// SeaweedFS may acknowledge CreateUser before the user is fully visible
|
||||
// to subsequent IAM operations. Ensure visibility before finishing Create.
|
||||
if err := retryIAMEventuallyConsistent(ctx, 20, func() error {
|
||||
_, innerErr := r.client.GetUser(ctx, user.User.UserName)
|
||||
return innerErr
|
||||
}); err != nil {
|
||||
resp.Diagnostics.AddError(
|
||||
"Failed to verify IAM user visibility",
|
||||
err.Error(),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
state := iamUserResourceModel{
|
||||
ID: types.StringValue(user.User.UserName),
|
||||
Name: types.StringValue(user.User.UserName),
|
||||
Path: types.StringValue(userPath),
|
||||
ARN: types.StringValue(user.User.Arn),
|
||||
UserID: types.StringValue(user.User.UserID),
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *iamUserResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
var state iamUserResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
var user getUserResponse
|
||||
err := retryIAMEventuallyConsistent(ctx, 6, func() error {
|
||||
var innerErr error
|
||||
user, innerErr = r.client.GetUser(ctx, state.Name.ValueString())
|
||||
return innerErr
|
||||
})
|
||||
if err != nil {
|
||||
if isNoSuchEntityError(err) {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.AddError(
|
||||
"Failed to read IAM user",
|
||||
err.Error(),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
userPath := user.User.Path
|
||||
if userPath == "" {
|
||||
userPath = state.Path.ValueString()
|
||||
if userPath == "" {
|
||||
userPath = "/"
|
||||
}
|
||||
}
|
||||
|
||||
state.ID = types.StringValue(user.User.UserName)
|
||||
state.Name = types.StringValue(user.User.UserName)
|
||||
state.Path = types.StringValue(userPath)
|
||||
state.ARN = types.StringValue(user.User.Arn)
|
||||
state.UserID = types.StringValue(user.User.UserID)
|
||||
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *iamUserResource) Update(_ context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
resp.Diagnostics.AddError(
|
||||
"Update not supported",
|
||||
"seaweedfs_iam_user currently supports replacement on changes to name/path only.",
|
||||
)
|
||||
}
|
||||
|
||||
func (r *iamUserResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
var state iamUserResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.data.withUserLock(state.Name.ValueString(), func() error {
|
||||
return retryIAMEventuallyConsistent(ctx, 8, func() error {
|
||||
return r.client.DeleteUser(ctx, state.Name.ValueString())
|
||||
})
|
||||
}); err != nil && !isNoSuchEntityError(err) {
|
||||
resp.Diagnostics.AddError(
|
||||
"Failed to delete IAM user",
|
||||
err.Error(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *iamUserResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), req.ID)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), req.ID)...)
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"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/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
)
|
||||
|
||||
var (
|
||||
_ resource.Resource = &iamUserPolicyResource{}
|
||||
_ resource.ResourceWithConfigure = &iamUserPolicyResource{}
|
||||
_ resource.ResourceWithImportState = &iamUserPolicyResource{}
|
||||
)
|
||||
|
||||
func NewIAMUserPolicyResource() resource.Resource {
|
||||
return &iamUserPolicyResource{}
|
||||
}
|
||||
|
||||
type iamUserPolicyResource struct {
|
||||
client *iamClient
|
||||
data *providerData
|
||||
}
|
||||
|
||||
type iamUserPolicyResourceModel struct {
|
||||
ID types.String `tfsdk:"id"`
|
||||
UserName types.String `tfsdk:"user_name"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Policy types.String `tfsdk:"policy"`
|
||||
}
|
||||
|
||||
func (r *iamUserPolicyResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_iam_user_policy"
|
||||
}
|
||||
|
||||
func (r *iamUserPolicyResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "Manages an inline IAM user policy in SeaweedFS.",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"user_name": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"policy": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "JSON policy document.",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *iamUserPolicyResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
data, ok := req.ProviderData.(*providerData)
|
||||
if !ok {
|
||||
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
r.client = data.client
|
||||
r.data = data
|
||||
}
|
||||
|
||||
func (r *iamUserPolicyResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
var plan iamUserPolicyResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
policyToWrite := plan.Policy.ValueString()
|
||||
if normalized, err := normalizeJSONString(policyToWrite); err == nil {
|
||||
policyToWrite = normalized
|
||||
}
|
||||
|
||||
if err := r.data.withUserLock(plan.UserName.ValueString(), func() error {
|
||||
return retryIAMEventuallyConsistent(ctx, 20, func() error {
|
||||
return r.client.PutUserPolicy(ctx, plan.UserName.ValueString(), plan.Name.ValueString(), policyToWrite)
|
||||
})
|
||||
}); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to create IAM user policy", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
state := iamUserPolicyResourceModel{
|
||||
ID: types.StringValue(plan.UserName.ValueString() + ":" + plan.Name.ValueString()),
|
||||
UserName: types.StringValue(plan.UserName.ValueString()),
|
||||
Name: types.StringValue(plan.Name.ValueString()),
|
||||
Policy: types.StringValue(plan.Policy.ValueString()),
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *iamUserPolicyResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
var state iamUserPolicyResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
var remotePolicy string
|
||||
err := retryIAMRead(ctx, 6, func() error {
|
||||
var innerErr error
|
||||
remotePolicy, innerErr = r.client.GetUserPolicy(ctx, state.UserName.ValueString(), state.Name.ValueString())
|
||||
return innerErr
|
||||
})
|
||||
if err != nil {
|
||||
if isNoSuchEntityError(err) {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.AddError("Failed to read IAM user policy", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
state.ID = types.StringValue(state.UserName.ValueString() + ":" + state.Name.ValueString())
|
||||
if !policiesSemanticallyEqual(state.Policy.ValueString(), remotePolicy) {
|
||||
state.Policy = types.StringValue(remotePolicy)
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *iamUserPolicyResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
var plan iamUserPolicyResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
policyToWrite := plan.Policy.ValueString()
|
||||
if normalized, err := normalizeJSONString(policyToWrite); err == nil {
|
||||
policyToWrite = normalized
|
||||
}
|
||||
|
||||
if err := r.data.withUserLock(plan.UserName.ValueString(), func() error {
|
||||
return retryIAMEventuallyConsistent(ctx, 20, func() error {
|
||||
return r.client.PutUserPolicy(ctx, plan.UserName.ValueString(), plan.Name.ValueString(), policyToWrite)
|
||||
})
|
||||
}); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to update IAM user policy", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
state := iamUserPolicyResourceModel{
|
||||
ID: types.StringValue(plan.UserName.ValueString() + ":" + plan.Name.ValueString()),
|
||||
UserName: types.StringValue(plan.UserName.ValueString()),
|
||||
Name: types.StringValue(plan.Name.ValueString()),
|
||||
Policy: types.StringValue(plan.Policy.ValueString()),
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *iamUserPolicyResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
var state iamUserPolicyResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
if err := r.data.withUserLock(state.UserName.ValueString(), func() error {
|
||||
return retryIAMEventuallyConsistent(ctx, 20, func() error {
|
||||
return r.client.DeleteUserPolicy(ctx, state.UserName.ValueString(), state.Name.ValueString())
|
||||
})
|
||||
}); err != nil && !isNoSuchEntityError(err) {
|
||||
resp.Diagnostics.AddError("Failed to delete IAM user policy", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (r *iamUserPolicyResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
parts := strings.SplitN(req.ID, ",", 2)
|
||||
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
||||
resp.Diagnostics.AddError(
|
||||
"Invalid import ID",
|
||||
"Expected import id in format `user_name,policy_name`.",
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), parts[0]+":"+parts[1])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("user_name"), parts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), parts[1])...)
|
||||
}
|
||||
@@ -0,0 +1,570 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/diag"
|
||||
"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/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/tfsdk"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
)
|
||||
|
||||
type s3TableMaintenanceResource struct {
|
||||
client *iamClient
|
||||
data *providerData
|
||||
table bool
|
||||
}
|
||||
|
||||
type s3TableMaintenanceResourceModel struct {
|
||||
ID types.String
|
||||
TableBucketARN types.String
|
||||
Namespace types.String
|
||||
Name types.String
|
||||
Type types.String
|
||||
Status types.String
|
||||
Strategy types.String
|
||||
TargetFileSizeMB types.Int64
|
||||
MinSnapshotsToKeep types.Int64
|
||||
MaxSnapshotAgeHours types.Int64
|
||||
UnreferencedDays types.Int64
|
||||
NonCurrentDays types.Int64
|
||||
}
|
||||
|
||||
type s3TableMaintenanceTerraformData interface {
|
||||
GetAttribute(context.Context, path.Path, interface{}) diag.Diagnostics
|
||||
}
|
||||
|
||||
var (
|
||||
_ resource.Resource = &s3TableMaintenanceResource{}
|
||||
_ resource.ResourceWithConfigure = &s3TableMaintenanceResource{}
|
||||
_ resource.ResourceWithImportState = &s3TableMaintenanceResource{}
|
||||
)
|
||||
|
||||
func NewS3TableBucketMaintenanceConfigurationResource() resource.Resource {
|
||||
return &s3TableMaintenanceResource{}
|
||||
}
|
||||
|
||||
func NewS3TableMaintenanceConfigurationResource() resource.Resource {
|
||||
return &s3TableMaintenanceResource{table: true}
|
||||
}
|
||||
|
||||
func (r *s3TableMaintenanceResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
suffix := "_table_bucket_maintenance_configuration"
|
||||
if r.table {
|
||||
suffix = "_table_maintenance_configuration"
|
||||
}
|
||||
resp.TypeName = req.ProviderTypeName + suffix
|
||||
}
|
||||
|
||||
func (r *s3TableMaintenanceResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
attributes := map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{Computed: true},
|
||||
"table_bucket_arn": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"status": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "Whether the maintenance operation is enabled or disabled.",
|
||||
},
|
||||
}
|
||||
if r.table {
|
||||
attributes["namespace"] = schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
}
|
||||
attributes["name"] = schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
}
|
||||
attributes["type"] = schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "Maintenance type: icebergCompaction or icebergSnapshotManagement.",
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
}
|
||||
attributes["strategy"] = schema.StringAttribute{
|
||||
Optional: true,
|
||||
Description: "Compaction strategy: auto, binpack, or sort. Only applies to icebergCompaction.",
|
||||
}
|
||||
attributes["target_file_size_mb"] = schema.Int64Attribute{
|
||||
Optional: true,
|
||||
Description: "Target compacted file size in MiB. Only applies to icebergCompaction.",
|
||||
}
|
||||
attributes["min_snapshots_to_keep"] = schema.Int64Attribute{
|
||||
Optional: true,
|
||||
Description: "Minimum snapshots to retain. Only applies to icebergSnapshotManagement.",
|
||||
}
|
||||
attributes["max_snapshot_age_hours"] = schema.Int64Attribute{
|
||||
Optional: true,
|
||||
Description: "Maximum snapshot age in hours. Only applies to icebergSnapshotManagement.",
|
||||
}
|
||||
} else {
|
||||
attributes["type"] = schema.StringAttribute{
|
||||
Computed: true,
|
||||
Description: "The bucket maintenance type is icebergUnreferencedFileRemoval.",
|
||||
}
|
||||
attributes["unreferenced_days"] = schema.Int64Attribute{
|
||||
Optional: true,
|
||||
Description: "Age in days after which unreferenced files may be removed.",
|
||||
}
|
||||
attributes["non_current_days"] = schema.Int64Attribute{
|
||||
Optional: true,
|
||||
Description: "Age in days after which non-current files may be removed.",
|
||||
}
|
||||
}
|
||||
|
||||
importDescription := "`table_bucket_arn`"
|
||||
if r.table {
|
||||
importDescription = "`table_bucket_arn,namespace,table_name,type`"
|
||||
}
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "Manages a SeaweedFS S3 Tables maintenance configuration. Import using " + importDescription + ". Deletion disables the configuration because the S3 Tables API has no delete operation.",
|
||||
Attributes: attributes,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *s3TableMaintenanceResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
data, ok := req.ProviderData.(*providerData)
|
||||
if !ok {
|
||||
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
r.client = data.client
|
||||
r.data = data
|
||||
}
|
||||
|
||||
func (r *s3TableMaintenanceResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
plan, diags := r.modelFromData(ctx, req.Plan)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
value, err := r.value(plan)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid S3 Tables maintenance configuration", err.Error())
|
||||
return
|
||||
}
|
||||
lock := r.data.getBucketLock("tables:" + plan.TableBucketARN.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.put(ctx, plan, value); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to create S3 Tables maintenance configuration", err.Error())
|
||||
return
|
||||
}
|
||||
current, err := r.get(ctx, plan)
|
||||
if err != nil {
|
||||
message := r.cleanupFailedCreate(ctx, plan, err.Error())
|
||||
resp.Diagnostics.AddError("Failed to read created S3 Tables maintenance configuration", message)
|
||||
return
|
||||
}
|
||||
if current == nil {
|
||||
message := r.cleanupFailedCreate(ctx, plan, "SeaweedFS did not return the configuration that was just created.")
|
||||
resp.Diagnostics.AddError("Missing S3 Tables maintenance configuration", message)
|
||||
return
|
||||
}
|
||||
if err := r.setState(&plan, current); err != nil {
|
||||
message := r.cleanupFailedCreate(ctx, plan, err.Error())
|
||||
resp.Diagnostics.AddError("Invalid S3 Tables maintenance configuration returned by SeaweedFS", message)
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(r.writeState(ctx, &resp.State, plan)...)
|
||||
}
|
||||
|
||||
func (r *s3TableMaintenanceResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
state, diags := r.modelFromData(ctx, req.State)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
lock := r.data.getBucketLock("tables:" + state.TableBucketARN.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
current, err := r.get(ctx, state)
|
||||
if err != nil {
|
||||
if isNoSuchS3TablesEntityError(err) {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.AddError("Failed to read S3 Tables maintenance configuration", err.Error())
|
||||
return
|
||||
}
|
||||
if current == nil {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
if err := r.setState(&state, current); err != nil {
|
||||
resp.Diagnostics.AddError("Invalid S3 Tables maintenance configuration returned by SeaweedFS", err.Error())
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(r.writeState(ctx, &resp.State, state)...)
|
||||
}
|
||||
|
||||
func (r *s3TableMaintenanceResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
plan, diags := r.modelFromData(ctx, req.Plan)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
value, err := r.value(plan)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid S3 Tables maintenance configuration", err.Error())
|
||||
return
|
||||
}
|
||||
lock := r.data.getBucketLock("tables:" + plan.TableBucketARN.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.put(ctx, plan, value); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to update S3 Tables maintenance configuration", err.Error())
|
||||
return
|
||||
}
|
||||
current, err := r.get(ctx, plan)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Failed to read updated S3 Tables maintenance configuration", err.Error())
|
||||
return
|
||||
}
|
||||
if current == nil {
|
||||
resp.Diagnostics.AddError("Missing S3 Tables maintenance configuration", "SeaweedFS did not return the configuration that was just updated.")
|
||||
return
|
||||
}
|
||||
if err := r.setState(&plan, current); err != nil {
|
||||
resp.Diagnostics.AddError("Invalid S3 Tables maintenance configuration returned by SeaweedFS", err.Error())
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(r.writeState(ctx, &resp.State, plan)...)
|
||||
}
|
||||
|
||||
func (r *s3TableMaintenanceResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
state, diags := r.modelFromData(ctx, req.State)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
lock := r.data.getBucketLock("tables:" + state.TableBucketARN.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.put(ctx, state, s3TableMaintenanceValue{Status: "disabled"}); err != nil && !isNoSuchS3TablesEntityError(err) {
|
||||
resp.Diagnostics.AddError("Failed to disable S3 Tables maintenance configuration", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (r *s3TableMaintenanceResource) modelFromData(ctx context.Context, data s3TableMaintenanceTerraformData) (s3TableMaintenanceResourceModel, diag.Diagnostics) {
|
||||
var model s3TableMaintenanceResourceModel
|
||||
var diags diag.Diagnostics
|
||||
diags.Append(data.GetAttribute(ctx, path.Root("id"), &model.ID)...)
|
||||
diags.Append(data.GetAttribute(ctx, path.Root("table_bucket_arn"), &model.TableBucketARN)...)
|
||||
diags.Append(data.GetAttribute(ctx, path.Root("type"), &model.Type)...)
|
||||
diags.Append(data.GetAttribute(ctx, path.Root("status"), &model.Status)...)
|
||||
|
||||
if r.table {
|
||||
diags.Append(data.GetAttribute(ctx, path.Root("namespace"), &model.Namespace)...)
|
||||
diags.Append(data.GetAttribute(ctx, path.Root("name"), &model.Name)...)
|
||||
diags.Append(data.GetAttribute(ctx, path.Root("strategy"), &model.Strategy)...)
|
||||
diags.Append(data.GetAttribute(ctx, path.Root("target_file_size_mb"), &model.TargetFileSizeMB)...)
|
||||
diags.Append(data.GetAttribute(ctx, path.Root("min_snapshots_to_keep"), &model.MinSnapshotsToKeep)...)
|
||||
diags.Append(data.GetAttribute(ctx, path.Root("max_snapshot_age_hours"), &model.MaxSnapshotAgeHours)...)
|
||||
} else {
|
||||
diags.Append(data.GetAttribute(ctx, path.Root("unreferenced_days"), &model.UnreferencedDays)...)
|
||||
diags.Append(data.GetAttribute(ctx, path.Root("non_current_days"), &model.NonCurrentDays)...)
|
||||
}
|
||||
return model, diags
|
||||
}
|
||||
|
||||
func (r *s3TableMaintenanceResource) writeState(ctx context.Context, state *tfsdk.State, model s3TableMaintenanceResourceModel) diag.Diagnostics {
|
||||
var diags diag.Diagnostics
|
||||
diags.Append(state.SetAttribute(ctx, path.Root("id"), model.ID)...)
|
||||
diags.Append(state.SetAttribute(ctx, path.Root("table_bucket_arn"), model.TableBucketARN)...)
|
||||
diags.Append(state.SetAttribute(ctx, path.Root("type"), model.Type)...)
|
||||
diags.Append(state.SetAttribute(ctx, path.Root("status"), model.Status)...)
|
||||
|
||||
if r.table {
|
||||
diags.Append(state.SetAttribute(ctx, path.Root("namespace"), model.Namespace)...)
|
||||
diags.Append(state.SetAttribute(ctx, path.Root("name"), model.Name)...)
|
||||
diags.Append(state.SetAttribute(ctx, path.Root("strategy"), model.Strategy)...)
|
||||
diags.Append(state.SetAttribute(ctx, path.Root("target_file_size_mb"), model.TargetFileSizeMB)...)
|
||||
diags.Append(state.SetAttribute(ctx, path.Root("min_snapshots_to_keep"), model.MinSnapshotsToKeep)...)
|
||||
diags.Append(state.SetAttribute(ctx, path.Root("max_snapshot_age_hours"), model.MaxSnapshotAgeHours)...)
|
||||
} else {
|
||||
diags.Append(state.SetAttribute(ctx, path.Root("unreferenced_days"), model.UnreferencedDays)...)
|
||||
diags.Append(state.SetAttribute(ctx, path.Root("non_current_days"), model.NonCurrentDays)...)
|
||||
}
|
||||
return diags
|
||||
}
|
||||
|
||||
func (r *s3TableMaintenanceResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
if !r.table {
|
||||
arn, err := parseTableBucketARN(req.ID)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid import ID", err.Error())
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), arn)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("table_bucket_arn"), arn)...)
|
||||
return
|
||||
}
|
||||
arn, namespace, name, maintenanceType, err := parseTableMaintenanceImportID(req.ID)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid import ID", err.Error())
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), req.ID)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("table_bucket_arn"), arn)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("namespace"), namespace)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), name)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("type"), maintenanceType)...)
|
||||
}
|
||||
|
||||
func (r *s3TableMaintenanceResource) get(ctx context.Context, model s3TableMaintenanceResourceModel) (*s3TableMaintenanceValue, error) {
|
||||
maintenanceType := r.maintenanceType(model)
|
||||
var configuration map[string]*s3TableMaintenanceValue
|
||||
var err error
|
||||
if r.table {
|
||||
configuration, err = r.client.GetS3TableMaintenanceConfiguration(ctx, model.TableBucketARN.ValueString(), model.Namespace.ValueString(), model.Name.ValueString())
|
||||
} else {
|
||||
configuration, err = r.client.GetS3TableBucketMaintenanceConfiguration(ctx, model.TableBucketARN.ValueString())
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return configuration[maintenanceType], nil
|
||||
}
|
||||
|
||||
func (r *s3TableMaintenanceResource) put(ctx context.Context, model s3TableMaintenanceResourceModel, value s3TableMaintenanceValue) error {
|
||||
if r.table {
|
||||
return r.client.PutS3TableMaintenanceConfiguration(ctx, model.TableBucketARN.ValueString(), model.Namespace.ValueString(), model.Name.ValueString(), r.maintenanceType(model), value)
|
||||
}
|
||||
return r.client.PutS3TableBucketMaintenanceConfiguration(ctx, model.TableBucketARN.ValueString(), value)
|
||||
}
|
||||
|
||||
func (r *s3TableMaintenanceResource) maintenanceType(model s3TableMaintenanceResourceModel) string {
|
||||
if !r.table {
|
||||
return s3TableMaintenanceUnreferencedFiles
|
||||
}
|
||||
return model.Type.ValueString()
|
||||
}
|
||||
|
||||
func (r *s3TableMaintenanceResource) value(model s3TableMaintenanceResourceModel) (s3TableMaintenanceValue, error) {
|
||||
status := model.Status.ValueString()
|
||||
if status != "enabled" && status != "disabled" {
|
||||
return s3TableMaintenanceValue{}, fmt.Errorf("status must be either enabled or disabled")
|
||||
}
|
||||
settings := &s3TableMaintenanceSettings{}
|
||||
hasSettings := false
|
||||
if r.table {
|
||||
switch model.Type.ValueString() {
|
||||
case s3TableMaintenanceCompaction:
|
||||
if !model.MinSnapshotsToKeep.IsNull() || !model.MaxSnapshotAgeHours.IsNull() {
|
||||
return s3TableMaintenanceValue{}, fmt.Errorf("snapshot management settings cannot be used with %s", model.Type.ValueString())
|
||||
}
|
||||
strategy := model.Strategy.ValueString()
|
||||
if strategy != "" && strategy != "auto" && strategy != "binpack" && strategy != "sort" {
|
||||
return s3TableMaintenanceValue{}, fmt.Errorf("strategy must be auto, binpack, or sort")
|
||||
}
|
||||
compaction := &s3TableCompactionSettings{Strategy: strategy}
|
||||
hasSettings = strategy != ""
|
||||
if !model.TargetFileSizeMB.IsNull() {
|
||||
compaction.TargetFileSizeMB = int64Pointer(model.TargetFileSizeMB.ValueInt64())
|
||||
hasSettings = true
|
||||
}
|
||||
if hasSettings {
|
||||
settings.IcebergCompaction = compaction
|
||||
}
|
||||
case s3TableMaintenanceSnapshotManagement:
|
||||
if !model.Strategy.IsNull() && model.Strategy.ValueString() != "" || !model.TargetFileSizeMB.IsNull() {
|
||||
return s3TableMaintenanceValue{}, fmt.Errorf("compaction settings cannot be used with %s", model.Type.ValueString())
|
||||
}
|
||||
snapshotManagement := &s3TableSnapshotManagementSettings{}
|
||||
if !model.MinSnapshotsToKeep.IsNull() {
|
||||
snapshotManagement.MinSnapshotsToKeep = int64Pointer(model.MinSnapshotsToKeep.ValueInt64())
|
||||
hasSettings = true
|
||||
}
|
||||
if !model.MaxSnapshotAgeHours.IsNull() {
|
||||
snapshotManagement.MaxSnapshotAgeHours = int64Pointer(model.MaxSnapshotAgeHours.ValueInt64())
|
||||
hasSettings = true
|
||||
}
|
||||
if hasSettings {
|
||||
settings.IcebergSnapshotManagement = snapshotManagement
|
||||
}
|
||||
default:
|
||||
return s3TableMaintenanceValue{}, fmt.Errorf("type must be %s or %s", s3TableMaintenanceCompaction, s3TableMaintenanceSnapshotManagement)
|
||||
}
|
||||
} else {
|
||||
if (!model.Strategy.IsNull() && model.Strategy.ValueString() != "") ||
|
||||
!model.TargetFileSizeMB.IsNull() || !model.MinSnapshotsToKeep.IsNull() || !model.MaxSnapshotAgeHours.IsNull() {
|
||||
return s3TableMaintenanceValue{}, fmt.Errorf("table maintenance settings cannot be used for bucket-level maintenance")
|
||||
}
|
||||
unreferencedFiles := &s3TableUnreferencedFileRemovalSettings{}
|
||||
if !model.UnreferencedDays.IsNull() {
|
||||
unreferencedFiles.UnreferencedDays = int64Pointer(model.UnreferencedDays.ValueInt64())
|
||||
hasSettings = true
|
||||
}
|
||||
if !model.NonCurrentDays.IsNull() {
|
||||
unreferencedFiles.NonCurrentDays = int64Pointer(model.NonCurrentDays.ValueInt64())
|
||||
hasSettings = true
|
||||
}
|
||||
if hasSettings {
|
||||
settings.IcebergUnreferencedFileRemoval = unreferencedFiles
|
||||
}
|
||||
}
|
||||
for _, field := range []struct {
|
||||
name string
|
||||
value *int64
|
||||
}{
|
||||
{"target_file_size_mb", maintenanceSettingValue(settings, "target_file_size_mb")},
|
||||
{"min_snapshots_to_keep", maintenanceSettingValue(settings, "min_snapshots_to_keep")},
|
||||
{"max_snapshot_age_hours", maintenanceSettingValue(settings, "max_snapshot_age_hours")},
|
||||
{"unreferenced_days", maintenanceSettingValue(settings, "unreferenced_days")},
|
||||
{"non_current_days", maintenanceSettingValue(settings, "non_current_days")},
|
||||
} {
|
||||
if field.value != nil && (*field.value < 1 || *field.value > 2147483647) {
|
||||
return s3TableMaintenanceValue{}, fmt.Errorf("%s must be between 1 and 2147483647", field.name)
|
||||
}
|
||||
}
|
||||
if !hasSettings {
|
||||
settings = nil
|
||||
}
|
||||
return s3TableMaintenanceValue{Status: status, Settings: settings}, nil
|
||||
}
|
||||
|
||||
func (r *s3TableMaintenanceResource) setState(state *s3TableMaintenanceResourceModel, value *s3TableMaintenanceValue) error {
|
||||
if value == nil || (value.Status != "enabled" && value.Status != "disabled") {
|
||||
return fmt.Errorf("configuration must include a valid status")
|
||||
}
|
||||
state.Type = types.StringValue(r.maintenanceType(*state))
|
||||
state.Status = types.StringValue(value.Status)
|
||||
state.Strategy = types.StringNull()
|
||||
state.TargetFileSizeMB = types.Int64Null()
|
||||
state.MinSnapshotsToKeep = types.Int64Null()
|
||||
state.MaxSnapshotAgeHours = types.Int64Null()
|
||||
state.UnreferencedDays = types.Int64Null()
|
||||
state.NonCurrentDays = types.Int64Null()
|
||||
if value.Settings == nil {
|
||||
state.ID = types.StringValue(r.resourceID(*state))
|
||||
return nil
|
||||
}
|
||||
switch state.Type.ValueString() {
|
||||
case s3TableMaintenanceCompaction:
|
||||
if value.Settings.IcebergSnapshotManagement != nil || value.Settings.IcebergUnreferencedFileRemoval != nil {
|
||||
return fmt.Errorf("settings do not match maintenance type %q", state.Type.ValueString())
|
||||
}
|
||||
if settings := value.Settings.IcebergCompaction; settings != nil {
|
||||
if settings.Strategy != "" {
|
||||
state.Strategy = types.StringValue(settings.Strategy)
|
||||
}
|
||||
if settings.TargetFileSizeMB != nil {
|
||||
state.TargetFileSizeMB = types.Int64Value(*settings.TargetFileSizeMB)
|
||||
}
|
||||
}
|
||||
case s3TableMaintenanceSnapshotManagement:
|
||||
if value.Settings.IcebergCompaction != nil || value.Settings.IcebergUnreferencedFileRemoval != nil {
|
||||
return fmt.Errorf("settings do not match maintenance type %q", state.Type.ValueString())
|
||||
}
|
||||
if settings := value.Settings.IcebergSnapshotManagement; settings != nil {
|
||||
if settings.MinSnapshotsToKeep != nil {
|
||||
state.MinSnapshotsToKeep = types.Int64Value(*settings.MinSnapshotsToKeep)
|
||||
}
|
||||
if settings.MaxSnapshotAgeHours != nil {
|
||||
state.MaxSnapshotAgeHours = types.Int64Value(*settings.MaxSnapshotAgeHours)
|
||||
}
|
||||
}
|
||||
case s3TableMaintenanceUnreferencedFiles:
|
||||
if value.Settings.IcebergCompaction != nil || value.Settings.IcebergSnapshotManagement != nil {
|
||||
return fmt.Errorf("settings do not match maintenance type %q", state.Type.ValueString())
|
||||
}
|
||||
if settings := value.Settings.IcebergUnreferencedFileRemoval; settings != nil {
|
||||
if settings.UnreferencedDays != nil {
|
||||
state.UnreferencedDays = types.Int64Value(*settings.UnreferencedDays)
|
||||
}
|
||||
if settings.NonCurrentDays != nil {
|
||||
state.NonCurrentDays = types.Int64Value(*settings.NonCurrentDays)
|
||||
}
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unsupported maintenance type %q", state.Type.ValueString())
|
||||
}
|
||||
state.ID = types.StringValue(r.resourceID(*state))
|
||||
return nil
|
||||
}
|
||||
|
||||
func maintenanceSettingValue(settings *s3TableMaintenanceSettings, name string) *int64 {
|
||||
switch name {
|
||||
case "target_file_size_mb":
|
||||
if settings.IcebergCompaction != nil {
|
||||
return settings.IcebergCompaction.TargetFileSizeMB
|
||||
}
|
||||
case "min_snapshots_to_keep":
|
||||
if settings.IcebergSnapshotManagement != nil {
|
||||
return settings.IcebergSnapshotManagement.MinSnapshotsToKeep
|
||||
}
|
||||
case "max_snapshot_age_hours":
|
||||
if settings.IcebergSnapshotManagement != nil {
|
||||
return settings.IcebergSnapshotManagement.MaxSnapshotAgeHours
|
||||
}
|
||||
case "unreferenced_days":
|
||||
if settings.IcebergUnreferencedFileRemoval != nil {
|
||||
return settings.IcebergUnreferencedFileRemoval.UnreferencedDays
|
||||
}
|
||||
case "non_current_days":
|
||||
if settings.IcebergUnreferencedFileRemoval != nil {
|
||||
return settings.IcebergUnreferencedFileRemoval.NonCurrentDays
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *s3TableMaintenanceResource) resourceID(model s3TableMaintenanceResourceModel) string {
|
||||
if !r.table {
|
||||
return model.TableBucketARN.ValueString()
|
||||
}
|
||||
return strings.Join([]string{
|
||||
model.TableBucketARN.ValueString(),
|
||||
model.Namespace.ValueString(),
|
||||
model.Name.ValueString(),
|
||||
model.Type.ValueString(),
|
||||
}, ",")
|
||||
}
|
||||
|
||||
func (r *s3TableMaintenanceResource) cleanupFailedCreate(ctx context.Context, model s3TableMaintenanceResourceModel, message string) string {
|
||||
if err := r.put(ctx, model, s3TableMaintenanceValue{Status: "disabled"}); err != nil && !isNoSuchS3TablesEntityError(err) {
|
||||
message += "; cleanup failed: " + err.Error()
|
||||
}
|
||||
return message
|
||||
}
|
||||
|
||||
func parseTableMaintenanceImportID(id string) (string, string, string, string, error) {
|
||||
parts := strings.SplitN(id, ",", 4)
|
||||
if len(parts) != 4 || parts[0] == "" || parts[1] == "" || parts[2] == "" || parts[3] == "" {
|
||||
return "", "", "", "", fmt.Errorf("expected import ID `table_bucket_arn,namespace,table_name,type`")
|
||||
}
|
||||
if _, err := parseTableBucketARN(parts[0]); err != nil {
|
||||
return "", "", "", "", err
|
||||
}
|
||||
if parts[3] != s3TableMaintenanceCompaction && parts[3] != s3TableMaintenanceSnapshotManagement {
|
||||
return "", "", "", "", fmt.Errorf("unsupported table maintenance type %q", parts[3])
|
||||
}
|
||||
return parts[0], parts[1], parts[2], parts[3], nil
|
||||
}
|
||||
|
||||
func int64Pointer(value int64) *int64 {
|
||||
return &value
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/diag"
|
||||
"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/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/tfsdk"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
)
|
||||
|
||||
type s3TablePolicyOperations struct {
|
||||
suffix string
|
||||
table bool
|
||||
}
|
||||
|
||||
type s3TablePolicyResource struct {
|
||||
client *iamClient
|
||||
data *providerData
|
||||
ops s3TablePolicyOperations
|
||||
}
|
||||
|
||||
type s3TablePolicyResourceModel struct {
|
||||
ID types.String
|
||||
TableBucketARN types.String
|
||||
Namespace types.String
|
||||
Name types.String
|
||||
Policy types.String
|
||||
}
|
||||
|
||||
type s3TablePolicyTerraformData interface {
|
||||
GetAttribute(context.Context, path.Path, interface{}) diag.Diagnostics
|
||||
}
|
||||
|
||||
var (
|
||||
_ resource.Resource = &s3TablePolicyResource{}
|
||||
_ resource.ResourceWithConfigure = &s3TablePolicyResource{}
|
||||
_ resource.ResourceWithImportState = &s3TablePolicyResource{}
|
||||
)
|
||||
|
||||
func NewS3TableBucketPolicyResource() resource.Resource {
|
||||
return &s3TablePolicyResource{ops: s3TablePolicyOperations{suffix: "table_bucket_policy"}}
|
||||
}
|
||||
|
||||
func NewS3TablePolicyResource() resource.Resource {
|
||||
return &s3TablePolicyResource{ops: s3TablePolicyOperations{suffix: "table_policy", table: true}}
|
||||
}
|
||||
|
||||
func (r *s3TablePolicyResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_" + r.ops.suffix
|
||||
}
|
||||
|
||||
func (r *s3TablePolicyResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
attributes := map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{Computed: true},
|
||||
"table_bucket_arn": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"policy": schema.StringAttribute{
|
||||
Required: true,
|
||||
Description: "JSON resource policy.",
|
||||
},
|
||||
}
|
||||
importDescription := "`table_bucket_arn`"
|
||||
if r.ops.table {
|
||||
attributes["namespace"] = schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
}
|
||||
attributes["name"] = schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
}
|
||||
importDescription = "`table_bucket_arn,namespace,table_name`"
|
||||
}
|
||||
resp.Schema = schema.Schema{
|
||||
Description: fmt.Sprintf("Manages a SeaweedFS S3 Tables %s policy. Import using %s.", strings.ReplaceAll(r.ops.suffix, "_", " "), importDescription),
|
||||
Attributes: attributes,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *s3TablePolicyResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
data, ok := req.ProviderData.(*providerData)
|
||||
if !ok {
|
||||
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
r.client = data.client
|
||||
r.data = data
|
||||
}
|
||||
|
||||
func (r *s3TablePolicyResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
plan, diags := r.modelFromData(ctx, req.Plan)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
policy, err := normalizeJSONString(plan.Policy.ValueString())
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid S3 Tables policy", err.Error())
|
||||
return
|
||||
}
|
||||
lock := r.data.getBucketLock("tables:" + plan.TableBucketARN.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.client.PutS3TablePolicy(ctx, plan.TableBucketARN.ValueString(), r.namespace(plan), r.name(plan), policy); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to create S3 Tables policy", err.Error())
|
||||
return
|
||||
}
|
||||
plan.Policy = types.StringValue(policy)
|
||||
plan.ID = r.resourceID(plan)
|
||||
resp.Diagnostics.Append(r.writeState(ctx, &resp.State, plan)...)
|
||||
}
|
||||
|
||||
func (r *s3TablePolicyResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
state, diags := r.modelFromData(ctx, req.State)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
lock := r.data.getBucketLock("tables:" + state.TableBucketARN.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
policy, err := r.client.GetS3TablePolicy(ctx, state.TableBucketARN.ValueString(), r.namespace(state), r.name(state))
|
||||
if err != nil {
|
||||
if isNoSuchS3TablesEntityError(err) {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.AddError("Failed to read S3 Tables policy", err.Error())
|
||||
return
|
||||
}
|
||||
normalized, err := normalizeJSONString(policy)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid S3 Tables policy returned by SeaweedFS", err.Error())
|
||||
return
|
||||
}
|
||||
state.ID = r.resourceID(state)
|
||||
if !policiesSemanticallyEqual(state.Policy.ValueString(), normalized) {
|
||||
state.Policy = types.StringValue(normalized)
|
||||
}
|
||||
resp.Diagnostics.Append(r.writeState(ctx, &resp.State, state)...)
|
||||
}
|
||||
|
||||
func (r *s3TablePolicyResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
plan, diags := r.modelFromData(ctx, req.Plan)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
policy, err := normalizeJSONString(plan.Policy.ValueString())
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid S3 Tables policy", err.Error())
|
||||
return
|
||||
}
|
||||
lock := r.data.getBucketLock("tables:" + plan.TableBucketARN.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.client.PutS3TablePolicy(ctx, plan.TableBucketARN.ValueString(), r.namespace(plan), r.name(plan), policy); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to update S3 Tables policy", err.Error())
|
||||
return
|
||||
}
|
||||
plan.Policy = types.StringValue(policy)
|
||||
plan.ID = r.resourceID(plan)
|
||||
resp.Diagnostics.Append(r.writeState(ctx, &resp.State, plan)...)
|
||||
}
|
||||
|
||||
func (r *s3TablePolicyResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
state, diags := r.modelFromData(ctx, req.State)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
lock := r.data.getBucketLock("tables:" + state.TableBucketARN.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.client.DeleteS3TablePolicy(ctx, state.TableBucketARN.ValueString(), r.namespace(state), r.name(state)); err != nil && !isNoSuchS3TablesEntityError(err) {
|
||||
resp.Diagnostics.AddError("Failed to delete S3 Tables policy", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (r *s3TablePolicyResource) modelFromData(ctx context.Context, data s3TablePolicyTerraformData) (s3TablePolicyResourceModel, diag.Diagnostics) {
|
||||
var model s3TablePolicyResourceModel
|
||||
var diags diag.Diagnostics
|
||||
diags.Append(data.GetAttribute(ctx, path.Root("id"), &model.ID)...)
|
||||
diags.Append(data.GetAttribute(ctx, path.Root("table_bucket_arn"), &model.TableBucketARN)...)
|
||||
diags.Append(data.GetAttribute(ctx, path.Root("policy"), &model.Policy)...)
|
||||
if r.ops.table {
|
||||
diags.Append(data.GetAttribute(ctx, path.Root("namespace"), &model.Namespace)...)
|
||||
diags.Append(data.GetAttribute(ctx, path.Root("name"), &model.Name)...)
|
||||
}
|
||||
return model, diags
|
||||
}
|
||||
|
||||
func (r *s3TablePolicyResource) writeState(ctx context.Context, state *tfsdk.State, model s3TablePolicyResourceModel) diag.Diagnostics {
|
||||
var diags diag.Diagnostics
|
||||
diags.Append(state.SetAttribute(ctx, path.Root("id"), model.ID)...)
|
||||
diags.Append(state.SetAttribute(ctx, path.Root("table_bucket_arn"), model.TableBucketARN)...)
|
||||
diags.Append(state.SetAttribute(ctx, path.Root("policy"), model.Policy)...)
|
||||
if r.ops.table {
|
||||
diags.Append(state.SetAttribute(ctx, path.Root("namespace"), model.Namespace)...)
|
||||
diags.Append(state.SetAttribute(ctx, path.Root("name"), model.Name)...)
|
||||
}
|
||||
return diags
|
||||
}
|
||||
|
||||
func (r *s3TablePolicyResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
if !r.ops.table {
|
||||
arn, err := parseTableBucketARN(req.ID)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid import ID", err.Error())
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), arn)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("table_bucket_arn"), arn)...)
|
||||
return
|
||||
}
|
||||
bucketARN, namespace, name, err := parseS3TableImportID(req.ID)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid import ID", err.Error())
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), req.ID)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("table_bucket_arn"), bucketARN)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("namespace"), namespace)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), name)...)
|
||||
}
|
||||
|
||||
func (r *s3TablePolicyResource) namespace(model s3TablePolicyResourceModel) string {
|
||||
if !r.ops.table {
|
||||
return ""
|
||||
}
|
||||
return model.Namespace.ValueString()
|
||||
}
|
||||
|
||||
func (r *s3TablePolicyResource) name(model s3TablePolicyResourceModel) string {
|
||||
if !r.ops.table {
|
||||
return ""
|
||||
}
|
||||
return model.Name.ValueString()
|
||||
}
|
||||
|
||||
func (r *s3TablePolicyResource) resourceID(model s3TablePolicyResourceModel) types.String {
|
||||
if !r.ops.table {
|
||||
return types.StringValue(model.TableBucketARN.ValueString())
|
||||
}
|
||||
return types.StringValue(model.TableBucketARN.ValueString() + "," + model.Namespace.ValueString() + "," + model.Name.ValueString())
|
||||
}
|
||||
@@ -0,0 +1,708 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/diag"
|
||||
"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/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
)
|
||||
|
||||
var (
|
||||
_ resource.Resource = &s3TableBucketResource{}
|
||||
_ resource.ResourceWithConfigure = &s3TableBucketResource{}
|
||||
_ resource.ResourceWithImportState = &s3TableBucketResource{}
|
||||
)
|
||||
|
||||
type s3TableBucketResource struct {
|
||||
client *iamClient
|
||||
data *providerData
|
||||
}
|
||||
|
||||
type s3TableBucketResourceModel struct {
|
||||
ID types.String `tfsdk:"id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
ARN types.String `tfsdk:"arn"`
|
||||
OwnerAccountID types.String `tfsdk:"owner_account_id"`
|
||||
CreatedAt types.String `tfsdk:"created_at"`
|
||||
Format types.String `tfsdk:"format"`
|
||||
Tags types.Map `tfsdk:"tags"`
|
||||
}
|
||||
|
||||
func NewS3TableBucketResource() resource.Resource {
|
||||
return &s3TableBucketResource{}
|
||||
}
|
||||
|
||||
func (r *s3TableBucketResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_table_bucket"
|
||||
}
|
||||
|
||||
func (r *s3TableBucketResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "Manages a SeaweedFS S3 Tables bucket. Import using its table bucket ARN.",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{Computed: true},
|
||||
"arn": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"owner_account_id": schema.StringAttribute{Computed: true},
|
||||
"created_at": schema.StringAttribute{Computed: true},
|
||||
"name": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Description: "Table bucket name.",
|
||||
},
|
||||
"format": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Description: "Table format served by the bucket, such as ICEBERG.",
|
||||
},
|
||||
"tags": schema.MapAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
ElementType: types.StringType,
|
||||
Description: "Tags applied to the table bucket.",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *s3TableBucketResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
data, ok := req.ProviderData.(*providerData)
|
||||
if !ok {
|
||||
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
r.client = data.client
|
||||
r.data = data
|
||||
}
|
||||
|
||||
func (r *s3TableBucketResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
var plan s3TableBucketResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tags, diags := stringMapFromTerraformMap(ctx, plan.Tags)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
lock := r.data.getBucketLock("tables:" + plan.Name.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
arn, err := r.client.CreateS3TableBucket(ctx, plan.Name.ValueString(), plan.Format.ValueString(), tags)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Failed to create S3 table bucket", err.Error())
|
||||
return
|
||||
}
|
||||
if arn == "" {
|
||||
resp.Diagnostics.AddError("Invalid S3 table bucket response", "SeaweedFS did not return the created table bucket ARN.")
|
||||
return
|
||||
}
|
||||
bucket, err := r.client.GetS3TableBucket(ctx, arn)
|
||||
if err != nil {
|
||||
message := err.Error()
|
||||
if cleanupErr := r.client.DeleteS3TableBucket(ctx, arn); cleanupErr != nil && !isNoSuchS3TablesEntityError(cleanupErr) {
|
||||
message += "; cleanup failed: " + cleanupErr.Error()
|
||||
}
|
||||
resp.Diagnostics.AddError("Failed to read created S3 table bucket", message)
|
||||
return
|
||||
}
|
||||
r.setState(ctx, &plan, bucket, &resp.Diagnostics)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *s3TableBucketResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
var state s3TableBucketResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
arn := state.ARN.ValueString()
|
||||
if arn == "" {
|
||||
arn = state.ID.ValueString()
|
||||
}
|
||||
lock := r.data.getBucketLock("tables:" + arn)
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
bucket, err := r.client.GetS3TableBucket(ctx, arn)
|
||||
if err != nil {
|
||||
if isNoSuchS3TablesEntityError(err) {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.AddError("Failed to read S3 table bucket", err.Error())
|
||||
return
|
||||
}
|
||||
r.setState(ctx, &state, bucket, &resp.Diagnostics)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *s3TableBucketResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
var plan s3TableBucketResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
var state s3TableBucketResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
arn := plan.ARN.ValueString()
|
||||
if plan.ARN.IsUnknown() || arn == "" {
|
||||
arn = state.ARN.ValueString()
|
||||
if arn == "" {
|
||||
arn = state.ID.ValueString()
|
||||
}
|
||||
}
|
||||
if arn == "" {
|
||||
resp.Diagnostics.AddError("Missing S3 table bucket ARN", "Terraform state and plan do not contain the table bucket ARN.")
|
||||
return
|
||||
}
|
||||
tags, diags := stringMapFromTerraformMap(ctx, plan.Tags)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
lock := r.data.getBucketLock("tables:" + arn)
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.client.SetS3TableTags(ctx, arn, tags); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to update S3 table bucket tags", err.Error())
|
||||
return
|
||||
}
|
||||
bucket, err := r.client.GetS3TableBucket(ctx, arn)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Failed to read updated S3 table bucket", err.Error())
|
||||
return
|
||||
}
|
||||
r.setState(ctx, &plan, bucket, &resp.Diagnostics)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *s3TableBucketResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
var state s3TableBucketResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
arn := state.ARN.ValueString()
|
||||
if arn == "" {
|
||||
arn = state.ID.ValueString()
|
||||
}
|
||||
lock := r.data.getBucketLock("tables:" + arn)
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.client.DeleteS3TableBucket(ctx, arn); err != nil && !isNoSuchS3TablesEntityError(err) {
|
||||
resp.Diagnostics.AddError("Failed to delete S3 table bucket", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (r *s3TableBucketResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
arn, err := parseTableBucketARN(req.ID)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid import ID", err.Error())
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), arn)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("arn"), arn)...)
|
||||
}
|
||||
|
||||
func (r *s3TableBucketResource) setState(ctx context.Context, state *s3TableBucketResourceModel, bucket s3TableBucket, diags *diag.Diagnostics) {
|
||||
state.ID = types.StringValue(bucket.ARN)
|
||||
state.ARN = types.StringValue(bucket.ARN)
|
||||
state.Name = types.StringValue(bucket.Name)
|
||||
state.OwnerAccountID = types.StringValue(bucket.OwnerAccountID)
|
||||
state.CreatedAt = types.StringValue(bucket.CreatedAt.UTC().Format(time.RFC3339))
|
||||
state.Format = types.StringValue(bucket.Format)
|
||||
tags, tagsDiags := terraformMapFromStringMap(ctx, bucket.Tags)
|
||||
diags.Append(tagsDiags...)
|
||||
state.Tags = tags
|
||||
}
|
||||
|
||||
var (
|
||||
_ resource.Resource = &s3TableNamespaceResource{}
|
||||
_ resource.ResourceWithConfigure = &s3TableNamespaceResource{}
|
||||
_ resource.ResourceWithImportState = &s3TableNamespaceResource{}
|
||||
)
|
||||
|
||||
type s3TableNamespaceResource struct {
|
||||
client *iamClient
|
||||
data *providerData
|
||||
}
|
||||
|
||||
type s3TableNamespaceResourceModel struct {
|
||||
ID types.String `tfsdk:"id"`
|
||||
TableBucketARN types.String `tfsdk:"table_bucket_arn"`
|
||||
Namespace types.String `tfsdk:"namespace"`
|
||||
OwnerAccountID types.String `tfsdk:"owner_account_id"`
|
||||
CreatedAt types.String `tfsdk:"created_at"`
|
||||
}
|
||||
|
||||
func NewS3TableNamespaceResource() resource.Resource {
|
||||
return &s3TableNamespaceResource{}
|
||||
}
|
||||
|
||||
func (r *s3TableNamespaceResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_table_namespace"
|
||||
}
|
||||
|
||||
func (r *s3TableNamespaceResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "Manages a namespace in a SeaweedFS S3 Tables bucket. Use a dot-separated path for nested namespaces. Import using `table_bucket_arn,namespace`.",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{Computed: true},
|
||||
"owner_account_id": schema.StringAttribute{Computed: true},
|
||||
"created_at": schema.StringAttribute{Computed: true},
|
||||
"table_bucket_arn": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"namespace": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Description: "Namespace name or dot-separated namespace path.",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *s3TableNamespaceResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
data, ok := req.ProviderData.(*providerData)
|
||||
if !ok {
|
||||
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
r.client = data.client
|
||||
r.data = data
|
||||
}
|
||||
|
||||
func (r *s3TableNamespaceResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
var plan s3TableNamespaceResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
lock := r.data.getBucketLock("tables:" + plan.TableBucketARN.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.client.CreateS3TableNamespace(ctx, plan.TableBucketARN.ValueString(), plan.Namespace.ValueString()); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to create S3 table namespace", err.Error())
|
||||
return
|
||||
}
|
||||
namespace, err := r.client.GetS3TableNamespace(ctx, plan.TableBucketARN.ValueString(), plan.Namespace.ValueString())
|
||||
if err != nil {
|
||||
message := err.Error()
|
||||
if cleanupErr := r.client.DeleteS3TableNamespace(ctx, plan.TableBucketARN.ValueString(), plan.Namespace.ValueString()); cleanupErr != nil && !isNoSuchS3TablesEntityError(cleanupErr) {
|
||||
message += "; cleanup failed: " + cleanupErr.Error()
|
||||
}
|
||||
resp.Diagnostics.AddError("Failed to read created S3 table namespace", message)
|
||||
return
|
||||
}
|
||||
r.setState(&plan, namespace)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *s3TableNamespaceResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
var state s3TableNamespaceResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
lock := r.data.getBucketLock("tables:" + state.TableBucketARN.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
namespace, err := r.client.GetS3TableNamespace(ctx, state.TableBucketARN.ValueString(), state.Namespace.ValueString())
|
||||
if err != nil {
|
||||
if isNoSuchS3TablesEntityError(err) {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.AddError("Failed to read S3 table namespace", err.Error())
|
||||
return
|
||||
}
|
||||
r.setState(&state, namespace)
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *s3TableNamespaceResource) Update(_ context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
resp.Diagnostics.AddError("Unsupported S3 table namespace update", "Changing a namespace name requires replacing it.")
|
||||
}
|
||||
|
||||
func (r *s3TableNamespaceResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
var state s3TableNamespaceResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
lock := r.data.getBucketLock("tables:" + state.TableBucketARN.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.client.DeleteS3TableNamespace(ctx, state.TableBucketARN.ValueString(), state.Namespace.ValueString()); err != nil && !isNoSuchS3TablesEntityError(err) {
|
||||
resp.Diagnostics.AddError("Failed to delete S3 table namespace", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (r *s3TableNamespaceResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
bucketARN, namespace, err := parseTableNamespaceImportID(req.ID)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid import ID", err.Error())
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), req.ID)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("table_bucket_arn"), bucketARN)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("namespace"), namespace)...)
|
||||
}
|
||||
|
||||
func (r *s3TableNamespaceResource) setState(state *s3TableNamespaceResourceModel, namespace s3TableNamespace) {
|
||||
name := strings.Join(namespace.Namespace, ".")
|
||||
state.ID = types.StringValue(state.TableBucketARN.ValueString() + "," + name)
|
||||
state.Namespace = types.StringValue(name)
|
||||
state.OwnerAccountID = types.StringValue(namespace.OwnerAccountID)
|
||||
state.CreatedAt = types.StringValue(namespace.CreatedAt.UTC().Format(time.RFC3339))
|
||||
}
|
||||
|
||||
var (
|
||||
_ resource.Resource = &s3TableResource{}
|
||||
_ resource.ResourceWithConfigure = &s3TableResource{}
|
||||
_ resource.ResourceWithImportState = &s3TableResource{}
|
||||
)
|
||||
|
||||
type s3TableResource struct {
|
||||
client *iamClient
|
||||
data *providerData
|
||||
}
|
||||
|
||||
type s3TableResourceModel struct {
|
||||
ID types.String `tfsdk:"id"`
|
||||
TableBucketARN types.String `tfsdk:"table_bucket_arn"`
|
||||
Namespace types.String `tfsdk:"namespace"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Format types.String `tfsdk:"format"`
|
||||
Metadata types.String `tfsdk:"metadata"`
|
||||
TableARN types.String `tfsdk:"table_arn"`
|
||||
VersionToken types.String `tfsdk:"version_token"`
|
||||
MetadataLocation types.String `tfsdk:"metadata_location"`
|
||||
CreatedAt types.String `tfsdk:"created_at"`
|
||||
ModifiedAt types.String `tfsdk:"modified_at"`
|
||||
Tags types.Map `tfsdk:"tags"`
|
||||
}
|
||||
|
||||
func NewS3TableResource() resource.Resource {
|
||||
return &s3TableResource{}
|
||||
}
|
||||
|
||||
func (r *s3TableResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_table"
|
||||
}
|
||||
|
||||
func (r *s3TableResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "Manages an Iceberg table in a SeaweedFS S3 Tables namespace. Table schema metadata is JSON encoded. Import using `table_bucket_arn,namespace,table_name`.",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{Computed: true},
|
||||
"table_arn": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"version_token": schema.StringAttribute{Computed: true},
|
||||
"metadata_location": schema.StringAttribute{Computed: true},
|
||||
"created_at": schema.StringAttribute{Computed: true},
|
||||
"modified_at": schema.StringAttribute{Computed: true},
|
||||
"table_bucket_arn": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"namespace": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"format": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Description: "Table format, typically ICEBERG.",
|
||||
},
|
||||
"metadata": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Description: "Optional JSON encoded table metadata, including Iceberg schema fields.",
|
||||
},
|
||||
"tags": schema.MapAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
ElementType: types.StringType,
|
||||
Description: "Tags applied to the table.",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *s3TableResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
data, ok := req.ProviderData.(*providerData)
|
||||
if !ok {
|
||||
resp.Diagnostics.AddError("Unexpected provider data type", fmt.Sprintf("Expected *providerData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
r.client = data.client
|
||||
r.data = data
|
||||
}
|
||||
|
||||
func (r *s3TableResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
||||
var plan s3TableResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
var metadata json.RawMessage
|
||||
if !plan.Metadata.IsNull() && !plan.Metadata.IsUnknown() && plan.Metadata.ValueString() != "" {
|
||||
if !json.Valid([]byte(plan.Metadata.ValueString())) {
|
||||
resp.Diagnostics.AddError("Invalid table metadata", "metadata must contain valid JSON.")
|
||||
return
|
||||
}
|
||||
metadata = json.RawMessage(plan.Metadata.ValueString())
|
||||
}
|
||||
tags, tagDiags := stringMapFromTerraformMap(ctx, plan.Tags)
|
||||
resp.Diagnostics.Append(tagDiags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
lock := r.data.getBucketLock("tables:" + plan.TableBucketARN.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
created, err := r.client.CreateS3Table(ctx, plan.TableBucketARN.ValueString(), plan.Namespace.ValueString(), plan.Name.ValueString(), plan.Format.ValueString(), metadata, tags)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Failed to create S3 table", err.Error())
|
||||
return
|
||||
}
|
||||
table, err := r.client.GetS3Table(ctx, plan.TableBucketARN.ValueString(), plan.Namespace.ValueString(), plan.Name.ValueString())
|
||||
if err != nil {
|
||||
message := err.Error()
|
||||
if cleanupErr := r.client.DeleteS3Table(ctx, plan.TableBucketARN.ValueString(), plan.Namespace.ValueString(), plan.Name.ValueString(), created.VersionToken); cleanupErr != nil && !isNoSuchS3TablesEntityError(cleanupErr) {
|
||||
message += "; cleanup failed: " + cleanupErr.Error()
|
||||
}
|
||||
resp.Diagnostics.AddError("Failed to read created S3 table", message)
|
||||
return
|
||||
}
|
||||
r.setState(ctx, &plan, table, &resp.Diagnostics)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *s3TableResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
||||
var state s3TableResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
lock := r.data.getBucketLock("tables:" + state.TableBucketARN.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
table, err := r.client.GetS3Table(ctx, state.TableBucketARN.ValueString(), state.Namespace.ValueString(), state.Name.ValueString())
|
||||
if err != nil {
|
||||
if isNoSuchS3TablesEntityError(err) {
|
||||
resp.State.RemoveResource(ctx)
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.AddError("Failed to read S3 table", err.Error())
|
||||
return
|
||||
}
|
||||
r.setState(ctx, &state, table, &resp.Diagnostics)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
|
||||
func (r *s3TableResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
||||
var plan s3TableResourceModel
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||
var state s3TableResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tableARN := plan.TableARN.ValueString()
|
||||
if plan.TableARN.IsUnknown() || tableARN == "" {
|
||||
tableARN = state.TableARN.ValueString()
|
||||
if tableARN == "" {
|
||||
tableARN = state.ID.ValueString()
|
||||
}
|
||||
}
|
||||
tableBucketARN := plan.TableBucketARN.ValueString()
|
||||
if plan.TableBucketARN.IsUnknown() || tableBucketARN == "" {
|
||||
tableBucketARN = state.TableBucketARN.ValueString()
|
||||
}
|
||||
if tableARN == "" || tableBucketARN == "" {
|
||||
resp.Diagnostics.AddError("Missing S3 table ARN", "Terraform state and plan do not contain the table and table bucket ARNs.")
|
||||
return
|
||||
}
|
||||
tags, tagDiags := stringMapFromTerraformMap(ctx, plan.Tags)
|
||||
resp.Diagnostics.Append(tagDiags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
lock := r.data.getBucketLock("tables:" + tableBucketARN)
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.client.SetS3TableTags(ctx, tableARN, tags); err != nil {
|
||||
resp.Diagnostics.AddError("Failed to update S3 table tags", err.Error())
|
||||
return
|
||||
}
|
||||
table, err := r.client.GetS3Table(ctx, tableBucketARN, plan.Namespace.ValueString(), plan.Name.ValueString())
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Failed to read updated S3 table", err.Error())
|
||||
return
|
||||
}
|
||||
r.setState(ctx, &plan, table, &resp.Diagnostics)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
|
||||
}
|
||||
|
||||
func (r *s3TableResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
||||
var state s3TableResourceModel
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
lock := r.data.getBucketLock("tables:" + state.TableBucketARN.ValueString())
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
if err := r.client.DeleteS3Table(ctx, state.TableBucketARN.ValueString(), state.Namespace.ValueString(), state.Name.ValueString(), state.VersionToken.ValueString()); err != nil && !isNoSuchS3TablesEntityError(err) {
|
||||
resp.Diagnostics.AddError("Failed to delete S3 table", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (r *s3TableResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
bucketARN, namespace, name, err := parseS3TableImportID(req.ID)
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Invalid import ID", err.Error())
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), req.ID)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("table_bucket_arn"), bucketARN)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("namespace"), namespace)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), name)...)
|
||||
}
|
||||
|
||||
func (r *s3TableResource) setState(ctx context.Context, state *s3TableResourceModel, table s3Table, diags *diag.Diagnostics) {
|
||||
state.ID = types.StringValue(table.TableARN)
|
||||
state.TableARN = types.StringValue(table.TableARN)
|
||||
state.Name = types.StringValue(table.Name)
|
||||
state.Namespace = types.StringValue(strings.Join(table.Namespace, "."))
|
||||
state.Format = types.StringValue(table.Format)
|
||||
state.VersionToken = types.StringValue(table.VersionToken)
|
||||
state.MetadataLocation = types.StringValue(table.MetadataLocation)
|
||||
state.CreatedAt = types.StringValue(table.CreatedAt.UTC().Format(time.RFC3339))
|
||||
state.ModifiedAt = types.StringValue(table.ModifiedAt.UTC().Format(time.RFC3339))
|
||||
tags, tagsDiags := terraformMapFromStringMap(ctx, table.Tags)
|
||||
diags.Append(tagsDiags...)
|
||||
state.Tags = tags
|
||||
if len(table.Metadata) == 0 || string(table.Metadata) == "null" {
|
||||
state.Metadata = types.StringNull()
|
||||
return
|
||||
}
|
||||
normalized, err := normalizeJSONString(string(table.Metadata))
|
||||
if err != nil {
|
||||
diags.AddError("Invalid table metadata returned by SeaweedFS", err.Error())
|
||||
return
|
||||
}
|
||||
state.Metadata = types.StringValue(normalized)
|
||||
}
|
||||
|
||||
func parseTableBucketARN(arn string) (string, error) {
|
||||
if !strings.HasPrefix(arn, "arn:") || strings.TrimSpace(arn) != arn || !strings.Contains(arn, ":bucket/") {
|
||||
return "", fmt.Errorf("expected a table bucket ARN")
|
||||
}
|
||||
return arn, nil
|
||||
}
|
||||
|
||||
func parseTableNamespaceImportID(id string) (string, string, error) {
|
||||
parts := strings.SplitN(id, ",", 2)
|
||||
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
||||
return "", "", fmt.Errorf("expected import ID `table_bucket_arn,namespace`")
|
||||
}
|
||||
if _, err := parseTableBucketARN(parts[0]); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return parts[0], parts[1], nil
|
||||
}
|
||||
|
||||
func parseS3TableImportID(id string) (string, string, string, error) {
|
||||
parts := strings.SplitN(id, ",", 3)
|
||||
if len(parts) != 3 || parts[0] == "" || parts[1] == "" || parts[2] == "" {
|
||||
return "", "", "", fmt.Errorf("expected import ID `table_bucket_arn,namespace,table_name`")
|
||||
}
|
||||
if _, err := parseTableBucketARN(parts[0]); err != nil {
|
||||
return "", "", "", err
|
||||
}
|
||||
return parts[0], parts[1], parts[2], nil
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package seaweedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/diag"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
)
|
||||
|
||||
func TestS3TableMaintenanceClientRequests(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const bucketARN = "arn:aws:s3tables:us-east-1:123456789012:bucket/lake"
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||
if got := req.Header.Get("Authorization"); got == "" {
|
||||
t.Error("request has no SigV4 authorization")
|
||||
}
|
||||
switch req.URL.Path {
|
||||
case "/buckets/" + bucketARN + "/maintenance/icebergUnreferencedFileRemoval":
|
||||
if req.Method != http.MethodPut {
|
||||
t.Errorf("bucket maintenance method = %s, want PUT", req.Method)
|
||||
}
|
||||
var body struct {
|
||||
Value s3TableMaintenanceValue `json:"value"`
|
||||
}
|
||||
if err := json.NewDecoder(req.Body).Decode(&body); err != nil {
|
||||
t.Errorf("decode bucket maintenance body: %v", err)
|
||||
}
|
||||
if body.Value.Status != "enabled" || body.Value.Settings == nil ||
|
||||
body.Value.Settings.IcebergUnreferencedFileRemoval == nil ||
|
||||
body.Value.Settings.IcebergUnreferencedFileRemoval.UnreferencedDays == nil ||
|
||||
*body.Value.Settings.IcebergUnreferencedFileRemoval.UnreferencedDays != 30 {
|
||||
t.Errorf("unexpected bucket maintenance body: %#v", body)
|
||||
}
|
||||
case "/buckets/" + bucketARN + "/maintenance":
|
||||
if req.Method != http.MethodGet {
|
||||
t.Errorf("bucket maintenance method = %s, want GET", req.Method)
|
||||
}
|
||||
_, _ = fmt.Fprint(w, `{"configuration":{"icebergUnreferencedFileRemoval":{"status":"enabled","settings":{"icebergUnreferencedFileRemoval":{"unreferencedDays":30}}}}}`)
|
||||
case "/tables/" + bucketARN + "/sales/orders/maintenance/icebergCompaction":
|
||||
if req.Method != http.MethodPut {
|
||||
t.Errorf("table maintenance method = %s, want PUT", req.Method)
|
||||
}
|
||||
var body struct {
|
||||
Value s3TableMaintenanceValue `json:"value"`
|
||||
}
|
||||
if err := json.NewDecoder(req.Body).Decode(&body); err != nil {
|
||||
t.Errorf("decode table maintenance body: %v", err)
|
||||
}
|
||||
settings := body.Value.Settings
|
||||
if body.Value.Status != "enabled" || settings == nil || settings.IcebergCompaction == nil ||
|
||||
settings.IcebergCompaction.Strategy != "sort" ||
|
||||
settings.IcebergCompaction.TargetFileSizeMB == nil ||
|
||||
*settings.IcebergCompaction.TargetFileSizeMB != 512 {
|
||||
t.Errorf("unexpected table maintenance body: %#v", body)
|
||||
}
|
||||
case "/tables/" + bucketARN + "/sales/orders/maintenance":
|
||||
if req.Method != http.MethodGet {
|
||||
t.Errorf("table maintenance method = %s, want GET", req.Method)
|
||||
}
|
||||
_, _ = fmt.Fprint(w, `{"configuration":{"icebergCompaction":{"status":"enabled","settings":{"icebergCompaction":{"strategy":"sort","targetFileSizeMB":512}}}}}`)
|
||||
default:
|
||||
t.Errorf("unexpected request: %s %s", req.Method, req.URL.Path)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client, err := newIAMClient(iamClientConfig{
|
||||
Endpoint: server.URL,
|
||||
Region: "us-east-1",
|
||||
AccessKey: "test-key",
|
||||
SecretKey: "test-secret",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("new client: %v", err)
|
||||
}
|
||||
days := int64(30)
|
||||
bucketValue := s3TableMaintenanceValue{
|
||||
Status: "enabled",
|
||||
Settings: &s3TableMaintenanceSettings{
|
||||
IcebergUnreferencedFileRemoval: &s3TableUnreferencedFileRemovalSettings{UnreferencedDays: &days},
|
||||
},
|
||||
}
|
||||
if err := client.PutS3TableBucketMaintenanceConfiguration(context.Background(), bucketARN, bucketValue); err != nil {
|
||||
t.Fatalf("put bucket maintenance configuration: %v", err)
|
||||
}
|
||||
bucketConfiguration, err := client.GetS3TableBucketMaintenanceConfiguration(context.Background(), bucketARN)
|
||||
if err != nil {
|
||||
t.Fatalf("get bucket maintenance configuration: %v", err)
|
||||
}
|
||||
if bucketConfiguration[s3TableMaintenanceUnreferencedFiles].Settings.IcebergUnreferencedFileRemoval.UnreferencedDays == nil {
|
||||
t.Fatal("bucket maintenance configuration was not decoded")
|
||||
}
|
||||
|
||||
targetSize := int64(512)
|
||||
tableValue := s3TableMaintenanceValue{
|
||||
Status: "enabled",
|
||||
Settings: &s3TableMaintenanceSettings{
|
||||
IcebergCompaction: &s3TableCompactionSettings{Strategy: "sort", TargetFileSizeMB: &targetSize},
|
||||
},
|
||||
}
|
||||
if err := client.PutS3TableMaintenanceConfiguration(context.Background(), bucketARN, "sales", "orders", s3TableMaintenanceCompaction, tableValue); err != nil {
|
||||
t.Fatalf("put table maintenance configuration: %v", err)
|
||||
}
|
||||
tableConfiguration, err := client.GetS3TableMaintenanceConfiguration(context.Background(), bucketARN, "sales", "orders")
|
||||
if err != nil {
|
||||
t.Fatalf("get table maintenance configuration: %v", err)
|
||||
}
|
||||
if got := tableConfiguration[s3TableMaintenanceCompaction].Settings.IcebergCompaction.Strategy; got != "sort" {
|
||||
t.Fatalf("compaction strategy = %q, want sort", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestS3TableMaintenanceResourceValue(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
targetSize := types.Int64Value(512)
|
||||
compaction := s3TableMaintenanceResource{table: true}
|
||||
value, err := compaction.value(s3TableMaintenanceResourceModel{
|
||||
Type: types.StringValue(s3TableMaintenanceCompaction),
|
||||
Status: types.StringValue("enabled"),
|
||||
Strategy: types.StringValue("sort"),
|
||||
TargetFileSizeMB: targetSize,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("valid compaction configuration: %v", err)
|
||||
}
|
||||
if value.Settings.IcebergCompaction == nil || value.Settings.IcebergCompaction.TargetFileSizeMB == nil {
|
||||
t.Fatalf("compaction settings not populated: %#v", value)
|
||||
}
|
||||
|
||||
_, err = compaction.value(s3TableMaintenanceResourceModel{
|
||||
Type: types.StringValue(s3TableMaintenanceCompaction),
|
||||
Status: types.StringValue("enabled"),
|
||||
MinSnapshotsToKeep: types.Int64Value(3),
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected mixed maintenance settings to be rejected")
|
||||
}
|
||||
_, err = compaction.value(s3TableMaintenanceResourceModel{
|
||||
Type: types.StringValue(s3TableMaintenanceCompaction),
|
||||
Status: types.StringValue("enabled"),
|
||||
Strategy: types.StringValue("z-order"),
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected unsupported compaction strategy to be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTableMaintenanceImportID(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const arn = "arn:aws:s3tables:us-east-1:123456789012:bucket/lake"
|
||||
gotARN, namespace, name, maintenanceType, err := parseTableMaintenanceImportID(
|
||||
arn + ",sales.daily,orders," + s3TableMaintenanceCompaction,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("parse maintenance import ID: %v", err)
|
||||
}
|
||||
if gotARN != arn || namespace != "sales.daily" || name != "orders" || maintenanceType != s3TableMaintenanceCompaction {
|
||||
t.Fatalf("parsed import ID = %q, %q, %q, %q", gotARN, namespace, name, maintenanceType)
|
||||
}
|
||||
if _, _, _, _, err := parseTableMaintenanceImportID(arn + ",sales,orders,unknown"); err == nil {
|
||||
t.Fatal("expected unsupported maintenance type to be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestS3TableSetStateRestoresImportedRequiredAttributes(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const bucketARN = "arn:aws:s3tables:us-east-1:123456789012:bucket/lake"
|
||||
state := &s3TableResourceModel{TableBucketARN: types.StringValue(bucketARN)}
|
||||
var diagnostics diag.Diagnostics
|
||||
resource := &s3TableResource{}
|
||||
resource.setState(context.Background(), state, s3Table{
|
||||
Name: "orders",
|
||||
TableARN: bucketARN + "/table/sales/orders",
|
||||
Namespace: []string{"sales", "daily"},
|
||||
Format: "ICEBERG",
|
||||
}, &diagnostics)
|
||||
if diagnostics.HasError() {
|
||||
t.Fatalf("set table state diagnostics: %v", diagnostics)
|
||||
}
|
||||
if state.Name.ValueString() != "orders" ||
|
||||
state.Namespace.ValueString() != "sales.daily" ||
|
||||
state.Format.ValueString() != "ICEBERG" {
|
||||
t.Fatalf("required imported attributes were not restored: %#v", state)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
master:
|
||||
enabled: false
|
||||
volume:
|
||||
enabled: false
|
||||
filer:
|
||||
enabled: false
|
||||
s3:
|
||||
credentials:
|
||||
admin:
|
||||
accessKey: terraform-admin
|
||||
secretKey: terraform-admin-secret-key-000000000001
|
||||
read:
|
||||
accessKey: terraform-read
|
||||
secretKey: terraform-read-secret-key-000000000001
|
||||
allInOne:
|
||||
enabled: true
|
||||
extraArgs:
|
||||
- "-s3.iam.readOnly=false"
|
||||
- "-s3.iam.config=/etc/seaweedfs/iam/iam-config.json"
|
||||
extraVolumes: |
|
||||
- name: iam-config
|
||||
secret:
|
||||
secretName: seaweedfs-iam-config
|
||||
extraVolumeMounts: |
|
||||
- name: iam-config
|
||||
mountPath: /etc/seaweedfs/iam
|
||||
readOnly: true
|
||||
s3:
|
||||
enabled: true
|
||||
enableAuth: true
|
||||
port: 8333
|
||||
data:
|
||||
type: emptyDir
|
||||
size: 10Gi
|
||||
Reference in new issue
Block a user