Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cyclops-sdk): clear dropped optional pool and template fields on update (#7889)

ddupont4a0b1d24f8a9
diff --git a/libs/fleet/sdk/src/pools.rs b/libs/fleet/sdk/src/pools.rs
index eaef342c7a..eb58d93502 100644
--- a/libs/fleet/sdk/src/pools.rs
+++ b/libs/fleet/sdk/src/pools.rs
@@ -229,12 +229,27 @@ fn json_request(method: &str, url: Url, body: Option<Vec<u8>>) -> HttpRequest {
}
}
+/// A merge patch keeps every key it leaves out, so an optional field the
+/// desired spec drops has to be written as an explicit null to be cleared
+/// (Terraform removing `idle_ttl_seconds`, say). `get_pool` returns every
+/// field, so get-modify-update callers keep what they did not touch.
fn pool_merge_patch_json(pool: &Pool) -> Result<Vec<u8>, SdkError> {
let mut value = serde_json::to_value(pool).map_err(|error| SdkError::Body {
reason: error.to_string(),
})?;
- if pool.spec.autoscaling.is_none() {
- value["spec"]["autoscaling"] = serde_json::Value::Null;
+ let spec = &pool.spec;
+ for (key, absent) in [
+ ("autoscaling", spec.autoscaling.is_none()),
+ (
+ "ttlSecondsAfterCreated",
+ spec.ttl_seconds_after_created.is_none(),
+ ),
+ ("idleTtlSeconds", spec.idle_ttl_seconds.is_none()),
+ ("ttlPolicy", spec.ttl_policy.is_none()),
+ ] {
+ if absent {
+ value["spec"][key] = serde_json::Value::Null;
+ }
}
to_json(&value)
}
diff --git a/libs/fleet/sdk/src/templates.rs b/libs/fleet/sdk/src/templates.rs
index 35ffb06517..b2de05565c 100644
--- a/libs/fleet/sdk/src/templates.rs
+++ b/libs/fleet/sdk/src/templates.rs
@@ -143,8 +143,19 @@ fn template_merge_patch_json(template: &Template) -> Result<Vec<u8>, SdkError> {
let mut value = serde_json::to_value(template).map_err(|error| SdkError::Body {
reason: error.to_string(),
})?;
- if template.spec.vm_template.image_pull_secret.is_none() {
- value["spec"]["vmTemplate"]["imagePullSecret"] = serde_json::Value::Null;
+ // The same explicit null clears the optional process and delivery fields a
+ // desired spec drops (Terraform removing `command`, say); a merge patch
+ // would otherwise keep them.
+ let vm_template = &template.spec.vm_template;
+ for (key, absent) in [
+ ("imagePullSecret", vm_template.image_pull_secret.is_none()),
+ ("command", vm_template.command.is_none()),
+ ("probes", vm_template.probes.is_none()),
+ ("claimSecrets", vm_template.claim_secrets.is_none()),
+ ] {
+ if absent {
+ value["spec"]["vmTemplate"][key] = serde_json::Value::Null;
+ }
}
to_json(&value)
}
diff --git a/libs/fleet/sdk/tests/pool_flow.rs b/libs/fleet/sdk/tests/pool_flow.rs
index 0a9f131e26..74da2cca11 100644
--- a/libs/fleet/sdk/tests/pool_flow.rs
+++ b/libs/fleet/sdk/tests/pool_flow.rs
@@ -402,6 +402,49 @@ async fn gets_named_pool_and_updates_typed_pools() {
assert_merge_patch_request(&requests[1], ITEM, Some(&pool_merge_patch_bytes(&updated)));
}
+/// Terraform drops `idle_ttl_seconds` / `ttl_policy` / `ttl_seconds_after_created`
+/// by leaving them out of the desired spec; a merge patch only clears them
+/// when it names them as null.
+#[tokio::test]
+async fn update_pool_nulls_lifecycle_fields_the_desired_spec_drops() {
+ let current = Pool {
+ spec: serde_json::from_value(serde_json::json!({
+ "replicas": 1,
+ "sandboxTemplateRef": { "name": "example-pool-template" },
+ "ttlSecondsAfterCreated": 600,
+ "idleTtlSeconds": 3600,
+ "ttlPolicy": "Cascade",
+ }))
+ .unwrap(),
+ ..pool()
+ };
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(json_response(200, &pool())),
+ Ok(json_response(200, &current)),
+ ]));
+ let client = client(Arc::clone(&http));
+
+ client.clone().update_pool(pool()).await.unwrap();
+ client.update_pool(current).await.unwrap();
+
+ let requests = resource_requests(&http).await;
+ let dropped: serde_json::Value =
+ serde_json::from_slice(requests[0].body.as_deref().unwrap()).unwrap();
+ for key in ["ttlSecondsAfterCreated", "idleTtlSeconds", "ttlPolicy"] {
+ assert!(
+ dropped["spec"].as_object().unwrap().contains_key(key),
+ "{key} must be patched to null"
+ );
+ assert_eq!(dropped["spec"][key], serde_json::Value::Null);
+ }
+ let kept: serde_json::Value =
+ serde_json::from_slice(requests[1].body.as_deref().unwrap()).unwrap();
+ assert_eq!(kept["spec"]["ttlSecondsAfterCreated"], 600);
+ assert_eq!(kept["spec"]["idleTtlSeconds"], 3600);
+ assert_eq!(kept["spec"]["ttlPolicy"], "Cascade");
+}
+
#[tokio::test]
async fn reconcile_updates_an_existing_named_pool() {
let current = pool();
@@ -927,8 +970,19 @@ fn json_response(status: u16, value: &impl serde::Serialize) -> HttpResponse {
fn pool_merge_patch_bytes(pool: &Pool) -> Vec<u8> {
let mut value = serde_json::to_value(pool).unwrap();
- if pool.spec.autoscaling.is_none() {
- value["spec"]["autoscaling"] = serde_json::Value::Null;
+ let spec = &pool.spec;
+ for (key, absent) in [
+ ("autoscaling", spec.autoscaling.is_none()),
+ (
+ "ttlSecondsAfterCreated",
+ spec.ttl_seconds_after_created.is_none(),
+ ),
+ ("idleTtlSeconds", spec.idle_ttl_seconds.is_none()),
+ ("ttlPolicy", spec.ttl_policy.is_none()),
+ ] {
+ if absent {
+ value["spec"][key] = serde_json::Value::Null;
+ }
}
serde_json::to_vec(&value).unwrap()
}
diff --git a/libs/fleet/sdk/tests/template_flow.rs b/libs/fleet/sdk/tests/template_flow.rs
index 1d957898da..248fe37fc5 100644
--- a/libs/fleet/sdk/tests/template_flow.rs
+++ b/libs/fleet/sdk/tests/template_flow.rs
@@ -90,6 +90,55 @@ async fn reconcile_template_keeps_a_pull_secret_the_desired_spec_asks_for() {
);
}
+/// Terraform drops `command`, the probes or `claim_secrets` by leaving them
+/// out of the desired spec; the merge patch has to null them to clear them.
+#[tokio::test]
+async fn reconcile_template_nulls_process_fields_the_desired_spec_drops() {
+ let mut configured = spec(None);
+ configured.vm_template.command = Some(vec!["srv".into()]);
+ configured.vm_template.claim_secrets = Some(true);
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(token()),
+ Ok(json_response(200, &template(None))),
+ Ok(json_response(200, &template(None))),
+ Ok(json_response(200, &template(None))),
+ Ok(json_response(200, &template(None))),
+ ]));
+ let client = client(Arc::clone(&http));
+
+ client
+ .clone()
+ .reconcile_template(create_request(None))
+ .await
+ .unwrap();
+ client
+ .reconcile_template(CreateTemplateRequest {
+ spec: configured,
+ ..create_request(None)
+ })
+ .await
+ .unwrap();
+
+ let requests = http.authenticated_requests().await;
+ let dropped: serde_json::Value =
+ serde_json::from_slice(requests[1].body.as_deref().unwrap()).unwrap();
+ let vm_template = dropped["spec"]["vmTemplate"].as_object().unwrap();
+ for key in ["command", "probes", "claimSecrets"] {
+ assert!(
+ vm_template.contains_key(key),
+ "{key} must be patched to null"
+ );
+ assert_eq!(vm_template[key], serde_json::Value::Null);
+ }
+ let kept: serde_json::Value =
+ serde_json::from_slice(requests[3].body.as_deref().unwrap()).unwrap();
+ assert_eq!(
+ kept["spec"]["vmTemplate"]["command"],
+ serde_json::json!(["srv"])
+ );
+ assert_eq!(kept["spec"]["vmTemplate"]["claimSecrets"], true);
+}
+
#[tokio::test]
async fn reconcile_template_update_403_maps_to_pool_access_denied() {
let http = Arc::new(ScriptedHttpClient::new([
diff --git a/libs/fleet/src/fleet/pools.ts b/libs/fleet/src/fleet/pools.ts
index ea191382f8..aa98f8ed20 100644
--- a/libs/fleet/src/fleet/pools.ts
+++ b/libs/fleet/src/fleet/pools.ts
@@ -268,6 +268,11 @@ function seedVmTemplateBuilder(vm: VmTemplate): VmTemplateBuilderLike {
if (vm.probes !== undefined) builder = builder.probes(vm.probes)
if (vm.services !== undefined) builder = builder.services(vm.services)
if (vm.oidc !== undefined) builder = builder.oidc(vm.oidc)
+ // The SDK patches a dropped claimSecrets to null, so a services edit has to
+ // carry it or it would turn claim-secret delivery off.
+ if (vm.claimSecrets !== undefined) {
+ builder = builder.claimSecrets(vm.claimSecrets)
+ }
return builder
}
diff --git a/libs/fleet/terraform-provider-fleets/cmd/generate-pool-resource/main.go b/libs/fleet/terraform-provider-fleets/cmd/generate-pool-resource/main.go
index 0992dff4b4..4c3cae47a7 100644
--- a/libs/fleet/terraform-provider-fleets/cmd/generate-pool-resource/main.go
+++ b/libs/fleet/terraform-provider-fleets/cmd/generate-pool-resource/main.go
@@ -51,6 +51,8 @@ type schemaInfo struct {
Enum []string
Minimum *int64
Maximum *int64
+ // Items describes the elements of an array.
+ Items *schemaInfo
}
// The flat fleets_pool resource is backed by a pair of native CRs, so every
@@ -159,10 +161,10 @@ func nestedSchema(blockSchema map[string]any, item field) map[string]any {
}
// blockSchema resolves the CRD node holding a block's nested fields: the object
-// itself for a single block, its items for a set.
+// itself for a single block, its items for a set or list.
func (s crdSchemas) blockSchema(item block) map[string]any {
node := lookup(s.root(item.CR, item.Name), item.CRDPath)
- if item.Collection == "set" {
+ if item.Collection != "single" {
return mustMap(node["items"], item.CRDPath+".items")
}
return node
@@ -197,12 +199,12 @@ func validateMapping(schemas crdSchemas, config mapping) {
}
for _, item := range config.Blocks {
registerTopLevel(item.Name, item.GoName)
- if item.Collection != "single" && item.Collection != "set" {
+ if item.Collection != "single" && item.Collection != "set" && item.Collection != "list" {
fatalf("block %q has unsupported collection %q", item.Name, item.Collection)
}
expectedType := "object"
- if item.Collection == "set" {
+ if item.Collection != "single" {
expectedType = "array"
}
node := lookup(schemas.root(item.CR, item.Name), item.CRDPath)
@@ -233,7 +235,7 @@ func validateMapping(schemas crdSchemas, config mapping) {
func validateFieldConfig(item field) {
switch item.ValueType {
- case "string", "int64", "normalized_json":
+ case "string", "int64", "bool", "normalized_json", "string_list", "int64_list", "string_map":
default:
fatalf("field %q has unsupported value_type %q", item.Name, item.ValueType)
}
@@ -252,33 +254,47 @@ func validateField(node map[string]any, item field) {
return
}
info := inspect(node)
- expectedType := baseType(item.ValueType)
- if expectedType == "int64" {
- expectedType = "integer"
- }
- if item.ValueType == "normalized_json" {
- expectedType = "object"
- }
+ expectedType, elementType := crdTypes(item.ValueType)
if info.Type != expectedType {
fatalf("field %s maps to CRD type %q, expected %q", item.Name, info.Type, expectedType)
}
+ if elementType == "" {
+ return
+ }
+ var element map[string]any
+ if expectedType == "array" {
+ element, _ = node["items"].(map[string]any)
+ } else {
+ element, _ = node["additionalProperties"].(map[string]any)
+ }
+ if actual, _ := element["type"].(string); actual != elementType {
+ fatalf("field %s maps to CRD element type %q, expected %q", item.Name, actual, elementType)
+ }
+}
+
+// crdTypes is the CRD type a Terraform value type maps to and, for
+// collections, the CRD type of its elements.
+func crdTypes(valueType string) (string, string) {
+ switch valueType {
+ case "int64":
+ return "integer", ""
+ case "bool":
+ return "boolean", ""
+ case "normalized_json":
+ return "object", ""
+ case "string_list":
+ return "array", "string"
+ case "int64_list":
+ return "array", "integer"
+ case "string_map":
+ return "object", "string"
+ default:
+ return valueType, ""
+ }
}
func render(schemas crdSchemas, config mapping) []byte {
var out bytes.Buffer
- out.WriteString("// Code generated by cmd/generate-pool-resource; DO NOT EDIT.\n\n")
- out.WriteString("package provider\n\n")
- out.WriteString("import (\n\t\"regexp\"\n\n")
- out.WriteString("\t\"github.com/hashicorp/terraform-plugin-framework-jsontypes/jsontypes\"\n")
- out.WriteString("\t\"github.com/hashicorp/terraform-plugin-framework-validators/int64validator\"\n")
- out.WriteString("\t\"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator\"\n")
- out.WriteString("\t\"github.com/hashicorp/terraform-plugin-framework/attr\"\n")
- out.WriteString("\t\"github.com/hashicorp/terraform-plugin-framework/resource/schema\"\n")
- out.WriteString("\t\"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier\"\n")
- out.WriteString("\t\"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier\"\n")
- out.WriteString("\t\"github.com/hashicorp/terraform-plugin-framework/schema/validator\"\n")
- out.WriteString("\t\"github.com/hashicorp/terraform-plugin-framework/types\"\n")
- out.WriteString(")\n\n")
renderModel(&out, "poolResourceModel", config.Attributes, config.Blocks)
for _, item := range config.Blocks {
@@ -294,14 +310,14 @@ func render(schemas crdSchemas, config mapping) []byte {
for _, item := range config.Blocks {
blockSchema := schemas.blockSchema(item)
fmt.Fprintf(&out, "\t\t\t%q: schema.%sNestedBlock{", item.Name, title(item.Collection))
- if item.Collection == "set" {
+ if item.Collection != "single" {
out.WriteString("NestedObject: schema.NestedBlockObject{")
}
out.WriteString("Attributes: map[string]schema.Attribute{\n")
for _, nested := range item.Fields {
renderAttribute(&out, nestedSchema(blockSchema, nested), nested, "\t\t\t\t")
}
- if item.Collection == "set" {
+ if item.Collection != "single" {
out.WriteString("\t\t\t}}},\n")
} else {
out.WriteString("\t\t\t}},\n")
@@ -320,7 +336,35 @@ func render(schemas crdSchemas, config mapping) []byte {
out.WriteString("}\n}\n\n")
}
out.WriteString("var dnsLabelRegex = regexp.MustCompile(`^[a-z0-9]([-a-z0-9]*[a-z0-9])?$`)\n")
- return out.Bytes()
+
+ var file bytes.Buffer
+ file.WriteString("// Code generated by cmd/generate-pool-resource; DO NOT EDIT.\n\n")
+ file.WriteString("package provider\n\n")
+ file.WriteString("import (\n\t\"regexp\"\n\n")
+ body := out.String()
+ for _, item := range generatedImports {
+ // Import only what the body uses so new value types never leave an
+ // unused import behind.
+ if strings.Contains(body, item.selector+".") {
+ fmt.Fprintf(&file, "\t%q\n", item.path)
+ }
+ }
+ file.WriteString(")\n\n")
+ file.Write(out.Bytes())
+ return file.Bytes()
+}
+
+var generatedImports = []struct{ path, selector string }{
+ {"github.com/hashicorp/terraform-plugin-framework-jsontypes/jsontypes", "jsontypes"},
+ {"github.com/hashicorp/terraform-plugin-framework-validators/int64validator", "int64validator"},
+ {"github.com/hashicorp/terraform-plugin-framework-validators/listvalidator", "listvalidator"},
+ {"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator", "stringvalidator"},
+ {"github.com/hashicorp/terraform-plugin-framework/attr", "attr"},
+ {"github.com/hashicorp/terraform-plugin-framework/resource/schema", "schema"},
+ {"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier", "planmodifier"},
+ {"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier", "stringplanmodifier"},
+ {"github.com/hashicorp/terraform-plugin-framework/schema/validator", "validator"},
+ {"github.com/hashicorp/terraform-plugin-framework/types", "types"},
}
func renderModel(out *bytes.Buffer, name string, fields []field, blocks []block) {
@@ -330,8 +374,11 @@ func renderModel(out *bytes.Buffer, name string, fields []field, blocks []block)
}
for _, item := range blocks {
valueType := "types.Object"
- if item.Collection == "set" {
+ switch item.Collection {
+ case "set":
valueType = "types.Set"
+ case "list":
+ valueType = "types.List"
}
fmt.Fprintf(out, "\t%s %s `tfsdk:%q`\n", item.GoName, valueType, item.Name)
}
@@ -369,6 +416,9 @@ func renderAttribute(out *bytes.Buffer, node map[string]any, item field, indent
if item.ValueType == "normalized_json" {
out.WriteString(", CustomType: jsontypes.NormalizedType{}")
}
+ if element := elementType(item.ValueType); element != "" {
+ fmt.Fprintf(out, ", ElementType: %s", element)
+ }
if description != "" {
fmt.Fprintf(out, ", Description: %s", strconv.Quote(strings.TrimSpace(description)))
}
@@ -394,6 +444,11 @@ func validatorsFor(item field, info schemaInfo) []string {
}
result = append(result, "stringvalidator.OneOf("+strings.Join(quoted, ", ")+")")
}
+ if item.ValueType == "int64_list" && info.Items != nil {
+ if bounds := int64Bounds(*info.Items); bounds != "" {
+ result = append(result, "listvalidator.ValueInt64sAre("+bounds+")")
+ }
+ }
if info.Minimum != nil && item.ValueType == "int64" {
if info.Maximum != nil {
result = append(result, fmt.Sprintf("int64validator.Between(%d, %d)", *info.Minimum, *info.Maximum))
@@ -404,6 +459,17 @@ func validatorsFor(item field, info schemaInfo) []string {
return result
}
+func int64Bounds(info schemaInfo) string {
+ switch {
+ case info.Minimum != nil && info.Maximum != nil:
+ return fmt.Sprintf("int64validator.Between(%d, %d)", *info.Minimum, *info.Maximum)
+ case info.Minimum != nil:
+ return fmt.Sprintf("int64validator.AtLeast(%d)", *info.Minimum)
+ default:
+ return ""
+ }
+}
+
func lookup(root map[string]any, path string) map[string]any {
current := root
for _, part := range strings.Split(path, ".") {
@@ -429,6 +495,10 @@ func inspect(value map[string]any) schemaInfo {
}
info.Minimum = integerPointer(value["minimum"])
info.Maximum = integerPointer(value["maximum"])
+ if items, ok := value["items"].(map[string]any); ok {
+ itemInfo := inspect(items)
+ info.Items = &itemInfo
+ }
return info
}
@@ -451,22 +521,50 @@ func modelType(valueType string) string {
if valueType == "normalized_json" {
return "jsontypes.Normalized"
}
- return "types." + title(valueType)
+ return "types." + title(baseType(valueType))
}
func attrType(valueType string) string {
- if valueType == "int64" {
+ switch valueType {
+ case "int64":
+ return "types.Int64Type"
+ case "bool":
+ return "types.BoolType"
+ case "string_list", "int64_list":
+ return "types.ListType{ElemType: " + elementType(valueType) + "}"
+ case "string_map":
+ return "types.MapType{ElemType: " + elementType(valueType) + "}"
+ default:
+ return "types.StringType"
+ }
+}
+
+// elementType is the element attr.Type of a collection value type, or "".
+func elementType(valueType string) string {
+ switch valueType {
+ case "string_list", "string_map":
+ return "types.StringType"
+ case "int64_list":
return "types.Int64Type"
+ default:
+ return ""
}
- return "types.StringType"
}
func attributeType(valueType string) string { return title(baseType(valueType)) }
+
+// baseType is the Terraform schema kind of a value type.
func baseType(valueType string) string {
- if valueType == "normalized_json" {
+ switch valueType {
+ case "normalized_json":
return "string"
+ case "string_list", "int64_list":
+ return "list"
+ case "string_map":
+ return "map"
+ default:
+ return valueType
}
- return valueType
}
func title(value string) string {
if value == "int64" {
diff --git a/libs/fleet/terraform-provider-fleets/cmd/generate-pool-resource/main_test.go b/libs/fleet/terraform-provider-fleets/cmd/generate-pool-resource/main_test.go
index 241f4e2e04..0e9aa27e0a 100644
--- a/libs/fleet/terraform-provider-fleets/cmd/generate-pool-resource/main_test.go
+++ b/libs/fleet/terraform-provider-fleets/cmd/generate-pool-resource/main_test.go
@@ -2,6 +2,7 @@ package main
import (
"bytes"
+ "go/format"
"os"
"os/exec"
"strings"
@@ -21,10 +22,10 @@ func TestValidateMappingRejectsInvalidMapping(t *testing.T) {
scenario string
wantStderr string
}{
- {name: "unsupported value type", scenario: "unsupported_value_type", wantStderr: `field "name" has unsupported value_type "bool"`},
+ {name: "unsupported value type", scenario: "unsupported_value_type", wantStderr: `field "name" has unsupported value_type "float"`},
{name: "unsupported mode", scenario: "unsupported_mode", wantStderr: `field "name" has unsupported mode "write_only"`},
{name: "requires replace on non-string", scenario: "requires_replace_int64", wantStderr: `field "replicas" sets requires_replace with value_type "int64"`},
- {name: "unsupported collection", scenario: "unsupported_collection", wantStderr: `block "service" has unsupported collection "list"`},
+ {name: "unsupported collection", scenario: "unsupported_collection", wantStderr: `block "service" has unsupported collection "map"`},
{name: "duplicate top-level name", scenario: "duplicate_top_level_name", wantStderr: `duplicate top-level Terraform name "name"`},
{name: "duplicate top-level Go name", scenario: "duplicate_top_level_go_name", wantStderr: `duplicate top-level Go name "Name"`},
{name: "duplicate block name", scenario: "duplicate_block_name", wantStderr: `duplicate top-level Terraform name "service"`},
@@ -37,6 +38,8 @@ func TestValidateMappingRejectsInvalidMapping(t *testing.T) {
{name: "unknown block CR", scenario: "unknown_block_cr", wantStderr: `"service" maps to unsupported cr "sandbox"`},
{name: "nested CR", scenario: "nested_cr", wantStderr: `field "name" in block "service" must not set cr`},
{name: "path in the other CR", scenario: "path_in_other_cr", wantStderr: `spec.vmTemplate.services is not an object`},
+ {name: "wrong list element type", scenario: "wrong_list_element_type", wantStderr: `field command maps to CRD element type "integer", expected "string"`},
+ {name: "wrong map element type", scenario: "wrong_map_element_type", wantStderr: `field env maps to CRD element type "", expected "string"`},
}
for _, test := range tests {
@@ -61,6 +64,43 @@ func TestRenderIsDeterministic(t *testing.T) {
}
}
+func TestRenderCollectionAndBoolTypes(t *testing.T) {
+ schemas, config := validationFixture("valid")
+ config.Attributes = append(config.Attributes,
+ field{Name: "command", GoName: "Command", ValueType: "string_list", Mode: "optional", CR: templateCR, CRDPath: "spec.vmTemplate.command"},
+ field{Name: "env", GoName: "Env", ValueType: "string_map", Mode: "optional", CR: templateCR, CRDPath: "spec.vmTemplate.env"},
+ field{Name: "claim_secrets", GoName: "ClaimSecrets", ValueType: "bool", Mode: "optional", CR: templateCR, CRDPath: "spec.vmTemplate.claimSecrets"},
+ field{Name: "ports", GoName: "Ports", ValueType: "int64_list", Mode: "optional", CR: templateCR, CRDPath: "spec.vmTemplate.ports"},
+ )
+ config.Blocks[0].Collection = "list"
+ validateMapping(schemas, config)
+ output, err := format.Source(render(schemas, config))
+ if err != nil {
+ t.Fatalf("generated source does not parse: %v", err)
+ }
+ // gofmt aligns struct fields and map keys; compare with single spaces.
+ generated := strings.Join(strings.Fields(string(output)), " ")
+ for _, want := range []string{
+ "Command types.List `tfsdk:\"command\"`",
+ "Env types.Map `tfsdk:\"env\"`",
+ "ClaimSecrets types.Bool `tfsdk:\"claim_secrets\"`",
+ "Services types.List `tfsdk:\"service\"`",
+ `"command": schema.ListAttribute{Optional: true, ElementType: types.StringType}`,
+ `"env": schema.MapAttribute{Optional: true, ElementType: types.StringType}`,
+ `"claim_secrets": schema.BoolAttribute{Optional: true}`,
+ `"ports": schema.ListAttribute{Optional: true, ElementType: types.Int64Type, Validators: []validator.List{listvalidator.ValueInt64sAre(int64validator.Between(1, 65535))}}`,
+ `"service": schema.ListNestedBlock{NestedObject: schema.NestedBlockObject{`,
+ `"github.com/hashicorp/terraform-plugin-framework-validators/listvalidator"`,
+ } {
+ if !strings.Contains(generated, want) {
+ t.Errorf("generated source is missing %s\n%s", want, output)
+ }
+ }
+ if strings.Contains(generated, "jsontypes") {
+ t.Error("generated source imports jsontypes without using it")
+ }
+}
+
func TestReadCRDSchemasFindsBothNativeCRDs(t *testing.T) {
schemas := readCRDSchemas("../../../../clusters/base/osgym/crd.yaml")
if lookup(schemas.root(warmPoolCR, "replicas"), "spec.replicas")["type"] != "integer" {
@@ -107,6 +147,10 @@ func validationFixture(scenario string) (crdSchemas, mapping) {
"vmTemplate": map[string]any{
"type": "object",
"properties": map[string]any{
+ "command": map[string]any{"type": "array", "items": map[string]any{"type": "string"}},
+ "env": map[string]any{"type": "object", "additionalProperties": map[string]any{"type": "string"}},
+ "claimSecrets": map[string]any{"type": "boolean"},
+ "ports": map[string]any{"type": "array", "items": map[string]any{"type": "integer", "minimum": 1.0, "maximum": 65535.0}},
"services": map[string]any{
"type": "array",
"items": map[string]any{
@@ -139,13 +183,13 @@ func validationFixture(scenario string) (crdSchemas, mapping) {
switch scenario {
case "valid":
case "unsupported_value_type":
- config.Attributes[0].ValueType = "bool"
+ config.Attributes[0].ValueType = "float"
case "unsupported_mode":
config.Attributes[0].Mode = "write_only"
case "requires_replace_int64":
config.Attributes[1].RequiresReplace = true
case "unsupported_collection":
- config.Blocks[0].Collection = "list"
+ config.Blocks[0].Collection = "map"
case "duplicate_top_level_name":
config.Blocks[0].Name = "name"
case "duplicate_top_level_go_name":
@@ -171,6 +215,12 @@ func validationFixture(scenario string) (crdSchemas, mapping) {
config.Blocks[0].CR = "sandbox"
case "nested_cr":
config.Blocks[0].Fields[0].CR = templateCR
+ case "wrong_list_element_type":
+ config.Attributes = append(config.Attributes, field{Name: "command", GoName: "Command", ValueType: "string_list", Mode: "optional", CR: templateCR, CRDPath: "spec.vmTemplate.command"})
+ vmTemplateProperties(template)["command"].(map[string]any)["items"] = map[string]any{"type": "integer"}
+ case "wrong_map_element_type":
+ config.Attributes = append(config.Attributes, field{Name: "env", GoName: "Env", ValueType: "string_map", Mode: "optional", CR: templateCR, CRDPath: "spec.vmTemplate.env"})
+ delete(vmTemplateProperties(template)["env"].(map[string]any), "additionalProperties")
case "path_in_other_cr":
config.Blocks[0].CR = warmPoolCR
default:
@@ -179,6 +229,10 @@ func validationFixture(scenario string) (crdSchemas, mapping) {
return schemas, config
}
+func vmTemplateProperties(root map[string]any) map[string]any {
+ return root["properties"].(map[string]any)["spec"].(map[string]any)["properties"].(map[string]any)["vmTemplate"].(map[string]any)["properties"].(map[string]any)
+}
+
func warmPoolSpec(root map[string]any) map[string]any {
return root["properties"].(map[string]any)["spec"].(map[string]any)["properties"].(map[string]any)
}
diff --git a/libs/fleet/terraform-provider-fleets/docs/resources/pool.md b/libs/fleet/terraform-provider-fleets/docs/resources/pool.md
index ff263f04be..c29585a7cc 100644
--- a/libs/fleet/terraform-provider-fleets/docs/resources/pool.md
+++ b/libs/fleet/terraform-provider-fleets/docs/resources/pool.md
@@ -58,6 +58,38 @@ resource "fleets_pool" "public_gvisor" {
}
```
+## SDK-equivalent pool
+
+`cua fleet pool export --terraform` prints this shape for a pool made with
+`Sandbox.create` or `Pool.apply`: a process, claim-scoped secrets, a warm
+floor of one, and lifecycle TTLs.
+
+```terraform
+resource "fleets_pool" "agent" {
+ name = "agent-linux"
+ cpu_cores = 4
+ memory = "8Gi"
+ container_disk_image = "ghcr.io/example/agent@sha256:..."
+ runtime = "gvisor"
+ command = ["python", "-m", "http.server", "8765"]
+ claim_secrets = true
+ idle_ttl_seconds = 86400
+ ttl_policy = "Cascade"
+ ttl_seconds_after_created = 604800
+
+ autoscaling {
+ min_pool_size = 1
+ initial_pool_size = 1
+ max_pool_size = 20
+ }
+
+ service {
+ name = "http"
+ target_port = 8765
+ }
+}
+```
+
## Arguments
- `name` - Pool and namespace DNS label. Changing it replaces the resource.
@@ -69,12 +101,21 @@ resource "fleets_pool" "public_gvisor" {
- `runtime` - `kubevirt`, `macos`, or `gvisor`; defaults to `kubevirt`.
- `firmware` - `bios` or `efi`; defaults to `bios`.
- `readiness_probe_json` / `liveness_probe_json` - Kubernetes probe objects encoded as JSON.
+- `command` - Entrypoint command list (replaces the image entrypoint). Pod runtimes (`gvisor`, `macos`) run it; KubeVirt ignores it.
+- `claim_secrets` - Opt in to claim-scoped secret delivery at `/run/cua` (the per-claim env token and a claim's `secretRef`). Claims with a `secretRef` fail on pools without it.
+- `idle_ttl_seconds` - Delete the pool after this many seconds with no Pending or Bound claims. Omit it to never reap for idleness.
+- `ttl_policy` - What a TTL expiry deletes: `Retain` (the pool only, the behavior when omitted) or `Cascade` (also the pool's dead unbound claims; never Bound claims, the namespace or volumes).
+- `ttl_seconds_after_created` - Delete the pool this many seconds after it was created. Omit it to never reap by age.
- `service` - Repeatable service with `name`, `target_port`, and optional `protocol`.
- `autoscaling` - Claim-driven autoscaling limits. Exactly one of `replicas` or `autoscaling` is required.
- `autoscaling.min_pool_size` - Minimum warm pool size while autoscaling is enabled.
- `autoscaling.initial_pool_size` - Initial pool target when autoscaling starts.
- `autoscaling.max_pool_size` - Maximum autoscaled pool size; defaults to `50` when omitted.
+Removing `command`, `claim_secrets`, a probe or a lifecycle attribute from the
+configuration clears it from the Fleet object. A pool TTL that expires deletes
+the pool; the next apply creates it again.
+
## Read-only Attributes
`namespace` and `template_name` identify the objects Fleet created. In autoscaling mode, `replicas` reports the current pool target so scaling changes remain visible in Terraform state. `current_replicas` and `ready_replicas` report the number of current and ready sandboxes.
diff --git a/libs/fleet/terraform-provider-fleets/internal/provider/generate/pool_mapping.json b/libs/fleet/terraform-provider-fleets/internal/provider/generate/pool_mapping.json
index 57556afcb4..b6394b6183 100644
--- a/libs/fleet/terraform-provider-fleets/internal/provider/generate/pool_mapping.json
+++ b/libs/fleet/terraform-provider-fleets/internal/provider/generate/pool_mapping.json
@@ -97,6 +97,46 @@
"crd_path": "spec.vmTemplate.probes",
"description": "JSON object for the VMI livenessProbe."
},
+ {
+ "name": "command",
+ "go_name": "Command",
+ "value_type": "string_list",
+ "mode": "optional",
+ "cr": "template",
+ "crd_path": "spec.vmTemplate.command"
+ },
+ {
+ "name": "claim_secrets",
+ "go_name": "ClaimSecrets",
+ "value_type": "bool",
+ "mode": "optional",
+ "cr": "template",
+ "crd_path": "spec.vmTemplate.claimSecrets"
+ },
+ {
+ "name": "ttl_seconds_after_created",
+ "go_name": "TTLSecondsAfterCreated",
+ "value_type": "int64",
+ "mode": "optional",
+ "cr": "warmpool",
+ "crd_path": "spec.ttlSecondsAfterCreated"
+ },
+ {
+ "name": "idle_ttl_seconds",
+ "go_name": "IdleTTLSeconds",
+ "value_type": "int64",
+ "mode": "optional",
+ "cr": "warmpool",
+ "crd_path": "spec.idleTtlSeconds"
+ },
+ {
+ "name": "ttl_policy",
+ "go_name": "TTLPolicy",
+ "value_type": "string",
+ "mode": "optional",
+ "cr": "warmpool",
+ "crd_path": "spec.ttlPolicy"
+ },
{
"name": "template_name",
"go_name": "TemplateName",
diff --git a/libs/fleet/terraform-provider-fleets/internal/provider/pool_generated.go b/libs/fleet/terraform-provider-fleets/internal/provider/pool_generated.go
index 0004bd75f1..53390e44d3 100644
--- a/libs/fleet/terraform-provider-fleets/internal/provider/pool_generated.go
+++ b/libs/fleet/terraform-provider-fleets/internal/provider/pool_generated.go
@@ -17,23 +17,28 @@ import (
)
type poolResourceModel struct {
- ID types.String `tfsdk:"id"`
- Name types.String `tfsdk:"name"`
- Namespace types.String `tfsdk:"namespace"`
- Replicas types.Int64 `tfsdk:"replicas"`
- CPUCores types.Int64 `tfsdk:"cpu_cores"`
- Memory types.String `tfsdk:"memory"`
- ContainerDiskImage types.String `tfsdk:"container_disk_image"`
- ImagePullSecret types.String `tfsdk:"image_pull_secret"`
- Runtime types.String `tfsdk:"runtime"`
- Firmware types.String `tfsdk:"firmware"`
- ReadinessProbeJSON jsontypes.Normalized `tfsdk:"readiness_probe_json"`
- LivenessProbeJSON jsontypes.Normalized `tfsdk:"liveness_probe_json"`
- TemplateName types.String `tfsdk:"template_name"`
- CurrentReplicas types.Int64 `tfsdk:"current_replicas"`
- ReadyReplicas types.Int64 `tfsdk:"ready_replicas"`
- Services types.Set `tfsdk:"service"`
- Autoscaling types.Object `tfsdk:"autoscaling"`
+ ID types.String `tfsdk:"id"`
+ Name types.String `tfsdk:"name"`
+ Namespace types.String `tfsdk:"namespace"`
+ Replicas types.Int64 `tfsdk:"replicas"`
+ CPUCores types.Int64 `tfsdk:"cpu_cores"`
+ Memory types.String `tfsdk:"memory"`
+ ContainerDiskImage types.String `tfsdk:"container_disk_image"`
+ ImagePullSecret types.String `tfsdk:"image_pull_secret"`
+ Runtime types.String `tfsdk:"runtime"`
+ Firmware types.String `tfsdk:"firmware"`
+ ReadinessProbeJSON jsontypes.Normalized `tfsdk:"readiness_probe_json"`
+ LivenessProbeJSON jsontypes.Normalized `tfsdk:"liveness_probe_json"`
+ Command types.List `tfsdk:"command"`
+ ClaimSecrets types.Bool `tfsdk:"claim_secrets"`
+ TTLSecondsAfterCreated types.Int64 `tfsdk:"ttl_seconds_after_created"`
+ IdleTTLSeconds types.Int64 `tfsdk:"idle_ttl_seconds"`
+ TTLPolicy types.String `tfsdk:"ttl_policy"`
+ TemplateName types.String `tfsdk:"template_name"`
+ CurrentReplicas types.Int64 `tfsdk:"current_replicas"`
+ ReadyReplicas types.Int64 `tfsdk:"ready_replicas"`
+ Services types.Set `tfsdk:"service"`
+ Autoscaling types.Object `tfsdk:"autoscaling"`
}
type serviceModel struct {
@@ -51,21 +56,26 @@ type autoscalingModel struct {
func poolResourceSchema() schema.Schema {
return schema.Schema{Description: "A Cua Fleet computer-use pool: an OSGymSandboxWarmPool and its OSGymSandboxTemplate. The pool name also owns its same-named namespace.",
Attributes: map[string]schema.Attribute{
- "id": schema.StringAttribute{Computed: true},
- "name": schema.StringAttribute{Required: true, Description: "DNS label used for both pool and namespace.", Validators: []validator.String{stringvalidator.LengthBetween(1, 63), stringvalidator.RegexMatches(dnsLabelRegex, "must be a lowercase DNS label")}, PlanModifiers: []planmodifier.String{stringplanmodifier.RequiresReplace()}},
- "namespace": schema.StringAttribute{Computed: true},
- "replicas": schema.Int64Attribute{Optional: true, Computed: true, Description: "Desired number of pre-warmed OSGymSandboxes.", Validators: []validator.Int64{int64validator.AtLeast(0)}},
- "cpu_cores": schema.Int64Attribute{Required: true, Validators: []validator.Int64{int64validator.AtLeast(1)}},
- "memory": schema.StringAttribute{Required: true},
- "container_disk_image": schema.StringAttribute{Required: true, Description: "KubeVirt containerDisk OCI image (runtime=kubevirt) or the sandbox pod image ref (runtime=macos/gvisor)."},
- "image_pull_secret": schema.StringAttribute{Optional: true, Description: "Kubernetes image pull secret. Omit this argument for anonymous public-image pulls."},
- "runtime": schema.StringAttribute{Optional: true, Computed: true, Description: "Pool backend runtime. \"kubevirt\" (default) reconciles each sandbox into a KubeVirt VM. \"macos\" reconciles it into a macOS sandbox (an agent-sandbox Sandbox on a macOS node); \"gvisor\" into a gVisor (runsc) pod on the gVisor K3s workers (also an agent-sandbox Sandbox). For the pod runtimes containerDiskImage is the pod image ref and firmware/cpuCores/memory are advisory.", Validators: []validator.String{stringvalidator.OneOf("gvisor", "kubevirt", "macos")}},
- "firmware": schema.StringAttribute{Optional: true, Computed: true, Description: "VM firmware. Use \"efi\" for GPT/UEFI-only guest images (e.g. the dockur-built Windows desktop-workspace); \"bios\" is KubeVirt's default and what the Linux workspace images boot with.", Validators: []validator.String{stringvalidator.OneOf("bios", "efi")}},
- "readiness_probe_json": schema.StringAttribute{Optional: true, CustomType: jsontypes.NormalizedType{}, Description: "JSON object for the VMI readinessProbe."},
- "liveness_probe_json": schema.StringAttribute{Optional: true, CustomType: jsontypes.NormalizedType{}, Description: "JSON object for the VMI livenessProbe."},
- "template_name": schema.StringAttribute{Computed: true, Description: "Name of the OSGymSandboxTemplate backing this pool."},
- "current_replicas": schema.Int64Attribute{Computed: true, Description: "Sandboxes the warm pool currently owns."},
- "ready_replicas": schema.Int64Attribute{Computed: true, Description: "Sandboxes that are ready to be claimed."},
+ "id": schema.StringAttribute{Computed: true},
+ "name": schema.StringAttribute{Required: true, Description: "DNS label used for both pool and namespace.", Validators: []validator.String{stringvalidator.LengthBetween(1, 63), stringvalidator.RegexMatches(dnsLabelRegex, "must be a lowercase DNS label")}, PlanModifiers: []planmodifier.String{stringplanmodifier.RequiresReplace()}},
+ "namespace": schema.StringAttribute{Computed: true},
+ "replicas": schema.Int64Attribute{Optional: true, Computed: true, Description: "Desired number of pre-warmed OSGymSandboxes.", Validators: []validator.Int64{int64validator.AtLeast(0)}},
+ "cpu_cores": schema.Int64Attribute{Required: true, Validators: []validator.Int64{int64validator.AtLeast(1)}},
+ "memory": schema.StringAttribute{Required: true},
+ "container_disk_image": schema.StringAttribute{Required: true, Description: "KubeVirt containerDisk OCI image (runtime=kubevirt) or the sandbox pod image ref (runtime=macos/gvisor)."},
+ "image_pull_secret": schema.StringAttribute{Optional: true, Description: "Kubernetes image pull secret. Omit this argument for anonymous public-image pulls."},
+ "runtime": schema.StringAttribute{Optional: true, Computed: true, Description: "Pool backend runtime. \"kubevirt\" (default) reconciles each sandbox into a KubeVirt VM. \"macos\" reconciles it into a macOS sandbox (an agent-sandbox Sandbox on a macOS node); \"gvisor\" into a gVisor (runsc) pod on the gVisor K3s workers (also an agent-sandbox Sandbox). For the pod runtimes containerDiskImage is the pod image ref and firmware/cpuCores/memory are advisory.", Validators: []validator.String{stringvalidator.OneOf("gvisor", "kubevirt", "macos")}},
+ "firmware": schema.StringAttribute{Optional: true, Computed: true, Description: "VM firmware. Use \"efi\" for GPT/UEFI-only guest images (e.g. the dockur-built Windows desktop-workspace); \"bios\" is KubeVirt's default and what the Linux workspace images boot with.", Validators: []validator.String{stringvalidator.OneOf("bios", "efi")}},
+ "readiness_probe_json": schema.StringAttribute{Optional: true, CustomType: jsontypes.NormalizedType{}, Description: "JSON object for the VMI readinessProbe."},
+ "liveness_probe_json": schema.StringAttribute{Optional: true, CustomType: jsontypes.NormalizedType{}, Description: "JSON object for the VMI livenessProbe."},
+ "command": schema.ListAttribute{Optional: true, ElementType: types.StringType, Description: "Pod runtimes (macos/gvisor) only. Entrypoint command for the sandbox container (overrides the image default)."},
+ "claim_secrets": schema.BoolAttribute{Optional: true, Description: "Opt in to claim-scoped secret delivery (OSGymSandboxClaim spec.secretRef). The pool-operator gives every sandbox an operator-owned Secret, empty while the sandbox is warm, fills it when a claim binds and wipes it on release, so a warm sandbox receives its claimant's secrets without a restart. Pod runtimes mount it read-only as a directory (never subPath) at /run/cua, root-owned, mode 0600; the image keeps its default root user, and its root token-sync helper hands the token to a non-root driver. KubeVirt shares it over virtiofs as tag cua-claim-secrets (needs the KubeVirt EnableVirtioFsConfigVolumes feature gate); the guest image mounts that tag read-only at /run/cua. cua-env-driver images enable their await-token mode only when /run/cua is a mount point, so the key env-token becomes /run/cua/env-token. Claims with a secretRef fail on templates without this flag."},
+ "ttl_seconds_after_created": schema.Int64Attribute{Optional: true, Description: "Creation-age TTL in seconds. When absent, the resource is not automatically reaped based on age.", Validators: []validator.Int64{int64validator.Between(0, 4294967295)}},
+ "idle_ttl_seconds": schema.Int64Attribute{Optional: true, Description: "Idle TTL in seconds. The pool-operator deletes the pool once it has had no Pending or Bound claims for this long, measured from status.lastActivityTime (or creation when no claim was ever made), when OSGYM_POOL_LIFECYCLE_MODE is enforce. When absent, the pool is never reaped for being idle.", Validators: []validator.Int64{int64validator.Between(0, 4294967295)}},
+ "ttl_policy": schema.StringAttribute{Optional: true, Description: "What expiry of ttlSecondsAfterCreated or idleTtlSeconds deletes. Retain (the behaviour when absent) deletes only the pool. Cascade also deletes the pool's dead unbound claims (TTL passed and older than max(900s, bindDeadline)); it never deletes Bound claims, the namespace or volumes.", Validators: []validator.String{stringvalidator.OneOf("Cascade", "Retain")}},
+ "template_name": schema.StringAttribute{Computed: true, Description: "Name of the OSGymSandboxTemplate backing this pool."},
+ "current_replicas": schema.Int64Attribute{Computed: true, Description: "Sandboxes the warm pool currently owns."},
+ "ready_replicas": schema.Int64Attribute{Computed: true, Description: "Sandboxes that are ready to be claimed."},
},
Blocks: map[string]schema.Block{
"service": schema.SetNestedBlock{NestedObject: schema.NestedBlockObject{Attributes: map[string]schema.Attribute{
diff --git a/libs/fleet/terraform-provider-fleets/internal/provider/pool_parity_test.go b/libs/fleet/terraform-provider-fleets/internal/provider/pool_parity_test.go
new file mode 100644
index 0000000000..af6a48a8c5
--- /dev/null
+++ b/libs/fleet/terraform-provider-fleets/internal/provider/pool_parity_test.go
@@ -0,0 +1,181 @@
+package provider
+
+import (
+ "context"
+ "testing"
+
+ "github.com/hashicorp/terraform-plugin-framework/attr"
+ "github.com/hashicorp/terraform-plugin-framework/diag"
+ "github.com/hashicorp/terraform-plugin-framework/types"
+ "github.com/trycua/cloud/cyclops-cs/sdk-bindings/go-uniffi/cyclops_sdk_schema"
+ "github.com/trycua/cloud/cyclops-cs/sdk-bindings/go-uniffi/fleet_sdk"
+)
+
+// The attributes Sandbox.create / Pool.apply can set, named as
+// `cua fleet pool export --terraform` emits them.
+func parityPoolModel() poolResourceModel {
+ model := examplePoolModel()
+ model.Command = types.ListValueMust(types.StringType, []attr.Value{types.StringValue("python"), types.StringValue("-m"), types.StringValue("srv")})
+ model.ClaimSecrets = types.BoolValue(true)
+ model.TTLSecondsAfterCreated = types.Int64Value(7200)
+ model.IdleTTLSeconds = types.Int64Value(86400)
+ model.TTLPolicy = types.StringValue("Cascade")
+ return model
+}
+
+func TestPoolParityAttributesAreOptionalOnly(t *testing.T) {
+ // Optional without Computed: an old state that lacks them and a server
+ // object that lacks them both read as null, so upgrading plans no diff.
+ attributes := poolResourceSchema().Attributes
+ for _, name := range []string{"command", "claim_secrets", "ttl_seconds_after_created", "idle_ttl_seconds", "ttl_policy"} {
+ attribute, ok := attributes[name]
+ if !ok {
+ t.Fatalf("%s is missing from the schema", name)
+ }
+ if !attribute.IsOptional() || attribute.IsComputed() || attribute.IsRequired() {
+ t.Fatalf("%s optional = %t, computed = %t, required = %t; want optional-only", name, attribute.IsOptional(), attribute.IsComputed(), attribute.IsRequired())
+ }
+ }
+}
+
+func TestPoolParityAttributesReachTheSDK(t *testing.T) {
+ model := parityPoolModel()
+
+ var diagnostics diag.Diagnostics
+ spec := model.toSDKPoolSpec(context.Background(), &diagnostics)
+ template := model.toSDKTemplateSpec(context.Background(), &diagnostics)
+ if diagnostics.HasError() {
+ t.Fatalf("unexpected diagnostics: %v", diagnostics)
+ }
+ if spec.TtlSecondsAfterCreated == nil || *spec.TtlSecondsAfterCreated != 7200 {
+ t.Fatalf("ttlSecondsAfterCreated = %v, want 7200", spec.TtlSecondsAfterCreated)
+ }
+ if spec.IdleTtlSeconds == nil || *spec.IdleTtlSeconds != 86400 {
+ t.Fatalf("idleTtlSeconds = %v, want 86400", spec.IdleTtlSeconds)
+ }
+ if spec.TtlPolicy == nil || *spec.TtlPolicy != cyclops_sdk_schema.WarmPoolTtlPolicyCascade {
+ t.Fatalf("ttlPolicy = %v, want Cascade", spec.TtlPolicy)
+ }
+ vm := template.VmTemplate
+ if vm.Command == nil || len(*vm.Command) != 3 || (*vm.Command)[2] != "srv" {
+ t.Fatalf("command = %v, want [python -m srv]", vm.Command)
+ }
+ if vm.ClaimSecrets == nil || !*vm.ClaimSecrets {
+ t.Fatalf("claimSecrets = %v, want true", vm.ClaimSecrets)
+ }
+}
+
+func TestPoolParityAttributesOmittedWhenUnset(t *testing.T) {
+ model := examplePoolModel()
+
+ var diagnostics diag.Diagnostics
+ spec := model.toSDKPoolSpec(context.Background(), &diagnostics)
+ template := model.toSDKTemplateSpec(context.Background(), &diagnostics)
+ if diagnostics.HasError() {
+ t.Fatalf("unexpected diagnostics: %v", diagnostics)
+ }
+ if spec.TtlSecondsAfterCreated != nil || spec.IdleTtlSeconds != nil || spec.TtlPolicy != nil {
+ t.Fatalf("lifecycle fields = %v %v %v, want all omitted", spec.TtlSecondsAfterCreated, spec.IdleTtlSeconds, spec.TtlPolicy)
+ }
+ if template.VmTemplate.Command != nil || template.VmTemplate.ClaimSecrets != nil {
+ t.Fatalf("command = %v, claimSecrets = %v; want omitted", template.VmTemplate.Command, template.VmTemplate.ClaimSecrets)
+ }
+}
+
+func TestPoolParityEmptyCommandIsSentAsEmpty(t *testing.T) {
+ model := examplePoolModel()
+ model.Command = types.ListValueMust(types.StringType, []attr.Value{})
+
+ var diagnostics diag.Diagnostics
+ template := model.toSDKTemplateSpec(context.Background(), &diagnostics)
+ if diagnostics.HasError() {
+ t.Fatalf("unexpected diagnostics: %v", diagnostics)
+ }
+ if template.VmTemplate.Command == nil || len(*template.VmTemplate.Command) != 0 {
+ t.Fatalf("command = %v, want an explicit empty list", template.VmTemplate.Command)
+ }
+}
+
+func TestPoolParityRoundTripsThroughTheSDK(t *testing.T) {
+ want := parityPoolModel()
+ var diagnostics diag.Diagnostics
+ pool := want.toSDKPool(context.Background(), &diagnostics)
+ template := fleet_sdk.Template{Spec: want.toSDKTemplateSpec(context.Background(), &diagnostics)}
+
+ var got poolResourceModel
+ got.fromSDKPool(pool, &diagnostics)
+ got.fromSDKTemplate(context.Background(), &template, &diagnostics)
+ if diagnostics.HasError() {
+ t.Fatalf("unexpected diagnostics: %v", diagnostics)
+ }
+ for name, pair := range map[string][2]attr.Value{
+ "command": {got.Command, want.Command},
+ "claim_secrets": {got.ClaimSecrets, want.ClaimSecrets},
+ "ttl_seconds_after_created": {got.TTLSecondsAfterCreated, want.TTLSecondsAfterCreated},
+ "idle_ttl_seconds": {got.IdleTTLSeconds, want.IdleTTLSeconds},
+ "ttl_policy": {got.TTLPolicy, want.TTLPolicy},
+ } {
+ if !pair[0].Equal(pair[1]) {
+ t.Errorf("%s = %v, want %v", name, pair[0], pair[1])
+ }
+ }
+}
+
+func TestPoolParityOldShapedObjectsReadAsNull(t *testing.T) {
+ cpuCores := uint32(4)
+ memory := "8Gi"
+ pool := fleet_sdk.Pool{
+ Metadata: fleet_sdk.ResourceMetadata{Namespace: "example", Name: "example"},
+ Spec: cyclops_sdk_schema.OsGymSandboxWarmPoolSpec{
+ Replicas: 1, SandboxTemplateRef: cyclops_sdk_schema.SandboxTemplateRef{Name: "example-template"},
+ },
+ }
+ template := fleet_sdk.Template{Spec: cyclops_sdk_schema.OsGymSandboxTemplateSpec{VmTemplate: cyclops_sdk_schema.VmTemplate{
+ ContainerDiskImage: "registry.example/image:latest", CpuCores: &cpuCores, Memory: &memory,
+ }}}
+
+ var model poolResourceModel
+ var diagnostics diag.Diagnostics
+ model.fromSDKPool(pool, &diagnostics)
+ model.fromSDKTemplate(context.Background(), &template, &diagnostics)
+ if diagnostics.HasError() {
+ t.Fatalf("unexpected diagnostics: %v", diagnostics)
+ }
+ for name, value := range map[string]attr.Value{
+ "command": model.Command,
+ "claim_secrets": model.ClaimSecrets,
+ "ttl_seconds_after_created": model.TTLSecondsAfterCreated,
+ "idle_ttl_seconds": model.IdleTTLSeconds,
+ "ttl_policy": model.TTLPolicy,
+ } {
+ if !value.IsNull() {
+ t.Errorf("%s = %v, want null for an object that never set it", name, value)
+ }
+ }
+}
+
+func TestPoolParityUpdateRoutesByOwningObject(t *testing.T) {
+ state := examplePoolModel()
+ changed := parityPoolModel()
+
+ poolOnly := state
+ poolOnly.TTLSecondsAfterCreated = changed.TTLSecondsAfterCreated
+ poolOnly.IdleTTLSeconds = changed.IdleTTLSeconds
+ poolOnly.TTLPolicy = changed.TTLPolicy
+ if poolOnly.warmPoolAttributesEqual(state) {
+ t.Fatal("lifecycle fields belong to the warm pool but did not register as changed")
+ }
+ if !poolOnly.templateAttributesEqual(state) {
+ t.Fatal("lifecycle fields must not mark the template as changed")
+ }
+
+ templateOnly := state
+ templateOnly.Command = changed.Command
+ templateOnly.ClaimSecrets = changed.ClaimSecrets
+ if templateOnly.templateAttributesEqual(state) {
+ t.Fatal("command/claim_secrets belong to the template but did not register as changed")
+ }
+ if !templateOnly.warmPoolAttributesEqual(state) {
+ t.Fatal("command/claim_secrets must not mark the warm pool as changed")
+ }
+}
diff --git a/libs/fleet/terraform-provider-fleets/internal/provider/pool_resource.go b/libs/fleet/terraform-provider-fleets/internal/provider/pool_resource.go
index 5d309b3dec..0b5e5ae1a5 100644
--- a/libs/fleet/terraform-provider-fleets/internal/provider/pool_resource.go
+++ b/libs/fleet/terraform-provider-fleets/internal/provider/pool_resource.go
@@ -312,12 +312,55 @@ func (m poolResourceModel) toSDKPoolSpec(ctx context.Context, diagnostics *diag.
replicas = initialPoolSize
}
return cyclops_sdk_schema.OsGymSandboxWarmPoolSpec{
- Replicas: replicas,
- SandboxTemplateRef: cyclops_sdk_schema.SandboxTemplateRef{Name: m.templateName()},
- Autoscaling: autoscaling,
+ Replicas: replicas,
+ SandboxTemplateRef: cyclops_sdk_schema.SandboxTemplateRef{Name: m.templateName()},
+ Autoscaling: autoscaling,
+ TtlSecondsAfterCreated: configuredUint32(m.TTLSecondsAfterCreated),
+ IdleTtlSeconds: configuredUint32(m.IdleTTLSeconds),
+ TtlPolicy: configuredTTLPolicy(m.TTLPolicy),
}
}
+func configuredUint32(value types.Int64) *uint32 {
+ if value.IsNull() || value.IsUnknown() {
+ return nil
+ }
+ configured := uint32(value.ValueInt64())
+ return &configured
+}
+
+func configuredTTLPolicy(value types.String) *cyclops_sdk_schema.WarmPoolTtlPolicy {
+ var policy cyclops_sdk_schema.WarmPoolTtlPolicy
+ switch {
+ case value.IsNull() || value.IsUnknown():
+ return nil
+ case value.ValueString() == "Cascade":
+ policy = cyclops_sdk_schema.WarmPoolTtlPolicyCascade
+ default:
+ policy = cyclops_sdk_schema.WarmPoolTtlPolicyRetain
+ }
+ return &policy
+}
+
+func configuredBool(value types.Bool) *bool {
+ if value.IsNull() || value.IsUnknown() {
+ return nil
+ }
+ configured := value.ValueBool()
+ return &configured
+}
+
+// configuredStrings keeps an explicit empty list distinct from an omitted one
+// so what Terraform sends is exactly what it reads back.
+func configuredStrings(ctx context.Context, value types.List, diagnostics *diag.Diagnostics) *[]string {
+ if value.IsNull() || value.IsUnknown() {
+ return nil
+ }
+ configured := []string{}
+ diagnostics.Append(value.ElementsAs(ctx, &configured, false)...)
+ return &configured
+}
+
func (m poolResourceModel) toSDKTemplateSpec(ctx context.Context, diagnostics *diag.Diagnostics) cyclops_sdk_schema.OsGymSandboxTemplateSpec {
services := []cyclops_sdk_schema.SandboxService{}
if !m.Services.IsNull() && !m.Services.IsUnknown() {
@@ -355,6 +398,8 @@ func (m poolResourceModel) toSDKTemplateSpec(ctx context.Context, diagnostics *d
VmTemplate: cyclops_sdk_schema.VmTemplate{
Runtime: runtime, ContainerDiskImage: m.ContainerDiskImage.ValueString(), ImagePullSecret: imagePullSecret,
CpuCores: &cpuCores, Memory: &memory, Firmware: firmware, Probes: probes, Services: &services,
+ Command: configuredStrings(ctx, m.Command, diagnostics),
+ ClaimSecrets: configuredBool(m.ClaimSecrets),
},
}
}
@@ -400,7 +445,10 @@ func (m poolResourceModel) templateName() string {
func (m poolResourceModel) warmPoolAttributesEqual(other poolResourceModel) bool {
return m.Replicas.Equal(other.Replicas) &&
m.TemplateName.Equal(other.TemplateName) &&
- m.Autoscaling.Equal(other.Autoscaling)
+ m.Autoscaling.Equal(other.Autoscaling) &&
+ m.TTLSecondsAfterCreated.Equal(other.TTLSecondsAfterCreated) &&
+ m.IdleTTLSeconds.Equal(other.IdleTTLSeconds) &&
+ m.TTLPolicy.Equal(other.TTLPolicy)
}
func (m poolResourceModel) templateAttributesEqual(other poolResourceModel) bool {
@@ -412,6 +460,8 @@ func (m poolResourceModel) templateAttributesEqual(other poolResourceModel) bool
m.Firmware.Equal(other.Firmware) &&
m.ReadinessProbeJSON.Equal(other.ReadinessProbeJSON) &&
m.LivenessProbeJSON.Equal(other.LivenessProbeJSON) &&
+ m.Command.Equal(other.Command) &&
+ m.ClaimSecrets.Equal(other.ClaimSecrets) &&
m.Services.Equal(other.Services)
}
@@ -421,6 +471,11 @@ func (m *poolResourceModel) fromSDKPool(pool fleet_sdk.Pool, diagnostics *diag.D
m.Namespace = types.StringValue(pool.Metadata.Namespace)
m.TemplateName = types.StringValue(pool.Spec.SandboxTemplateRef.Name)
m.Replicas = types.Int64Value(int64(pool.Spec.Replicas))
+ // Absent lifecycle fields read back as null, so pools created before these
+ // attributes existed plan with no diff.
+ m.TTLSecondsAfterCreated = optionalInt64Value(pool.Spec.TtlSecondsAfterCreated)
+ m.IdleTTLSeconds = optionalInt64Value(pool.Spec.IdleTtlSeconds)
+ m.TTLPolicy = ttlPolicyValue(pool.Spec.TtlPolicy)
if pool.Spec.Autoscaling == nil {
m.Autoscaling = types.ObjectNull(autoscalingObjectType())
} else {
@@ -458,6 +513,12 @@ func (m *poolResourceModel) fromSDKTemplate(ctx context.Context, template *fleet
m.ImagePullSecret = types.StringValue(*vmTemplate.ImagePullSecret)
}
m.Runtime = types.StringValue(runtimeString(vmTemplate.Runtime))
+ m.Command = stringListValue(vmTemplate.Command, diagnostics)
+ if vmTemplate.ClaimSecrets == nil {
+ m.ClaimSecrets = types.BoolNull()
+ } else {
+ m.ClaimSecrets = types.BoolValue(*vmTemplate.ClaimSecrets)
+ }
m.Firmware = types.StringValue(firmwareString(vmTemplate.Firmware))
probes := sdkProbes(vmTemplate.Probes, diagnostics)
m.ReadinessProbeJSON = encodeProbe(probes["readinessProbe"], diagnostics)
@@ -496,6 +557,37 @@ func optionalUint32(value *uint32) int64 {
return int64(*value)
}
+func optionalInt64Value(value *uint32) types.Int64 {
+ if value == nil {
+ return types.Int64Null()
+ }
+ return types.Int64Value(int64(*value))
+}
+
+func ttlPolicyValue(value *cyclops_sdk_schema.WarmPoolTtlPolicy) types.String {
+ switch {
+ case value == nil:
+ return types.StringNull()
+ case *value == cyclops_sdk_schema.WarmPoolTtlPolicyCascade:
+ return types.StringValue("Cascade")
+ default:
+ return types.StringValue("Retain")
+ }
+}
+
+func stringListValue(value *[]string, diagnostics *diag.Diagnostics) types.List {
+ if value == nil {
+ return types.ListNull(types.StringType)
+ }
+ elements := make([]attr.Value, 0, len(*value))
+ for _, item := range *value {
+ elements = append(elements, types.StringValue(item))
+ }
+ list, diags := types.ListValue(types.StringType, elements)
+ diagnostics.Append(diags...)
+ return list
+}
+
func optionalString(value *string) string {
if value == nil {
return ""
diff --git a/libs/fleet/terraform-provider-fleets/internal/provider/pool_resource_acc_test.go b/libs/fleet/terraform-provider-fleets/internal/provider/pool_resource_acc_test.go
index d101be28a7..bae22fb5a9 100644
--- a/libs/fleet/terraform-provider-fleets/internal/provider/pool_resource_acc_test.go
+++ b/libs/fleet/terraform-provider-fleets/internal/provider/pool_resource_acc_test.go
@@ -140,6 +140,45 @@ provider "fleets" {
resource.TestCheckResourceAttr("fleets_pool.test", "autoscaling.max_pool_size", "5"),
),
},
+ {
+ // Every pool/template field Sandbox.create and Pool.apply set,
+ // under the names `cua fleet pool export --terraform` emits.
+ Config: providerConfig + parityPoolConfig(),
+ Check: resource.ComposeAggregateTestCheckFunc(
+ resource.TestCheckResourceAttr("fleets_pool.test", "command.#", "3"),
+ resource.TestCheckResourceAttr("fleets_pool.test", "command.2", "http.server"),
+ resource.TestCheckResourceAttr("fleets_pool.test", "claim_secrets", "true"),
+ resource.TestCheckResourceAttr("fleets_pool.test", "idle_ttl_seconds", "86400"),
+ resource.TestCheckResourceAttr("fleets_pool.test", "ttl_policy", "Cascade"),
+ resource.TestCheckResourceAttr("fleets_pool.test", "ttl_seconds_after_created", "604800"),
+ resource.TestCheckResourceAttr("fleets_pool.test", "autoscaling.min_pool_size", "1"),
+ checkObjectField(dynamicClient, warmPoolGVR, "terraform-e2e", `{"autoscaling":{"initialPoolSize":1,"maxPoolSize":5,"minPoolSize":1},"idleTtlSeconds":86400,"replicas":1,"sandboxTemplateRef":{"name":"terraform-e2e-template"},"ttlPolicy":"Cascade","ttlSecondsAfterCreated":604800}`, "spec"),
+ checkObjectField(dynamicClient, templateGVR, "terraform-e2e-template", `["python","-m","http.server"]`, "spec", "vmTemplate", "command"),
+ checkObjectField(dynamicClient, templateGVR, "terraform-e2e-template", `true`, "spec", "vmTemplate", "claimSecrets"),
+ ),
+ },
+ {
+ ResourceName: "fleets_pool.test",
+ ImportState: true,
+ ImportStateVerify: true,
+ },
+ {
+ // Dropping the attributes clears them on the server too: the SDK
+ // patches them to null rather than leaving the old values.
+ Config: providerConfig + poolConfig(3, "24Gi"),
+ Check: resource.ComposeAggregateTestCheckFunc(
+ resource.TestCheckNoResourceAttr("fleets_pool.test", "command.#"),
+ resource.TestCheckNoResourceAttr("fleets_pool.test", "claim_secrets"),
+ resource.TestCheckNoResourceAttr("fleets_pool.test", "idle_ttl_seconds"),
+ resource.TestCheckNoResourceAttr("fleets_pool.test", "ttl_policy"),
+ resource.TestCheckNoResourceAttr("fleets_pool.test", "ttl_seconds_after_created"),
+ checkObjectFieldAbsent(dynamicClient, warmPoolGVR, "terraform-e2e", "spec", "idleTtlSeconds"),
+ checkObjectFieldAbsent(dynamicClient, warmPoolGVR, "terraform-e2e", "spec", "ttlPolicy"),
+ checkObjectFieldAbsent(dynamicClient, warmPoolGVR, "terraform-e2e", "spec", "ttlSecondsAfterCreated"),
+ checkObjectFieldAbsent(dynamicClient, templateGVR, "terraform-e2e-template", "spec", "vmTemplate", "command"),
+ checkObjectFieldAbsent(dynamicClient, templateGVR, "terraform-e2e-template", "spec", "vmTemplate", "claimSecrets"),
+ ),
+ },
{
Config: providerConfig + poolConfig(3, "24Gi"),
Check: resource.ComposeAggregateTestCheckFunc(
@@ -156,6 +195,113 @@ provider "fleets" {
})
}
+// TestAccPoolLifecycleLegacyImport shows that a pool written before the
+// parity attributes existed (an old provider or SDK: no command, claimSecrets
+// or lifecycle fields) imports and then plans empty against an old-shaped
+// config, so upgrading the provider never proposes a change.
+func TestAccPoolLifecycleLegacyImport(t *testing.T) {
+ if os.Getenv("TF_ACC") == "" {
+ t.Skip("TF_ACC must be set for acceptance tests")
+ }
+ if os.Getenv("KUBEBUILDER_ASSETS") == "" {
+ t.Skip("KUBEBUILDER_ASSETS must point to envtest binaries")
+ }
+
+ testEnvironment := &envtest.Environment{
+ CRDDirectoryPaths: []string{"../../../../clusters/base/osgym/crd.yaml"},
+ ErrorIfCRDPathMissing: true,
+ }
+ config, err := testEnvironment.Start()
+ if err != nil {
+ t.Fatalf("start envtest: %v", err)
+ }
+ t.Cleanup(func() {
+ if err := testEnvironment.Stop(); err != nil {
+ t.Errorf("stop envtest: %v", err)
+ }
+ })
+ clientset, err := kubernetes.NewForConfig(config)
+ if err != nil {
+ t.Fatal(err)
+ }
+ dynamicClient, err := dynamic.NewForConfig(config)
+ if err != nil {
+ t.Fatal(err)
+ }
+ apiServer := newCyclopsTestServer(t, clientset, dynamicClient, nil)
+ defer apiServer.Close()
+
+ // Exactly what the previous provider release wrote for poolConfig(1, "4Gi").
+ ctx := context.Background()
+ if _, err := clientset.CoreV1().Namespaces().Create(ctx, namespaceObject("terraform-e2e"), metav1.CreateOptions{}); err != nil {
+ t.Fatal(err)
+ }
+ for gvr, object := range map[schema.GroupVersionResource]string{
+ warmPoolGVR: `{"apiVersion":"osgym.cua.ai/v1alpha1","kind":"OSGymSandboxWarmPool","metadata":{"name":"terraform-e2e","namespace":"terraform-e2e"},"spec":{"replicas":1,"sandboxTemplateRef":{"name":"terraform-e2e-template"}}}`,
+ templateGVR: `{"apiVersion":"osgym.cua.ai/v1alpha1","kind":"OSGymSandboxTemplate","metadata":{"name":"terraform-e2e-template","namespace":"terraform-e2e"},"spec":{"vmTemplate":{"containerDiskImage":"example.invalid/cyclops/e2e:latest","cpuCores":2,"memory":"4Gi","services":[{"name":"ssh","protocol":"TCP","targetPort":22}]}}}`,
+ } {
+ var legacy unstructured.Unstructured
+ if err := json.Unmarshal([]byte(object), &legacy.Object); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := dynamicClient.Resource(gvr).Namespace("terraform-e2e").Create(ctx, &legacy, metav1.CreateOptions{}); err != nil {
+ t.Fatalf("create legacy %s: %v", gvr.Resource, err)
+ }
+ }
+
+ providerConfig := fmt.Sprintf(`
+provider "fleets" {
+ endpoint = %q
+ client_id = "terraform-e2e"
+ client_secret = "terraform-secret"
+ token_url = %q
+}
+`, apiServer.URL, apiServer.URL+"/token")
+
+ resource.Test(t, resource.TestCase{
+ ProtoV6ProviderFactories: map[string]func() (tfprotov6.ProviderServer, error){
+ "fleets": providerserver.NewProtocol6WithError(fleetsprovider.New("test")()),
+ },
+ Steps: []resource.TestStep{
+ {
+ Config: providerConfig + poolConfig(1, "4Gi"),
+ ResourceName: "fleets_pool.test",
+ ImportState: true,
+ ImportStateId: "terraform-e2e",
+ ImportStatePersist: true,
+ ImportStateCheck: func(states []*terraform.InstanceState) error {
+ if len(states) != 1 {
+ return fmt.Errorf("imported %d resources, want 1", len(states))
+ }
+ for _, key := range []string{"command.#", "claim_secrets", "idle_ttl_seconds", "ttl_policy", "ttl_seconds_after_created"} {
+ if value, ok := states[0].Attributes[key]; ok {
+ return fmt.Errorf("%s = %q on a legacy pool, want unset", key, value)
+ }
+ }
+ return nil
+ },
+ },
+ {
+ Config: providerConfig + poolConfig(1, "4Gi"),
+ ConfigPlanChecks: resource.ConfigPlanChecks{
+ PreApply: []plancheck.PlanCheck{plancheck.ExpectEmptyPlan()},
+ },
+ },
+ {
+ Config: providerConfig + poolConfig(1, "4Gi"),
+ PlanOnly: true,
+ },
+ },
+ })
+ // The empty plan must not have written anything either.
+ for gvr, name := range map[schema.GroupVersionResource]string{warmPoolGVR: "terraform-e2e", templateGVR: "terraform-e2e-template"} {
+ object, err := dynamicClient.Resource(gvr).Namespace("terraform-e2e").Get(ctx, name, metav1.GetOptions{})
+ if err == nil && object.GetGeneration() != 1 {
+ t.Errorf("%s generation = %d, want 1 (untouched)", name, object.GetGeneration())
+ }
+ }
+}
+
func TestAccPoolUnknownResolvedModesRejected(t *testing.T) {
if os.Getenv("TF_ACC") == "" {
t.Skip("TF_ACC must be set for acceptance tests")
@@ -285,6 +431,34 @@ resource "fleets_pool" "test" {
`, replicas, memory)
}
+func parityPoolConfig() string {
+ return `
+resource "fleets_pool" "test" {
+ name = "terraform-e2e"
+ cpu_cores = 2
+ memory = "24Gi"
+ container_disk_image = "example.invalid/cyclops/e2e:latest"
+ command = ["python", "-m", "http.server"]
+ claim_secrets = true
+ idle_ttl_seconds = 86400
+ ttl_policy = "Cascade"
+ ttl_seconds_after_created = 604800
+
+ autoscaling {
+ min_pool_size = 1
+ initial_pool_size = 1
+ max_pool_size = 5
+ }
+
+ service {
+ name = "ssh"
+ target_port = 22
+ protocol = "TCP"
+ }
+}
+`
+}
+
func autoscaledPoolConfig(memory string) string {
return fmt.Sprintf(`
resource "fleets_pool" "test" {
@@ -408,6 +582,46 @@ func setWarmPoolReplicas(dynamicClient dynamic.Interface, replicas int64) resour
}
}
+// checkObjectField compares the JSON of a field of a live object.
+func checkObjectField(dynamicClient dynamic.Interface, gvr schema.GroupVersionResource, name, want string, fields ...string) resource.TestCheckFunc {
+ return func(*terraform.State) error {
+ object, err := dynamicClient.Resource(gvr).Namespace("terraform-e2e").Get(context.Background(), name, metav1.GetOptions{})
+ if err != nil {
+ return err
+ }
+ value, found, err := unstructured.NestedFieldNoCopy(object.Object, fields...)
+ if err != nil || !found {
+ return fmt.Errorf("%s %s: field %v missing (%v)", gvr.Resource, name, fields, err)
+ }
+ got, err := json.Marshal(value)
+ if err != nil {
+ return err
+ }
+ var wantValue any
+ if err := json.Unmarshal([]byte(want), &wantValue); err != nil {
+ return err
+ }
+ wantJSON, _ := json.Marshal(wantValue)
+ if string(got) != string(wantJSON) {
+ return fmt.Errorf("%s %s %v = %s, want %s", gvr.Resource, name, fields, got, wantJSON)
+ }
+ return nil
+ }
+}
+
+func checkObjectFieldAbsent(dynamicClient dynamic.Interface, gvr schema.GroupVersionResource, name string, fields ...string) resource.TestCheckFunc {
+ return func(*terraform.State) error {
+ object, err := dynamicClient.Resource(gvr).Namespace("terraform-e2e").Get(context.Background(), name, metav1.GetOptions{})
+ if err != nil {
+ return err
+ }
+ if value, found, _ := unstructured.NestedFieldNoCopy(object.Object, fields...); found {
+ return fmt.Errorf("%s %s %v = %v, want it cleared", gvr.Resource, name, fields, value)
+ }
+ return nil
+ }
+}
+
func namespaceObject(name string) *corev1.Namespace {
return &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: name}}
}
diff --git a/libs/fleet/terraform-provider-fleets/internal/provider/pool_sdk_test.go b/libs/fleet/terraform-provider-fleets/internal/provider/pool_sdk_test.go
index fde839157e..4da0aab85d 100644
--- a/libs/fleet/terraform-provider-fleets/internal/provider/pool_sdk_test.go
+++ b/libs/fleet/terraform-provider-fleets/internal/provider/pool_sdk_test.go
@@ -26,6 +26,13 @@ func examplePoolModel() poolResourceModel {
Firmware: types.StringValue("bios"),
Services: types.SetNull(types.ObjectType{AttrTypes: serviceObjectType()}),
Autoscaling: types.ObjectNull(autoscalingObjectType()),
+ Command: types.ListNull(types.StringType),
+ ClaimSecrets: types.BoolNull(),
+ // Lifecycle attributes default to null: what a pool created before
+ // they existed reads back as.
+ TTLSecondsAfterCreated: types.Int64Null(),
+ IdleTTLSeconds: types.Int64Null(),
+ TTLPolicy: types.StringNull(),
}
}