diff --git a/CHANGELOG.md b/CHANGELOG.md index 1cd550638..8d0da2a44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ ## [Unreleased] +- Update `elasticstack_fleet_output` to use new API schema format ([#434](https://github.com/elastic/terraform-provider-elasticstack/pull/434)) + ## [0.8.0] - 2023-09-26 ### Added diff --git a/docs/resources/fleet_output.md b/docs/resources/fleet_output.md index 7482ed1f3..8a095da0a 100644 --- a/docs/resources/fleet_output.md +++ b/docs/resources/fleet_output.md @@ -42,6 +42,7 @@ resource "elasticstack_fleet_output" "test_output" { ### Optional - `ca_sha256` (String) Fingerprint of the Elasticsearch CA certificate. +- `ca_trusted_fingerprint` (String) Fingerprint of trusted CA. - `config_yaml` (String, Sensitive) Advanced YAML configuration. YAML settings here will be added to the output section of each agent policy. - `default_integrations` (Boolean) Make this output the default for agent integrations. - `default_monitoring` (Boolean) Make this output the default for agent monitoring. diff --git a/internal/clients/fleet/fleetapi/.gitignore b/generated/fleet/.gitignore similarity index 100% rename from internal/clients/fleet/fleetapi/.gitignore rename to generated/fleet/.gitignore diff --git a/internal/clients/fleet/fleetapi/client_gen.go b/generated/fleet/fleet.gen.go similarity index 57% rename from internal/clients/fleet/fleetapi/client_gen.go rename to generated/fleet/fleet.gen.go index aaff4a5f8..281424c55 100644 --- a/internal/clients/fleet/fleetapi/client_gen.go +++ b/generated/fleet/fleet.gen.go @@ -1,21 +1,821 @@ -// Package fleetapi provides primitives to interact with the openapi HTTP API. +// Package fleet provides primitives to interact with the openapi HTTP API. // // Code generated by github.com/deepmap/oapi-codegen version v1.14.0 DO NOT EDIT. -package fleetapi +package fleet import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "net/http" "net/url" "strings" + "time" "github.com/oapi-codegen/runtime" ) +const ( + BasicAuthScopes = "basicAuth.Scopes" +) + +// Defines values for AgentPolicyMonitoringEnabled. +const ( + AgentPolicyMonitoringEnabledLogs AgentPolicyMonitoringEnabled = "logs" + AgentPolicyMonitoringEnabledMetrics AgentPolicyMonitoringEnabled = "metrics" +) + +// Defines values for AgentPolicyCreateRequestMonitoringEnabled. +const ( + AgentPolicyCreateRequestMonitoringEnabledLogs AgentPolicyCreateRequestMonitoringEnabled = "logs" + AgentPolicyCreateRequestMonitoringEnabledMetrics AgentPolicyCreateRequestMonitoringEnabled = "metrics" +) + +// Defines values for AgentPolicyUpdateRequestMonitoringEnabled. +const ( + Logs AgentPolicyUpdateRequestMonitoringEnabled = "logs" + Metrics AgentPolicyUpdateRequestMonitoringEnabled = "metrics" +) + +// Defines values for OutputCreateRequestElasticsearchType. +const ( + OutputCreateRequestElasticsearchTypeElasticsearch OutputCreateRequestElasticsearchType = "elasticsearch" +) + +// Defines values for OutputCreateRequestKafkaConnectionType. +const ( + OutputCreateRequestKafkaConnectionTypeEncryption OutputCreateRequestKafkaConnectionType = "encryption" + OutputCreateRequestKafkaConnectionTypePlaintext OutputCreateRequestKafkaConnectionType = "plaintext" +) + +// Defines values for OutputCreateRequestKafkaSslVerificationMode. +const ( + OutputCreateRequestKafkaSslVerificationModeCertificate OutputCreateRequestKafkaSslVerificationMode = "certificate" + OutputCreateRequestKafkaSslVerificationModeFull OutputCreateRequestKafkaSslVerificationMode = "full" + OutputCreateRequestKafkaSslVerificationModeNone OutputCreateRequestKafkaSslVerificationMode = "none" + OutputCreateRequestKafkaSslVerificationModeStrict OutputCreateRequestKafkaSslVerificationMode = "strict" +) + +// Defines values for OutputCreateRequestKafkaType. +const ( + OutputCreateRequestKafkaTypeKafka OutputCreateRequestKafkaType = "kafka" +) + +// Defines values for OutputCreateRequestLogstashType. +const ( + OutputCreateRequestLogstashTypeLogstash OutputCreateRequestLogstashType = "logstash" +) + +// Defines values for OutputUpdateRequestElasticsearchType. +const ( + OutputUpdateRequestElasticsearchTypeElasticsearch OutputUpdateRequestElasticsearchType = "elasticsearch" +) + +// Defines values for OutputUpdateRequestKafkaConnectionType. +const ( + OutputUpdateRequestKafkaConnectionTypeEncryption OutputUpdateRequestKafkaConnectionType = "encryption" + OutputUpdateRequestKafkaConnectionTypePlaintext OutputUpdateRequestKafkaConnectionType = "plaintext" +) + +// Defines values for OutputUpdateRequestKafkaSslVerificationMode. +const ( + OutputUpdateRequestKafkaSslVerificationModeCertificate OutputUpdateRequestKafkaSslVerificationMode = "certificate" + OutputUpdateRequestKafkaSslVerificationModeFull OutputUpdateRequestKafkaSslVerificationMode = "full" + OutputUpdateRequestKafkaSslVerificationModeNone OutputUpdateRequestKafkaSslVerificationMode = "none" + OutputUpdateRequestKafkaSslVerificationModeStrict OutputUpdateRequestKafkaSslVerificationMode = "strict" +) + +// Defines values for OutputUpdateRequestKafkaType. +const ( + OutputUpdateRequestKafkaTypeKafka OutputUpdateRequestKafkaType = "kafka" +) + +// Defines values for OutputUpdateRequestLogstashType. +const ( + OutputUpdateRequestLogstashTypeLogstash OutputUpdateRequestLogstashType = "logstash" +) + +// AgentPolicy defines model for agent_policy. +type AgentPolicy struct { + AgentFeatures *[]struct { + Enabled bool `json:"enabled"` + Name string `json:"name"` + } `json:"agent_features,omitempty"` + Agents *float32 `json:"agents,omitempty"` + DataOutputId *string `json:"data_output_id"` + Description *string `json:"description,omitempty"` + DownloadSourceId *string `json:"download_source_id"` + FleetServerHostId *string `json:"fleet_server_host_id"` + Id string `json:"id"` + InactivityTimeout *float32 `json:"inactivity_timeout,omitempty"` + + // IsProtected Indicates whether the agent policy has tamper protection enabled. Default false. + IsProtected *bool `json:"is_protected,omitempty"` + MonitoringEnabled *[]AgentPolicyMonitoringEnabled `json:"monitoring_enabled,omitempty"` + MonitoringOutputId *string `json:"monitoring_output_id"` + Name string `json:"name"` + Namespace string `json:"namespace"` + + // Overrides Override settings that are defined in the agent policy. Input settings cannot be overridden. The override option should be used only in unusual circumstances and not as a routine procedure. + Overrides *map[string]interface{} `json:"overrides"` + + // PackagePolicies This field is present only when retrieving a single agent policy, or when retrieving a list of agent policies with the ?full=true parameter + PackagePolicies *[]PackagePolicy `json:"package_policies,omitempty"` + Revision *float32 `json:"revision,omitempty"` + UnenrollTimeout *float32 `json:"unenroll_timeout,omitempty"` + UpdatedBy *string `json:"updated_by,omitempty"` + UpdatedOn *time.Time `json:"updated_on,omitempty"` +} + +// AgentPolicyMonitoringEnabled defines model for AgentPolicy.MonitoringEnabled. +type AgentPolicyMonitoringEnabled string + +// AgentPolicyCreateRequest defines model for agent_policy_create_request. +type AgentPolicyCreateRequest struct { + AgentFeatures *[]struct { + Enabled bool `json:"enabled"` + Name string `json:"name"` + } `json:"agent_features,omitempty"` + DataOutputId *string `json:"data_output_id"` + Description *string `json:"description,omitempty"` + DownloadSourceId *string `json:"download_source_id"` + FleetServerHostId *string `json:"fleet_server_host_id"` + Id *string `json:"id,omitempty"` + InactivityTimeout *float32 `json:"inactivity_timeout,omitempty"` + IsProtected *bool `json:"is_protected,omitempty"` + MonitoringEnabled *[]AgentPolicyCreateRequestMonitoringEnabled `json:"monitoring_enabled,omitempty"` + MonitoringOutputId *string `json:"monitoring_output_id"` + Name string `json:"name"` + Namespace string `json:"namespace"` + UnenrollTimeout *float32 `json:"unenroll_timeout,omitempty"` +} + +// AgentPolicyCreateRequestMonitoringEnabled defines model for AgentPolicyCreateRequest.MonitoringEnabled. +type AgentPolicyCreateRequestMonitoringEnabled string + +// AgentPolicyUpdateRequest defines model for agent_policy_update_request. +type AgentPolicyUpdateRequest struct { + AgentFeatures *[]struct { + Enabled bool `json:"enabled"` + Name string `json:"name"` + } `json:"agent_features,omitempty"` + DataOutputId *string `json:"data_output_id"` + Description *string `json:"description,omitempty"` + DownloadSourceId *string `json:"download_source_id"` + FleetServerHostId *string `json:"fleet_server_host_id"` + InactivityTimeout *float32 `json:"inactivity_timeout,omitempty"` + IsProtected *bool `json:"is_protected,omitempty"` + MonitoringEnabled *[]AgentPolicyUpdateRequestMonitoringEnabled `json:"monitoring_enabled,omitempty"` + MonitoringOutputId *string `json:"monitoring_output_id"` + Name string `json:"name"` + Namespace string `json:"namespace"` + UnenrollTimeout *float32 `json:"unenroll_timeout,omitempty"` +} + +// AgentPolicyUpdateRequestMonitoringEnabled defines model for AgentPolicyUpdateRequest.MonitoringEnabled. +type AgentPolicyUpdateRequestMonitoringEnabled string + +// EnrollmentApiKey defines model for enrollment_api_key. +type EnrollmentApiKey struct { + Active bool `json:"active"` + ApiKey string `json:"api_key"` + ApiKeyId string `json:"api_key_id"` + CreatedAt string `json:"created_at"` + Id string `json:"id"` + Name *string `json:"name,omitempty"` + PolicyId *string `json:"policy_id,omitempty"` +} + +// FleetServerHost defines model for fleet_server_host. +type FleetServerHost struct { + HostUrls []string `json:"host_urls"` + Id string `json:"id"` + IsDefault bool `json:"is_default"` + IsPreconfigured bool `json:"is_preconfigured"` + Name *string `json:"name,omitempty"` +} + +// NewPackagePolicy defines model for new_package_policy. +type NewPackagePolicy struct { + Description *string `json:"description,omitempty"` + Enabled *bool `json:"enabled,omitempty"` + Inputs []struct { + Config *map[string]interface{} `json:"config,omitempty"` + Enabled bool `json:"enabled"` + Processors *[]string `json:"processors,omitempty"` + Streams *[]interface{} `json:"streams,omitempty"` + Type string `json:"type"` + Vars *map[string]interface{} `json:"vars,omitempty"` + } `json:"inputs"` + Name string `json:"name"` + Namespace *string `json:"namespace,omitempty"` + // Deprecated: + OutputId *string `json:"output_id,omitempty"` + Package *struct { + Name string `json:"name"` + Title *string `json:"title,omitempty"` + Version string `json:"version"` + } `json:"package,omitempty"` + PolicyId *string `json:"policy_id,omitempty"` +} + +// OutputCreateRequest defines model for output_create_request. +type OutputCreateRequest struct { + union json.RawMessage +} + +// OutputCreateRequestElasticsearch defines model for output_create_request_elasticsearch. +type OutputCreateRequestElasticsearch struct { + CaSha256 *string `json:"ca_sha256,omitempty"` + CaTrustedFingerprint *string `json:"ca_trusted_fingerprint,omitempty"` + Config *map[string]interface{} `json:"config,omitempty"` + ConfigYaml *string `json:"config_yaml,omitempty"` + Hosts *[]string `json:"hosts,omitempty"` + Id *string `json:"id,omitempty"` + IsDefault *bool `json:"is_default,omitempty"` + IsDefaultMonitoring *bool `json:"is_default_monitoring,omitempty"` + Name string `json:"name"` + ProxyId *string `json:"proxy_id,omitempty"` + Shipper *struct { + CompressionLevel *float32 `json:"compression_level,omitempty"` + DiskQueueCompressionEnabled *bool `json:"disk_queue_compression_enabled,omitempty"` + DiskQueueEnabled *bool `json:"disk_queue_enabled,omitempty"` + DiskQueueEncryptionEnabled *bool `json:"disk_queue_encryption_enabled,omitempty"` + DiskQueueMaxSize *float32 `json:"disk_queue_max_size,omitempty"` + DiskQueuePath *string `json:"disk_queue_path,omitempty"` + Loadbalance *bool `json:"loadbalance,omitempty"` + } `json:"shipper,omitempty"` + Ssl *struct { + Certificate *string `json:"certificate,omitempty"` + CertificateAuthorities *[]string `json:"certificate_authorities,omitempty"` + Key *string `json:"key,omitempty"` + } `json:"ssl,omitempty"` + Type OutputCreateRequestElasticsearchType `json:"type"` +} + +// OutputCreateRequestElasticsearchType defines model for OutputCreateRequestElasticsearch.Type. +type OutputCreateRequestElasticsearchType string + +// OutputCreateRequestKafka defines model for output_create_request_kafka. +type OutputCreateRequestKafka struct { + AuthType string `json:"auth_type"` + BrokerTimeout *float32 `json:"broker_timeout,omitempty"` + CaSha256 *string `json:"ca_sha256,omitempty"` + CaTrustedFingerprint *string `json:"ca_trusted_fingerprint,omitempty"` + ClientId *string `json:"client_id,omitempty"` + Compression *string `json:"compression,omitempty"` + CompressionLevel *float32 `json:"compression_level,omitempty"` + Config *map[string]interface{} `json:"config,omitempty"` + ConfigYaml *string `json:"config_yaml,omitempty"` + ConnectionType *OutputCreateRequestKafkaConnectionType `json:"connection_type,omitempty"` + Headers *[]struct { + Key *string `json:"key,omitempty"` + Value *string `json:"value,omitempty"` + } `json:"headers,omitempty"` + Hosts []string `json:"hosts"` + Id *string `json:"id,omitempty"` + IsDefault *bool `json:"is_default,omitempty"` + IsDefaultMonitoring *bool `json:"is_default_monitoring,omitempty"` + Key *string `json:"key,omitempty"` + Name string `json:"name"` + Partition *string `json:"partition,omitempty"` + Password *string `json:"password,omitempty"` + ProxyId *string `json:"proxy_id,omitempty"` + Random *struct { + GroupEvents *float32 `json:"group_events,omitempty"` + } `json:"random,omitempty"` + RequiredAcks *float32 `json:"required_acks,omitempty"` + RoundRobin *struct { + GroupEvents *float32 `json:"group_events,omitempty"` + } `json:"round_robin,omitempty"` + Sasl *struct { + Mechanism *string `json:"mechanism,omitempty"` + } `json:"sasl,omitempty"` + Shipper *struct { + CompressionLevel *float32 `json:"compression_level,omitempty"` + DiskQueueCompressionEnabled *bool `json:"disk_queue_compression_enabled,omitempty"` + DiskQueueEnabled *bool `json:"disk_queue_enabled,omitempty"` + DiskQueueEncryptionEnabled *bool `json:"disk_queue_encryption_enabled,omitempty"` + DiskQueueMaxSize *float32 `json:"disk_queue_max_size,omitempty"` + DiskQueuePath *string `json:"disk_queue_path,omitempty"` + Loadbalance *bool `json:"loadbalance,omitempty"` + } `json:"shipper,omitempty"` + Ssl *struct { + Certificate *string `json:"certificate,omitempty"` + CertificateAuthorities *[]string `json:"certificate_authorities,omitempty"` + Key *string `json:"key,omitempty"` + VerificationMode *OutputCreateRequestKafkaSslVerificationMode `json:"verification_mode,omitempty"` + } `json:"ssl,omitempty"` + Timeout *float32 `json:"timeout,omitempty"` + Topics []struct { + Topic *string `json:"topic,omitempty"` + When *struct { + Condition *string `json:"condition,omitempty"` + Type *string `json:"type,omitempty"` + } `json:"when,omitempty"` + } `json:"topics"` + Type OutputCreateRequestKafkaType `json:"type"` + Username *string `json:"username,omitempty"` + Version *string `json:"version,omitempty"` +} + +// OutputCreateRequestKafkaConnectionType defines model for OutputCreateRequestKafka.ConnectionType. +type OutputCreateRequestKafkaConnectionType string + +// OutputCreateRequestKafkaSslVerificationMode defines model for OutputCreateRequestKafka.Ssl.VerificationMode. +type OutputCreateRequestKafkaSslVerificationMode string + +// OutputCreateRequestKafkaType defines model for OutputCreateRequestKafka.Type. +type OutputCreateRequestKafkaType string + +// OutputCreateRequestLogstash defines model for output_create_request_logstash. +type OutputCreateRequestLogstash struct { + CaSha256 *string `json:"ca_sha256,omitempty"` + CaTrustedFingerprint *string `json:"ca_trusted_fingerprint,omitempty"` + Config *map[string]interface{} `json:"config,omitempty"` + ConfigYaml *string `json:"config_yaml,omitempty"` + Hosts []string `json:"hosts"` + Id *string `json:"id,omitempty"` + IsDefault *bool `json:"is_default,omitempty"` + IsDefaultMonitoring *bool `json:"is_default_monitoring,omitempty"` + Name string `json:"name"` + ProxyId *string `json:"proxy_id,omitempty"` + Shipper *struct { + CompressionLevel *float32 `json:"compression_level,omitempty"` + DiskQueueCompressionEnabled *bool `json:"disk_queue_compression_enabled,omitempty"` + DiskQueueEnabled *bool `json:"disk_queue_enabled,omitempty"` + DiskQueueEncryptionEnabled *bool `json:"disk_queue_encryption_enabled,omitempty"` + DiskQueueMaxSize *float32 `json:"disk_queue_max_size,omitempty"` + DiskQueuePath *string `json:"disk_queue_path,omitempty"` + Loadbalance *bool `json:"loadbalance,omitempty"` + } `json:"shipper,omitempty"` + Ssl *struct { + Certificate *string `json:"certificate,omitempty"` + CertificateAuthorities *[]string `json:"certificate_authorities,omitempty"` + Key *string `json:"key,omitempty"` + } `json:"ssl,omitempty"` + Type OutputCreateRequestLogstashType `json:"type"` +} + +// OutputCreateRequestLogstashType defines model for OutputCreateRequestLogstash.Type. +type OutputCreateRequestLogstashType string + +// OutputUpdateRequest defines model for output_update_request. +type OutputUpdateRequest struct { + union json.RawMessage +} + +// OutputUpdateRequestElasticsearch defines model for output_update_request_elasticsearch. +type OutputUpdateRequestElasticsearch struct { + CaSha256 *string `json:"ca_sha256,omitempty"` + CaTrustedFingerprint *string `json:"ca_trusted_fingerprint,omitempty"` + Config *map[string]interface{} `json:"config,omitempty"` + ConfigYaml *string `json:"config_yaml,omitempty"` + Hosts []string `json:"hosts"` + Id *string `json:"id,omitempty"` + IsDefault *bool `json:"is_default,omitempty"` + IsDefaultMonitoring *bool `json:"is_default_monitoring,omitempty"` + Name string `json:"name"` + ProxyId *string `json:"proxy_id,omitempty"` + Shipper *struct { + CompressionLevel *float32 `json:"compression_level,omitempty"` + DiskQueueCompressionEnabled *bool `json:"disk_queue_compression_enabled,omitempty"` + DiskQueueEnabled *bool `json:"disk_queue_enabled,omitempty"` + DiskQueueEncryptionEnabled *bool `json:"disk_queue_encryption_enabled,omitempty"` + DiskQueueMaxSize *float32 `json:"disk_queue_max_size,omitempty"` + DiskQueuePath *string `json:"disk_queue_path,omitempty"` + Loadbalance *bool `json:"loadbalance,omitempty"` + } `json:"shipper,omitempty"` + Ssl *struct { + Certificate *string `json:"certificate,omitempty"` + CertificateAuthorities *[]string `json:"certificate_authorities,omitempty"` + Key *string `json:"key,omitempty"` + } `json:"ssl,omitempty"` + Type OutputUpdateRequestElasticsearchType `json:"type"` +} + +// OutputUpdateRequestElasticsearchType defines model for OutputUpdateRequestElasticsearch.Type. +type OutputUpdateRequestElasticsearchType string + +// OutputUpdateRequestKafka defines model for output_update_request_kafka. +type OutputUpdateRequestKafka struct { + AuthType *string `json:"auth_type,omitempty"` + BrokerTimeout *float32 `json:"broker_timeout,omitempty"` + CaSha256 *string `json:"ca_sha256,omitempty"` + CaTrustedFingerprint *string `json:"ca_trusted_fingerprint,omitempty"` + ClientId *string `json:"client_id,omitempty"` + Compression *string `json:"compression,omitempty"` + CompressionLevel *float32 `json:"compression_level,omitempty"` + Config *map[string]interface{} `json:"config,omitempty"` + ConfigYaml *string `json:"config_yaml,omitempty"` + ConnectionType *OutputUpdateRequestKafkaConnectionType `json:"connection_type,omitempty"` + Headers *[]struct { + Key *string `json:"key,omitempty"` + Value *string `json:"value,omitempty"` + } `json:"headers,omitempty"` + Hosts *[]string `json:"hosts,omitempty"` + Id *string `json:"id,omitempty"` + IsDefault *bool `json:"is_default,omitempty"` + IsDefaultMonitoring *bool `json:"is_default_monitoring,omitempty"` + Key *string `json:"key,omitempty"` + Name string `json:"name"` + Partition *string `json:"partition,omitempty"` + Password *string `json:"password,omitempty"` + ProxyId *string `json:"proxy_id,omitempty"` + Random *struct { + GroupEvents *float32 `json:"group_events,omitempty"` + } `json:"random,omitempty"` + RequiredAcks *float32 `json:"required_acks,omitempty"` + RoundRobin *struct { + GroupEvents *float32 `json:"group_events,omitempty"` + } `json:"round_robin,omitempty"` + Sasl *struct { + Mechanism *string `json:"mechanism,omitempty"` + } `json:"sasl,omitempty"` + Shipper *struct { + CompressionLevel *float32 `json:"compression_level,omitempty"` + DiskQueueCompressionEnabled *bool `json:"disk_queue_compression_enabled,omitempty"` + DiskQueueEnabled *bool `json:"disk_queue_enabled,omitempty"` + DiskQueueEncryptionEnabled *bool `json:"disk_queue_encryption_enabled,omitempty"` + DiskQueueMaxSize *float32 `json:"disk_queue_max_size,omitempty"` + DiskQueuePath *string `json:"disk_queue_path,omitempty"` + Loadbalance *bool `json:"loadbalance,omitempty"` + } `json:"shipper,omitempty"` + Ssl *struct { + Certificate *string `json:"certificate,omitempty"` + CertificateAuthorities *[]string `json:"certificate_authorities,omitempty"` + Key *string `json:"key,omitempty"` + VerificationMode *OutputUpdateRequestKafkaSslVerificationMode `json:"verification_mode,omitempty"` + } `json:"ssl,omitempty"` + Timeout *float32 `json:"timeout,omitempty"` + Topics *[]struct { + Topic *string `json:"topic,omitempty"` + When *struct { + Condition *string `json:"condition,omitempty"` + Type *string `json:"type,omitempty"` + } `json:"when,omitempty"` + } `json:"topics,omitempty"` + Type OutputUpdateRequestKafkaType `json:"type"` + Username *string `json:"username,omitempty"` + Version *string `json:"version,omitempty"` +} + +// OutputUpdateRequestKafkaConnectionType defines model for OutputUpdateRequestKafka.ConnectionType. +type OutputUpdateRequestKafkaConnectionType string + +// OutputUpdateRequestKafkaSslVerificationMode defines model for OutputUpdateRequestKafka.Ssl.VerificationMode. +type OutputUpdateRequestKafkaSslVerificationMode string + +// OutputUpdateRequestKafkaType defines model for OutputUpdateRequestKafka.Type. +type OutputUpdateRequestKafkaType string + +// OutputUpdateRequestLogstash defines model for output_update_request_logstash. +type OutputUpdateRequestLogstash struct { + CaSha256 *string `json:"ca_sha256,omitempty"` + CaTrustedFingerprint *string `json:"ca_trusted_fingerprint,omitempty"` + Config *map[string]interface{} `json:"config,omitempty"` + ConfigYaml *string `json:"config_yaml,omitempty"` + Hosts *[]string `json:"hosts,omitempty"` + Id *string `json:"id,omitempty"` + IsDefault *bool `json:"is_default,omitempty"` + IsDefaultMonitoring *bool `json:"is_default_monitoring,omitempty"` + Name string `json:"name"` + ProxyId *string `json:"proxy_id,omitempty"` + Shipper *struct { + CompressionLevel *float32 `json:"compression_level,omitempty"` + DiskQueueCompressionEnabled *bool `json:"disk_queue_compression_enabled,omitempty"` + DiskQueueEnabled *bool `json:"disk_queue_enabled,omitempty"` + DiskQueueEncryptionEnabled *bool `json:"disk_queue_encryption_enabled,omitempty"` + DiskQueueMaxSize *float32 `json:"disk_queue_max_size,omitempty"` + DiskQueuePath *string `json:"disk_queue_path,omitempty"` + Loadbalance *bool `json:"loadbalance,omitempty"` + } `json:"shipper,omitempty"` + Ssl *struct { + Certificate *string `json:"certificate,omitempty"` + CertificateAuthorities *[]string `json:"certificate_authorities,omitempty"` + Key *string `json:"key,omitempty"` + } `json:"ssl,omitempty"` + Type OutputUpdateRequestLogstashType `json:"type"` +} + +// OutputUpdateRequestLogstashType defines model for OutputUpdateRequestLogstash.Type. +type OutputUpdateRequestLogstashType string + +// PackagePolicy defines model for package_policy. +type PackagePolicy struct { + Description *string `json:"description,omitempty"` + Enabled *bool `json:"enabled,omitempty"` + Id string `json:"id"` + Inputs []struct { + Config *map[string]interface{} `json:"config,omitempty"` + Enabled bool `json:"enabled"` + Processors *[]string `json:"processors,omitempty"` + Streams *[]interface{} `json:"streams,omitempty"` + Type string `json:"type"` + Vars *map[string]interface{} `json:"vars,omitempty"` + } `json:"inputs"` + Name string `json:"name"` + Namespace *string `json:"namespace,omitempty"` + // Deprecated: + OutputId *string `json:"output_id,omitempty"` + Package *struct { + Name string `json:"name"` + Title *string `json:"title,omitempty"` + Version string `json:"version"` + } `json:"package,omitempty"` + PolicyId *string `json:"policy_id,omitempty"` + Revision float32 `json:"revision"` +} + +// Error defines model for error. +type Error struct { + Error *string `json:"error,omitempty"` + Message *string `json:"message,omitempty"` + StatusCode *float32 `json:"statusCode,omitempty"` +} + +// DeleteAgentPolicyJSONBody defines parameters for DeleteAgentPolicy. +type DeleteAgentPolicyJSONBody struct { + AgentPolicyId string `json:"agentPolicyId"` +} + +// PostFleetServerHostsJSONBody defines parameters for PostFleetServerHosts. +type PostFleetServerHostsJSONBody struct { + HostUrls []string `json:"host_urls"` + Id *string `json:"id,omitempty"` + IsDefault *bool `json:"is_default,omitempty"` + Name string `json:"name"` +} + +// UpdateFleetServerHostsJSONBody defines parameters for UpdateFleetServerHosts. +type UpdateFleetServerHostsJSONBody struct { + HostUrls *[]string `json:"host_urls,omitempty"` + IsDefault *bool `json:"is_default,omitempty"` + Name *string `json:"name,omitempty"` +} + +// CreateAgentPolicyJSONRequestBody defines body for CreateAgentPolicy for application/json ContentType. +type CreateAgentPolicyJSONRequestBody = AgentPolicyCreateRequest + +// DeleteAgentPolicyJSONRequestBody defines body for DeleteAgentPolicy for application/json ContentType. +type DeleteAgentPolicyJSONRequestBody DeleteAgentPolicyJSONBody + +// UpdateAgentPolicyJSONRequestBody defines body for UpdateAgentPolicy for application/json ContentType. +type UpdateAgentPolicyJSONRequestBody = AgentPolicyUpdateRequest + +// PostFleetServerHostsJSONRequestBody defines body for PostFleetServerHosts for application/json ContentType. +type PostFleetServerHostsJSONRequestBody PostFleetServerHostsJSONBody + +// UpdateFleetServerHostsJSONRequestBody defines body for UpdateFleetServerHosts for application/json ContentType. +type UpdateFleetServerHostsJSONRequestBody UpdateFleetServerHostsJSONBody + +// PostOutputsJSONRequestBody defines body for PostOutputs for application/json ContentType. +type PostOutputsJSONRequestBody = OutputCreateRequest + +// UpdateOutputJSONRequestBody defines body for UpdateOutput for application/json ContentType. +type UpdateOutputJSONRequestBody = OutputUpdateRequest + +// AsOutputCreateRequestElasticsearch returns the union data inside the OutputCreateRequest as a OutputCreateRequestElasticsearch +func (t OutputCreateRequest) AsOutputCreateRequestElasticsearch() (OutputCreateRequestElasticsearch, error) { + var body OutputCreateRequestElasticsearch + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromOutputCreateRequestElasticsearch overwrites any union data inside the OutputCreateRequest as the provided OutputCreateRequestElasticsearch +func (t *OutputCreateRequest) FromOutputCreateRequestElasticsearch(v OutputCreateRequestElasticsearch) error { + v.Type = "elasticsearch" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeOutputCreateRequestElasticsearch performs a merge with any union data inside the OutputCreateRequest, using the provided OutputCreateRequestElasticsearch +func (t *OutputCreateRequest) MergeOutputCreateRequestElasticsearch(v OutputCreateRequestElasticsearch) error { + v.Type = "elasticsearch" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JsonMerge(t.union, b) + t.union = merged + return err +} + +// AsOutputCreateRequestKafka returns the union data inside the OutputCreateRequest as a OutputCreateRequestKafka +func (t OutputCreateRequest) AsOutputCreateRequestKafka() (OutputCreateRequestKafka, error) { + var body OutputCreateRequestKafka + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromOutputCreateRequestKafka overwrites any union data inside the OutputCreateRequest as the provided OutputCreateRequestKafka +func (t *OutputCreateRequest) FromOutputCreateRequestKafka(v OutputCreateRequestKafka) error { + v.Type = "kafka" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeOutputCreateRequestKafka performs a merge with any union data inside the OutputCreateRequest, using the provided OutputCreateRequestKafka +func (t *OutputCreateRequest) MergeOutputCreateRequestKafka(v OutputCreateRequestKafka) error { + v.Type = "kafka" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JsonMerge(t.union, b) + t.union = merged + return err +} + +// AsOutputCreateRequestLogstash returns the union data inside the OutputCreateRequest as a OutputCreateRequestLogstash +func (t OutputCreateRequest) AsOutputCreateRequestLogstash() (OutputCreateRequestLogstash, error) { + var body OutputCreateRequestLogstash + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromOutputCreateRequestLogstash overwrites any union data inside the OutputCreateRequest as the provided OutputCreateRequestLogstash +func (t *OutputCreateRequest) FromOutputCreateRequestLogstash(v OutputCreateRequestLogstash) error { + v.Type = "logstash" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeOutputCreateRequestLogstash performs a merge with any union data inside the OutputCreateRequest, using the provided OutputCreateRequestLogstash +func (t *OutputCreateRequest) MergeOutputCreateRequestLogstash(v OutputCreateRequestLogstash) error { + v.Type = "logstash" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JsonMerge(t.union, b) + t.union = merged + return err +} + +func (t OutputCreateRequest) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t OutputCreateRequest) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "elasticsearch": + return t.AsOutputCreateRequestElasticsearch() + case "kafka": + return t.AsOutputCreateRequestKafka() + case "logstash": + return t.AsOutputCreateRequestLogstash() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t OutputCreateRequest) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *OutputCreateRequest) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsOutputUpdateRequestElasticsearch returns the union data inside the OutputUpdateRequest as a OutputUpdateRequestElasticsearch +func (t OutputUpdateRequest) AsOutputUpdateRequestElasticsearch() (OutputUpdateRequestElasticsearch, error) { + var body OutputUpdateRequestElasticsearch + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromOutputUpdateRequestElasticsearch overwrites any union data inside the OutputUpdateRequest as the provided OutputUpdateRequestElasticsearch +func (t *OutputUpdateRequest) FromOutputUpdateRequestElasticsearch(v OutputUpdateRequestElasticsearch) error { + v.Type = "elasticsearch" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeOutputUpdateRequestElasticsearch performs a merge with any union data inside the OutputUpdateRequest, using the provided OutputUpdateRequestElasticsearch +func (t *OutputUpdateRequest) MergeOutputUpdateRequestElasticsearch(v OutputUpdateRequestElasticsearch) error { + v.Type = "elasticsearch" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JsonMerge(t.union, b) + t.union = merged + return err +} + +// AsOutputUpdateRequestKafka returns the union data inside the OutputUpdateRequest as a OutputUpdateRequestKafka +func (t OutputUpdateRequest) AsOutputUpdateRequestKafka() (OutputUpdateRequestKafka, error) { + var body OutputUpdateRequestKafka + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromOutputUpdateRequestKafka overwrites any union data inside the OutputUpdateRequest as the provided OutputUpdateRequestKafka +func (t *OutputUpdateRequest) FromOutputUpdateRequestKafka(v OutputUpdateRequestKafka) error { + v.Type = "kafka" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeOutputUpdateRequestKafka performs a merge with any union data inside the OutputUpdateRequest, using the provided OutputUpdateRequestKafka +func (t *OutputUpdateRequest) MergeOutputUpdateRequestKafka(v OutputUpdateRequestKafka) error { + v.Type = "kafka" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JsonMerge(t.union, b) + t.union = merged + return err +} + +// AsOutputUpdateRequestLogstash returns the union data inside the OutputUpdateRequest as a OutputUpdateRequestLogstash +func (t OutputUpdateRequest) AsOutputUpdateRequestLogstash() (OutputUpdateRequestLogstash, error) { + var body OutputUpdateRequestLogstash + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromOutputUpdateRequestLogstash overwrites any union data inside the OutputUpdateRequest as the provided OutputUpdateRequestLogstash +func (t *OutputUpdateRequest) FromOutputUpdateRequestLogstash(v OutputUpdateRequestLogstash) error { + v.Type = "logstash" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeOutputUpdateRequestLogstash performs a merge with any union data inside the OutputUpdateRequest, using the provided OutputUpdateRequestLogstash +func (t *OutputUpdateRequest) MergeOutputUpdateRequestLogstash(v OutputUpdateRequestLogstash) error { + v.Type = "logstash" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JsonMerge(t.union, b) + t.union = merged + return err +} + +func (t OutputUpdateRequest) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t OutputUpdateRequest) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "elasticsearch": + return t.AsOutputUpdateRequestElasticsearch() + case "kafka": + return t.AsOutputUpdateRequestKafka() + case "logstash": + return t.AsOutputUpdateRequestLogstash() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t OutputUpdateRequest) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *OutputUpdateRequest) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + // RequestEditorFn is the function signature for the RequestEditor callback function type RequestEditorFn func(ctx context.Context, req *http.Request) error @@ -984,6 +1784,7 @@ type CreateAgentPolicyResponse struct { JSON200 *struct { Item *AgentPolicy `json:"item,omitempty"` } + JSON400 *Error } // Status returns HTTPResponse.Status @@ -1009,6 +1810,7 @@ type DeleteAgentPolicyResponse struct { Id string `json:"id"` Success bool `json:"success"` } + JSON400 *Error } // Status returns HTTPResponse.Status @@ -1033,6 +1835,7 @@ type AgentPolicyInfoResponse struct { JSON200 *struct { Item AgentPolicy `json:"item"` } + JSON400 *Error } // Status returns HTTPResponse.Status @@ -1057,6 +1860,7 @@ type UpdateAgentPolicyResponse struct { JSON200 *struct { Item AgentPolicy `json:"item"` } + JSON400 *Error } // Status returns HTTPResponse.Status @@ -1086,6 +1890,7 @@ type GetEnrollmentApiKeysResponse struct { PerPage float32 `json:"perPage"` Total float32 `json:"total"` } + JSON400 *Error } // Status returns HTTPResponse.Status @@ -1110,6 +1915,7 @@ type PostFleetServerHostsResponse struct { JSON200 *struct { Item *FleetServerHost `json:"item,omitempty"` } + JSON400 *Error } // Status returns HTTPResponse.Status @@ -1134,6 +1940,7 @@ type DeleteFleetServerHostsResponse struct { JSON200 *struct { Id string `json:"id"` } + JSON400 *Error } // Status returns HTTPResponse.Status @@ -1158,6 +1965,7 @@ type GetOneFleetServerHostsResponse struct { JSON200 *struct { Item FleetServerHost `json:"item"` } + JSON400 *Error } // Status returns HTTPResponse.Status @@ -1182,6 +1990,7 @@ type UpdateFleetServerHostsResponse struct { JSON200 *struct { Item FleetServerHost `json:"item"` } + JSON400 *Error } // Status returns HTTPResponse.Status @@ -1204,8 +2013,9 @@ type PostOutputsResponse struct { Body []byte HTTPResponse *http.Response JSON200 *struct { - Item *Output `json:"item,omitempty"` + Item *OutputCreateRequest `json:"item,omitempty"` } + JSON400 *Error } // Status returns HTTPResponse.Status @@ -1230,6 +2040,7 @@ type DeleteOutputResponse struct { JSON200 *struct { Id string `json:"id"` } + JSON400 *Error } // Status returns HTTPResponse.Status @@ -1252,8 +2063,9 @@ type GetOutputResponse struct { Body []byte HTTPResponse *http.Response JSON200 *struct { - Item Output `json:"item"` + Item *OutputCreateRequest `json:"item,omitempty"` } + JSON400 *Error } // Status returns HTTPResponse.Status @@ -1276,8 +2088,9 @@ type UpdateOutputResponse struct { Body []byte HTTPResponse *http.Response JSON200 *struct { - Item Output `json:"item"` + Item *OutputUpdateRequest `json:"item,omitempty"` } + JSON400 *Error } // Status returns HTTPResponse.Status @@ -1492,6 +2305,13 @@ func ParseCreateAgentPolicyResponse(rsp *http.Response) (*CreateAgentPolicyRespo } response.JSON200 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + } return response, nil @@ -1521,6 +2341,13 @@ func ParseDeleteAgentPolicyResponse(rsp *http.Response) (*DeleteAgentPolicyRespo } response.JSON200 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + } return response, nil @@ -1549,6 +2376,13 @@ func ParseAgentPolicyInfoResponse(rsp *http.Response) (*AgentPolicyInfoResponse, } response.JSON200 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + } return response, nil @@ -1577,6 +2411,13 @@ func ParseUpdateAgentPolicyResponse(rsp *http.Response) (*UpdateAgentPolicyRespo } response.JSON200 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + } return response, nil @@ -1610,6 +2451,13 @@ func ParseGetEnrollmentApiKeysResponse(rsp *http.Response) (*GetEnrollmentApiKey } response.JSON200 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + } return response, nil @@ -1638,6 +2486,13 @@ func ParsePostFleetServerHostsResponse(rsp *http.Response) (*PostFleetServerHost } response.JSON200 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + } return response, nil @@ -1666,6 +2521,13 @@ func ParseDeleteFleetServerHostsResponse(rsp *http.Response) (*DeleteFleetServer } response.JSON200 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + } return response, nil @@ -1694,6 +2556,13 @@ func ParseGetOneFleetServerHostsResponse(rsp *http.Response) (*GetOneFleetServer } response.JSON200 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + } return response, nil @@ -1722,6 +2591,13 @@ func ParseUpdateFleetServerHostsResponse(rsp *http.Response) (*UpdateFleetServer } response.JSON200 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + } return response, nil @@ -1743,13 +2619,20 @@ func ParsePostOutputsResponse(rsp *http.Response) (*PostOutputsResponse, error) switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: var dest struct { - Item *Output `json:"item,omitempty"` + Item *OutputCreateRequest `json:"item,omitempty"` } if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } response.JSON200 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + } return response, nil @@ -1778,6 +2661,13 @@ func ParseDeleteOutputResponse(rsp *http.Response) (*DeleteOutputResponse, error } response.JSON200 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + } return response, nil @@ -1799,13 +2689,20 @@ func ParseGetOutputResponse(rsp *http.Response) (*GetOutputResponse, error) { switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: var dest struct { - Item Output `json:"item"` + Item *OutputCreateRequest `json:"item,omitempty"` } if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } response.JSON200 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + } return response, nil @@ -1827,13 +2724,20 @@ func ParseUpdateOutputResponse(rsp *http.Response) (*UpdateOutputResponse, error switch { case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: var dest struct { - Item Output `json:"item"` + Item *OutputUpdateRequest `json:"item,omitempty"` } if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } response.JSON200 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Error + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + } return response, nil diff --git a/generated/fleet/getschema.go b/generated/fleet/getschema.go new file mode 100644 index 000000000..99c54875c --- /dev/null +++ b/generated/fleet/getschema.go @@ -0,0 +1,394 @@ +//go:build ignore +// +build ignore + +package main + +import ( + "encoding/json" + "flag" + "fmt" + "io" + "log" + "net/http" + "os" + "strconv" + "strings" +) + +const ( + fleetSchemaURLTmpl = "https://raw.githubusercontent.com/elastic/kibana/%s/x-pack/plugins/fleet/common/openapi/bundled.json" +) + +type Schema struct { + Paths map[string]*Path `json:"paths"` + OpenAPIVersion string `json:"openapi"` + Tags []any `json:"tags,omitempty"` + Servers []any `json:"servers,omitempty"` + Components Fields `json:"components,omitempty"` + Security []any `json:"security,omitempty"` + Info map[string]any `json:"info"` +} + +type Path struct { + Parameters []Fields `json:"parameters,omitempty"` + Get *Endpoint `json:"get,omitempty"` + Post *Endpoint `json:"post,omitempty"` + Put *Endpoint `json:"put,omitempty"` + Delete *Endpoint `json:"delete,omitempty"` +} + +func (p *Path) GetEndpoint(method string) *Endpoint { + switch strings.ToUpper(method) { + case http.MethodGet: + return p.Get + case http.MethodPost: + return p.Post + case http.MethodPut: + return p.Put + case http.MethodDelete: + return p.Delete + } + + return nil +} + +type Endpoint struct { + Summary string `json:"summary,omitempty"` + Tags []string `json:"tags,omitempty"` + Responses Fields `json:"responses,omitempty"` + RequestBody Fields `json:"requestBody,omitempty"` + OperationID string `json:"operationId,omitempty"` + Parameters []Fields `json:"parameters,omitempty"` + Deprecated bool `json:"deprecated,omitempty"` +} + +type TransformFunc func(schema *Schema) + +var transformers = []TransformFunc{ + transformFilterPaths, + transformOutputTypeRequired, + transformOutputResponseType, +} + +// transformFilterPaths filters the paths in a schema down to +// a specified list of endpoints and methods. +func transformFilterPaths(schema *Schema) { + var includePaths = map[string][]string{ + "/agent_policies": {"post"}, + "/agent_policies/{agentPolicyId}": {"get", "put"}, + "/agent_policies/delete": {"post"}, + "/enrollment_api_keys": {"get"}, + "/fleet_server_hosts": {"post"}, + "/fleet_server_hosts/{itemId}": {"get", "put", "delete"}, + "/outputs": {"post"}, + "/outputs/{outputId}": {"get", "put", "delete"}, + } + + // filterKbnXsrfParameter filters out an entry if it is a kbn_xsrf parameter. + // Returns a copy of the slice if it was modified, otherwise returns the original + // slice if no match was found. + filterKbnXsrfParameter := func(parameters []Fields) []Fields { + removeIndex := -1 + + for i, param := range parameters { + if ref, ok := param["$ref"].(string); ok && ref == "#/components/parameters/kbn_xsrf" { + removeIndex = i + break + } + } + if removeIndex != -1 { + ret := make([]Fields, 0) + ret = append(ret, parameters[:removeIndex]...) + return append(ret, parameters[removeIndex+1:]...) + } + + return parameters + } + + for path, pathInfo := range schema.Paths { + // Remove paths not in filter list. + if _, exists := includePaths[path]; !exists { + delete(schema.Paths, path) + continue + } + + // Filter out kbn-xsrf parameter (already set by API client). + pathInfo.Parameters = filterKbnXsrfParameter(pathInfo.Parameters) + + // Filter out endpoints not if filter list, filter out kbn-xsrf + // parameter in endpoint (already set by API client). + allowedMethods := includePaths[path] + filterEndpointFn := func(endpoint *Endpoint, method string) *Endpoint { + if endpoint == nil { + return nil + } + if !stringInSlice(method, allowedMethods) { + return nil + } + + endpoint.Parameters = filterKbnXsrfParameter(endpoint.Parameters) + + return endpoint + } + pathInfo.Get = filterEndpointFn(pathInfo.Get, "get") + pathInfo.Post = filterEndpointFn(pathInfo.Post, "post") + pathInfo.Put = filterEndpointFn(pathInfo.Put, "put") + pathInfo.Delete = filterEndpointFn(pathInfo.Delete, "delete") + } + + return +} + +// transformOutputTypeRequired ensures that the type key is +// in the list of required keys for an output type. +func transformOutputTypeRequired(schema *Schema) { + path := []string{ + "schemas.output_create_request_elasticsearch.required", + "schemas.output_create_request_kafka.required", + "schemas.output_create_request_logstash.required", + "schemas.output_update_request_elasticsearch.required", + "schemas.output_update_request_kafka.required", + "schemas.output_update_request_logstash.required", + } + + for _, v := range path { + raw, ok := schema.Components.Get(v) + if !ok { + continue + } + required, ok := raw.([]any) + if !ok { + continue + } + + if stringInAnySlice("type", required) { + continue + } + + required = append(required, "type") + schema.Components.Set(v, required) + } +} + +// transformOutputTypeRequired ensures that the response object is wrapped +// in an `item` key/value pair. Remove once the following issue is closed: +// https://github.com/elastic/kibana/issues/167181 +func transformOutputResponseType(schema *Schema) { + methods := []string{http.MethodGet, http.MethodPut} + for _, method := range methods { + endpoint := schema.Paths["/outputs/{outputId}"].GetEndpoint(method) + resSchema, ok := endpoint.Responses.GetFields("200.content.application/json.schema") + if !ok { + continue + } + ref, ok := resSchema.Get("$ref") + if ok { + resSchema.Set("type", "object") + resSchema.Set("properties.item.$ref", ref) + resSchema.Delete("$ref") + } + } +} + +// downloadFile will download a file from url and return the +// bytes. If the request fails, or a non 200 error code is +// observed in the response, an error is returned instead. +func downloadFile(url string) ([]byte, error) { + resp, err := http.Get(url) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("unexpected status: HTTP %v: %v", resp.StatusCode, resp.Status) + } + + return io.ReadAll(resp.Body) +} + +func main() { + outFile := flag.String("o", "", "output file") + inFile := flag.String("i", "", "input file") + apiVersion := flag.String("v", "main", "api version") + flag.Parse() + + if *outFile == "" { + flag.Usage() + os.Exit(1) + } + + var err error + var rawData []byte + if *inFile != "" { + rawData, err = os.ReadFile(*inFile) + } else { + rawData, err = downloadFile(fmt.Sprintf(fleetSchemaURLTmpl, *apiVersion)) + } + if err != nil { + log.Fatal(err) + } + + var schema Schema + if err = json.Unmarshal(rawData, &schema); err != nil { + log.Fatal(err) + } + + for _, fn := range transformers { + fn(&schema) + } + + outData, err := json.MarshalIndent(&schema, "", " ") + if err != nil { + log.Fatal(err) + } + if err = os.WriteFile(*outFile, outData, 0664); err != nil { + log.Fatal(err) + } +} + +// Fields wraps map[string]any with convenience functions for interacting +// with nested map values. +type Fields map[string]any + +// Get will get the value at 'key' as the first returned +// parameter. The second parameter is a bool indicating +// if 'key' exists. +func (f Fields) Get(key string) (any, bool) { + indexSliceFn := func(slice []any, key string) (any, string, bool) { + indexStr, subKeys, _ := strings.Cut(key, ".") + index, err := strconv.Atoi(indexStr) + if err != nil { + log.Printf("Failed to parse slice index key %q: %v", indexStr, err) + return nil, "", false + } + + if index < 0 || index >= len(slice) { + log.Printf("Slice index is out of bounds (%d, target slice len: %d)", index, len(slice)) + return nil, "", false + } + + return slice[index], subKeys, true + } + + rootKey, subKeys, split := strings.Cut(key, ".") + if split { + switch t := f[rootKey].(type) { + case Fields: + return t.Get(subKeys) + case map[string]any: + return Fields(t).Get(subKeys) + case []any: + slicedValue, postSliceKeys, ok := indexSliceFn(t, subKeys) + if !ok { + return nil, false + } + if m, isMap := slicedValue.(map[string]any); ok && isMap { + return Fields(m).Get(postSliceKeys) + } + return slicedValue, true + + default: + rootKey = key + } + } + + value, ok := f[rootKey] + return value, ok +} + +// GetFields is like Get, but converts the found value to Fields. +// If the key is not found or the type conversion fails, the +// second return value will be false. +func (f Fields) GetFields(key string) (Fields, bool) { + value, ok := f.Get(key) + if !ok { + return nil, false + } + + switch t := value.(type) { + case Fields: + return t, true + case map[string]any: + return t, true + } + + return nil, false +} + +// Set will set key to the value of 'value'. +func (f Fields) Set(key string, value any) { + rootKey, subKeys, split := strings.Cut(key, ".") + if split { + if v, ok := f[rootKey]; ok { + switch t := v.(type) { + case Fields: + t.Set(subKeys, value) + case map[string]any: + Fields(t).Set(subKeys, value) + } + } else { + subMap := Fields{} + subMap.Set(subKeys, value) + f[rootKey] = subMap + } + } else { + f[rootKey] = value + } +} + +// Move will move the value from 'key' to 'target'. If 'key' does not +// exist, the operation is a no-op. +func (f Fields) Move(key, target string) { + value, ok := f.Get(key) + if !ok { + return + } + + f.Set(target, value) + f.Delete(key) +} + +// Delete will remove the key from the Fields. If key is nested, +// empty sub-keys will be removed as well. +func (f Fields) Delete(key string) { + rootKey, subKeys, split := strings.Cut(key, ".") + if split { + if v, ok := f[rootKey]; ok { + switch t := v.(type) { + case Fields: + t.Delete(subKeys) + case map[string]any: + Fields(t).Delete(subKeys) + } + } + } else { + delete(f, rootKey) + } +} + +// stringInSlice returns true if value is present in slice. +func stringInSlice(value string, slice []string) bool { + for _, v := range slice { + if value == v { + return true + } + } + + return false +} + +// stringInAnySlice returns true if value is present in slice. +func stringInAnySlice(value string, slice []any) bool { + for _, v := range slice { + s, ok := v.(string) + if !ok { + continue + } + if value == s { + return true + } + } + + return false +} diff --git a/internal/clients/fleet/client.go b/internal/clients/fleet/client.go index acdaa05f5..e5c5b1832 100644 --- a/internal/clients/fleet/client.go +++ b/internal/clients/fleet/client.go @@ -8,7 +8,7 @@ import ( "os" "strings" - "github.com/elastic/terraform-provider-elasticstack/internal/clients/fleet/fleetapi" + fleetapi "github.com/elastic/terraform-provider-elasticstack/generated/fleet" "github.com/elastic/terraform-provider-elasticstack/internal/utils" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging" ) diff --git a/internal/clients/fleet/fleet.go b/internal/clients/fleet/fleet.go index 5ca57cc4e..e017622c2 100644 --- a/internal/clients/fleet/fleet.go +++ b/internal/clients/fleet/fleet.go @@ -5,7 +5,7 @@ import ( "fmt" "net/http" - "github.com/elastic/terraform-provider-elasticstack/internal/clients/fleet/fleetapi" + fleetapi "github.com/elastic/terraform-provider-elasticstack/generated/fleet" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" ) @@ -91,7 +91,7 @@ func DeleteAgentPolicy(ctx context.Context, client *Client, id string) diag.Diag } // ReadOutput reads a specific output from the API. -func ReadOutput(ctx context.Context, client *Client, id string) (*fleetapi.Output, diag.Diagnostics) { +func ReadOutput(ctx context.Context, client *Client, id string) (*fleetapi.OutputCreateRequest, diag.Diagnostics) { resp, err := client.API.GetOutputWithResponse(ctx, id) if err != nil { return nil, diag.FromErr(err) @@ -99,7 +99,7 @@ func ReadOutput(ctx context.Context, client *Client, id string) (*fleetapi.Outpu switch resp.StatusCode() { case http.StatusOK: - return &resp.JSON200.Item, nil + return resp.JSON200.Item, nil case http.StatusNotFound: return nil, nil default: @@ -108,7 +108,7 @@ func ReadOutput(ctx context.Context, client *Client, id string) (*fleetapi.Outpu } // CreateOutput creates a new output. -func CreateOutput(ctx context.Context, client *Client, req fleetapi.PostOutputsJSONRequestBody) (*fleetapi.Output, diag.Diagnostics) { +func CreateOutput(ctx context.Context, client *Client, req fleetapi.PostOutputsJSONRequestBody) (*fleetapi.OutputCreateRequest, diag.Diagnostics) { resp, err := client.API.PostOutputsWithResponse(ctx, req) if err != nil { return nil, diag.FromErr(err) @@ -123,7 +123,7 @@ func CreateOutput(ctx context.Context, client *Client, req fleetapi.PostOutputsJ } // UpdateOutput updates an existing output. -func UpdateOutput(ctx context.Context, client *Client, id string, req fleetapi.UpdateOutputJSONRequestBody) (*fleetapi.Output, diag.Diagnostics) { +func UpdateOutput(ctx context.Context, client *Client, id string, req fleetapi.UpdateOutputJSONRequestBody) (*fleetapi.OutputUpdateRequest, diag.Diagnostics) { resp, err := client.API.UpdateOutputWithResponse(ctx, id, req) if err != nil { return nil, diag.FromErr(err) @@ -131,7 +131,7 @@ func UpdateOutput(ctx context.Context, client *Client, id string, req fleetapi.U switch resp.StatusCode() { case http.StatusOK: - return &resp.JSON200.Item, nil + return resp.JSON200.Item, nil default: return nil, reportUnknownError(resp.StatusCode(), resp.Body) } diff --git a/internal/clients/fleet/fleetapi/doc.go b/internal/clients/fleet/fleetapi/doc.go deleted file mode 100644 index 1e03040c8..000000000 --- a/internal/clients/fleet/fleetapi/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -package fleetapi - -//go:generate go run generate.go -v v8.7.1 -o fleet-filtered.json -//go:generate go run github.com/deepmap/oapi-codegen/cmd/oapi-codegen -package=fleetapi -generate=types -o ./fleetapi_gen.go fleet-filtered.json -//go:generate go run github.com/deepmap/oapi-codegen/cmd/oapi-codegen -package=fleetapi -generate=client -o ./client_gen.go fleet-filtered.json diff --git a/internal/clients/fleet/fleetapi/fleetapi_gen.go b/internal/clients/fleet/fleetapi/fleetapi_gen.go deleted file mode 100644 index 01d92f5c1..000000000 --- a/internal/clients/fleet/fleetapi/fleetapi_gen.go +++ /dev/null @@ -1,291 +0,0 @@ -// Package fleetapi provides primitives to interact with the openapi HTTP API. -// -// Code generated by github.com/deepmap/oapi-codegen version v1.14.0 DO NOT EDIT. -package fleetapi - -import ( - "time" -) - -const ( - BasicAuthScopes = "basicAuth.Scopes" -) - -// Defines values for AgentPolicyMonitoringEnabled. -const ( - AgentPolicyMonitoringEnabledLogs AgentPolicyMonitoringEnabled = "logs" - AgentPolicyMonitoringEnabledMetrics AgentPolicyMonitoringEnabled = "metrics" -) - -// Defines values for AgentPolicyCreateRequestMonitoringEnabled. -const ( - AgentPolicyCreateRequestMonitoringEnabledLogs AgentPolicyCreateRequestMonitoringEnabled = "logs" - AgentPolicyCreateRequestMonitoringEnabledMetrics AgentPolicyCreateRequestMonitoringEnabled = "metrics" -) - -// Defines values for AgentPolicyUpdateRequestMonitoringEnabled. -const ( - Logs AgentPolicyUpdateRequestMonitoringEnabled = "logs" - Metrics AgentPolicyUpdateRequestMonitoringEnabled = "metrics" -) - -// Defines values for OutputType. -const ( - OutputTypeElasticsearch OutputType = "elasticsearch" - OutputTypeLogstash OutputType = "logstash" -) - -// Defines values for PostOutputsJSONBodyType. -const ( - PostOutputsJSONBodyTypeElasticsearch PostOutputsJSONBodyType = "elasticsearch" -) - -// Defines values for UpdateOutputJSONBodyType. -const ( - Elasticsearch UpdateOutputJSONBodyType = "elasticsearch" -) - -// AgentPolicy defines model for agent_policy. -type AgentPolicy struct { - AgentFeatures *[]struct { - Enabled bool `json:"enabled"` - Name string `json:"name"` - } `json:"agent_features,omitempty"` - Agents *float32 `json:"agents,omitempty"` - DataOutputId *string `json:"data_output_id"` - Description *string `json:"description,omitempty"` - DownloadSourceId *string `json:"download_source_id"` - FleetServerHostId *string `json:"fleet_server_host_id"` - Id string `json:"id"` - InactivityTimeout *float32 `json:"inactivity_timeout,omitempty"` - MonitoringEnabled *[]AgentPolicyMonitoringEnabled `json:"monitoring_enabled,omitempty"` - MonitoringOutputId *string `json:"monitoring_output_id"` - Name string `json:"name"` - Namespace string `json:"namespace"` - - // PackagePolicies This field is present only when retrieving a single agent policy, or when retrieving a list of agent policy with the ?full=true parameter - PackagePolicies *[]PackagePolicy `json:"package_policies,omitempty"` - Revision *float32 `json:"revision,omitempty"` - UnenrollTimeout *float32 `json:"unenroll_timeout,omitempty"` - UpdatedBy *string `json:"updated_by,omitempty"` - UpdatedOn *time.Time `json:"updated_on,omitempty"` -} - -// AgentPolicyMonitoringEnabled defines model for AgentPolicy.MonitoringEnabled. -type AgentPolicyMonitoringEnabled string - -// AgentPolicyCreateRequest defines model for agent_policy_create_request. -type AgentPolicyCreateRequest struct { - AgentFeatures *[]struct { - Enabled bool `json:"enabled"` - Name string `json:"name"` - } `json:"agent_features,omitempty"` - DataOutputId *string `json:"data_output_id"` - Description *string `json:"description,omitempty"` - DownloadSourceId *string `json:"download_source_id"` - FleetServerHostId *string `json:"fleet_server_host_id"` - Id *string `json:"id,omitempty"` - InactivityTimeout *float32 `json:"inactivity_timeout,omitempty"` - MonitoringEnabled *[]AgentPolicyCreateRequestMonitoringEnabled `json:"monitoring_enabled,omitempty"` - MonitoringOutputId *string `json:"monitoring_output_id"` - Name string `json:"name"` - Namespace string `json:"namespace"` - UnenrollTimeout *float32 `json:"unenroll_timeout,omitempty"` -} - -// AgentPolicyCreateRequestMonitoringEnabled defines model for AgentPolicyCreateRequest.MonitoringEnabled. -type AgentPolicyCreateRequestMonitoringEnabled string - -// AgentPolicyUpdateRequest defines model for agent_policy_update_request. -type AgentPolicyUpdateRequest struct { - AgentFeatures *[]struct { - Enabled bool `json:"enabled"` - Name string `json:"name"` - } `json:"agent_features,omitempty"` - DataOutputId *string `json:"data_output_id"` - Description *string `json:"description,omitempty"` - DownloadSourceId *string `json:"download_source_id"` - FleetServerHostId *string `json:"fleet_server_host_id"` - InactivityTimeout *float32 `json:"inactivity_timeout,omitempty"` - MonitoringEnabled *[]AgentPolicyUpdateRequestMonitoringEnabled `json:"monitoring_enabled,omitempty"` - MonitoringOutputId *string `json:"monitoring_output_id"` - Name string `json:"name"` - Namespace string `json:"namespace"` - UnenrollTimeout *float32 `json:"unenroll_timeout,omitempty"` -} - -// AgentPolicyUpdateRequestMonitoringEnabled defines model for AgentPolicyUpdateRequest.MonitoringEnabled. -type AgentPolicyUpdateRequestMonitoringEnabled string - -// EnrollmentApiKey defines model for enrollment_api_key. -type EnrollmentApiKey struct { - Active bool `json:"active"` - ApiKey string `json:"api_key"` - ApiKeyId string `json:"api_key_id"` - CreatedAt string `json:"created_at"` - Id string `json:"id"` - Name *string `json:"name,omitempty"` - PolicyId *string `json:"policy_id,omitempty"` -} - -// FleetServerHost defines model for fleet_server_host. -type FleetServerHost struct { - HostUrls []string `json:"host_urls"` - Id string `json:"id"` - IsDefault bool `json:"is_default"` - IsPreconfigured bool `json:"is_preconfigured"` - Name *string `json:"name,omitempty"` -} - -// NewPackagePolicy defines model for new_package_policy. -type NewPackagePolicy struct { - Description *string `json:"description,omitempty"` - Enabled *bool `json:"enabled,omitempty"` - Inputs []struct { - Config *map[string]interface{} `json:"config,omitempty"` - Enabled bool `json:"enabled"` - Processors *[]string `json:"processors,omitempty"` - Streams *[]interface{} `json:"streams,omitempty"` - Type string `json:"type"` - Vars *map[string]interface{} `json:"vars,omitempty"` - } `json:"inputs"` - Name string `json:"name"` - Namespace *string `json:"namespace,omitempty"` - // Deprecated: - OutputId *string `json:"output_id,omitempty"` - Package *struct { - Name string `json:"name"` - Title *string `json:"title,omitempty"` - Version string `json:"version"` - } `json:"package,omitempty"` - PolicyId *string `json:"policy_id,omitempty"` -} - -// Output defines model for output. -type Output struct { - CaSha256 *string `json:"ca_sha256,omitempty"` - CaTrustedFingerprint *string `json:"ca_trusted_fingerprint,omitempty"` - Config *map[string]interface{} `json:"config,omitempty"` - ConfigYaml *string `json:"config_yaml,omitempty"` - Hosts *[]string `json:"hosts,omitempty"` - Id string `json:"id"` - IsDefault bool `json:"is_default"` - IsDefaultMonitoring *bool `json:"is_default_monitoring,omitempty"` - Name string `json:"name"` - ProxyId *string `json:"proxy_id,omitempty"` - Shipper *struct { - CompressionLevel *float32 `json:"compression_level,omitempty"` - DiskQueueCompressionEnabled *bool `json:"disk_queue_compression_enabled,omitempty"` - DiskQueueEnabled *bool `json:"disk_queue_enabled,omitempty"` - DiskQueueEncryptionEnabled *bool `json:"disk_queue_encryption_enabled,omitempty"` - DiskQueueMaxSize *float32 `json:"disk_queue_max_size,omitempty"` - DiskQueuePath *string `json:"disk_queue_path,omitempty"` - Loadbalance *bool `json:"loadbalance,omitempty"` - } `json:"shipper,omitempty"` - Ssl *struct { - Certificate *string `json:"certificate,omitempty"` - CertificateAuthorities *[]string `json:"certificate_authorities,omitempty"` - Key *string `json:"key,omitempty"` - } `json:"ssl,omitempty"` - Type OutputType `json:"type"` -} - -// OutputType defines model for Output.Type. -type OutputType string - -// PackagePolicy defines model for package_policy. -type PackagePolicy struct { - Description *string `json:"description,omitempty"` - Enabled *bool `json:"enabled,omitempty"` - Id string `json:"id"` - Inputs []struct { - Config *map[string]interface{} `json:"config,omitempty"` - Enabled bool `json:"enabled"` - Processors *[]string `json:"processors,omitempty"` - Streams *[]interface{} `json:"streams,omitempty"` - Type string `json:"type"` - Vars *map[string]interface{} `json:"vars,omitempty"` - } `json:"inputs"` - Name string `json:"name"` - Namespace *string `json:"namespace,omitempty"` - // Deprecated: - OutputId *string `json:"output_id,omitempty"` - Package *struct { - Name string `json:"name"` - Title *string `json:"title,omitempty"` - Version string `json:"version"` - } `json:"package,omitempty"` - PolicyId *string `json:"policy_id,omitempty"` - Revision float32 `json:"revision"` -} - -// DeleteAgentPolicyJSONBody defines parameters for DeleteAgentPolicy. -type DeleteAgentPolicyJSONBody struct { - AgentPolicyId string `json:"agentPolicyId"` -} - -// PostFleetServerHostsJSONBody defines parameters for PostFleetServerHosts. -type PostFleetServerHostsJSONBody struct { - HostUrls []string `json:"host_urls"` - Id *string `json:"id,omitempty"` - IsDefault *bool `json:"is_default,omitempty"` - Name string `json:"name"` -} - -// UpdateFleetServerHostsJSONBody defines parameters for UpdateFleetServerHosts. -type UpdateFleetServerHostsJSONBody struct { - HostUrls *[]string `json:"host_urls,omitempty"` - IsDefault *bool `json:"is_default,omitempty"` - Name *string `json:"name,omitempty"` -} - -// PostOutputsJSONBody defines parameters for PostOutputs. -type PostOutputsJSONBody struct { - CaSha256 *string `json:"ca_sha256,omitempty"` - ConfigYaml *string `json:"config_yaml,omitempty"` - Hosts *[]string `json:"hosts,omitempty"` - Id *string `json:"id,omitempty"` - IsDefault *bool `json:"is_default,omitempty"` - IsDefaultMonitoring *bool `json:"is_default_monitoring,omitempty"` - Name string `json:"name"` - Type PostOutputsJSONBodyType `json:"type"` -} - -// PostOutputsJSONBodyType defines parameters for PostOutputs. -type PostOutputsJSONBodyType string - -// UpdateOutputJSONBody defines parameters for UpdateOutput. -type UpdateOutputJSONBody struct { - CaSha256 *string `json:"ca_sha256,omitempty"` - CaTrustedFingerprint *string `json:"ca_trusted_fingerprint,omitempty"` - ConfigYaml *string `json:"config_yaml,omitempty"` - Hosts *[]string `json:"hosts,omitempty"` - IsDefault *bool `json:"is_default,omitempty"` - IsDefaultMonitoring *bool `json:"is_default_monitoring,omitempty"` - Name string `json:"name"` - Type UpdateOutputJSONBodyType `json:"type"` -} - -// UpdateOutputJSONBodyType defines parameters for UpdateOutput. -type UpdateOutputJSONBodyType string - -// CreateAgentPolicyJSONRequestBody defines body for CreateAgentPolicy for application/json ContentType. -type CreateAgentPolicyJSONRequestBody = AgentPolicyCreateRequest - -// DeleteAgentPolicyJSONRequestBody defines body for DeleteAgentPolicy for application/json ContentType. -type DeleteAgentPolicyJSONRequestBody DeleteAgentPolicyJSONBody - -// UpdateAgentPolicyJSONRequestBody defines body for UpdateAgentPolicy for application/json ContentType. -type UpdateAgentPolicyJSONRequestBody = AgentPolicyUpdateRequest - -// PostFleetServerHostsJSONRequestBody defines body for PostFleetServerHosts for application/json ContentType. -type PostFleetServerHostsJSONRequestBody PostFleetServerHostsJSONBody - -// UpdateFleetServerHostsJSONRequestBody defines body for UpdateFleetServerHosts for application/json ContentType. -type UpdateFleetServerHostsJSONRequestBody UpdateFleetServerHostsJSONBody - -// PostOutputsJSONRequestBody defines body for PostOutputs for application/json ContentType. -type PostOutputsJSONRequestBody PostOutputsJSONBody - -// UpdateOutputJSONRequestBody defines body for UpdateOutput for application/json ContentType. -type UpdateOutputJSONRequestBody UpdateOutputJSONBody diff --git a/internal/clients/fleet/fleetapi/generate.go b/internal/clients/fleet/fleetapi/generate.go deleted file mode 100644 index 6741fa299..000000000 --- a/internal/clients/fleet/fleetapi/generate.go +++ /dev/null @@ -1,169 +0,0 @@ -//go:build ignore -// +build ignore - -package main - -import ( - "encoding/json" - "flag" - "fmt" - "io" - "log" - "net/http" - "os" -) - -const ( - fleetSchemaURLTmpl = "https://raw.githubusercontent.com/elastic/kibana/%s/x-pack/plugins/fleet/common/openapi/bundled.json" -) - -type OpenAPISchema struct { - Paths map[string]*Path `json:"paths"` - OpenAPIVersion string `json:"openapi"` - Tags []any `json:"tags,omitempty"` - Servers []any `json:"servers,omitempty"` - Components map[string]any `json:"components,omitempty"` - Security []any `json:"security,omitempty"` -} - -type Path struct { - Parameters []map[string]any `json:"parameters,omitempty"` - Get *Endpoint `json:"get,omitempty"` - Post *Endpoint `json:"post,omitempty"` - Put *Endpoint `json:"put,omitempty"` - Delete *Endpoint `json:"delete,omitempty"` -} - -type Endpoint struct { - Summary string `json:"summary,omitempty"` - Tags []string `json:"tags,omitempty"` - Responses map[string]any `json:"responses,omitempty"` - RequestBody map[string]any `json:"requestBody,omitempty"` - OperationID string `json:"operationId,omitempty"` - Parameters []map[string]any `json:"parameters,omitempty"` - Deprecated bool `json:"deprecated,omitempty"` -} - -var includePaths = map[string][]string{ - "/agent_policies": {"post"}, - "/agent_policies/{agentPolicyId}": {"get", "put"}, - "/agent_policies/delete": {"post"}, - "/enrollment_api_keys": {"get"}, - "/fleet_server_hosts": {"post"}, - "/fleet_server_hosts/{itemId}": {"get", "put", "delete"}, - "/outputs": {"post"}, - "/outputs/{outputId}": {"get", "put", "delete"}, -} - -func downloadFile(url string) ([]byte, error) { - resp, err := http.Get(url) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("unexpected status: HTTP %v: %v", resp.StatusCode, resp.Status) - } - - return io.ReadAll(resp.Body) -} - -func stringInSlice(value string, slice []string) bool { - for _, v := range slice { - if v == value { - return true - } - } - - return false -} - -// filterKbnXsrfParameter filters out an entry if it is a kbn_xsrf parameter. -// Returns a copy of the slice if it was modified, otherwise returns the original -// slice if no match was found. -func filterKbnXsrfParameter(parameters []map[string]any) []map[string]any { - removeIndex := -1 - - for i, param := range parameters { - if ref, ok := param["$ref"].(string); ok && ref == "#/components/parameters/kbn_xsrf" { - removeIndex = i - break - } - } - if removeIndex != -1 { - ret := make([]map[string]any, 0) - ret = append(ret, parameters[:removeIndex]...) - return append(ret, parameters[removeIndex+1:]...) - } - - return parameters -} - -func main() { - outFile := flag.String("o", "", "output file") - inFile := flag.String("i", "", "input file") - apiVersion := flag.String("v", "main", "api version") - flag.Parse() - - if *outFile == "" { - flag.Usage() - os.Exit(1) - } - - var err error - var schemaData []byte - - if *inFile != "" { - schemaData, err = os.ReadFile(*inFile) - } else { - schemaData, err = downloadFile(fmt.Sprintf(fleetSchemaURLTmpl, *apiVersion)) - } - if err != nil { - log.Fatal(err) - } - - var schema OpenAPISchema - if err = json.Unmarshal(schemaData, &schema); err != nil { - log.Fatal(err) - } - - for path, pathInfo := range schema.Paths { - // Remove paths not in filter list. - if _, exists := includePaths[path]; !exists { - delete(schema.Paths, path) - continue - } - - // Filter out kbn-xsrf parameter (already set by API client). - pathInfo.Parameters = filterKbnXsrfParameter(pathInfo.Parameters) - - // Filter out endpoints not if filter list, filter out kbn-xsrf - // parameter in endpoint (already set by API client). - allowedMethods := includePaths[path] - filterEndpointFn := func(endpoint *Endpoint, method string) *Endpoint { - if endpoint == nil { - return nil - } - if !stringInSlice(method, allowedMethods) { - return nil - } - - endpoint.Parameters = filterKbnXsrfParameter(endpoint.Parameters) - - return endpoint - } - pathInfo.Get = filterEndpointFn(pathInfo.Get, "get") - pathInfo.Post = filterEndpointFn(pathInfo.Post, "post") - pathInfo.Put = filterEndpointFn(pathInfo.Put, "put") - pathInfo.Delete = filterEndpointFn(pathInfo.Delete, "delete") - } - - outData, err := json.MarshalIndent(&schema, "", " ") - if err != nil { - log.Fatal(err) - } - if err = os.WriteFile(*outFile, outData, 0664); err != nil { - log.Fatal(err) - } -} diff --git a/internal/fleet/agent_policy_resource.go b/internal/fleet/agent_policy_resource.go index f490ba979..3badf20aa 100644 --- a/internal/fleet/agent_policy_resource.go +++ b/internal/fleet/agent_policy_resource.go @@ -3,8 +3,8 @@ package fleet import ( "context" + fleetapi "github.com/elastic/terraform-provider-elasticstack/generated/fleet" "github.com/elastic/terraform-provider-elasticstack/internal/clients/fleet" - "github.com/elastic/terraform-provider-elasticstack/internal/clients/fleet/fleetapi" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" diff --git a/internal/fleet/fleet_server_host_resource.go b/internal/fleet/fleet_server_host_resource.go index 623434fb3..582d883bc 100644 --- a/internal/fleet/fleet_server_host_resource.go +++ b/internal/fleet/fleet_server_host_resource.go @@ -3,8 +3,8 @@ package fleet import ( "context" + fleetapi "github.com/elastic/terraform-provider-elasticstack/generated/fleet" "github.com/elastic/terraform-provider-elasticstack/internal/clients/fleet" - "github.com/elastic/terraform-provider-elasticstack/internal/clients/fleet/fleetapi" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) diff --git a/internal/fleet/output_resource.go b/internal/fleet/output_resource.go index ae8279f6f..565c80372 100644 --- a/internal/fleet/output_resource.go +++ b/internal/fleet/output_resource.go @@ -3,8 +3,8 @@ package fleet import ( "context" + fleetapi "github.com/elastic/terraform-provider-elasticstack/generated/fleet" "github.com/elastic/terraform-provider-elasticstack/internal/clients/fleet" - "github.com/elastic/terraform-provider-elasticstack/internal/clients/fleet/fleetapi" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" @@ -43,6 +43,11 @@ func ResourceOutput() *schema.Resource { Type: schema.TypeString, Optional: true, }, + "ca_trusted_fingerprint": { + Description: "Fingerprint of trusted CA.", + Type: schema.TypeString, + Optional: true, + }, "default_integrations": { Description: "Make this output the default for agent integrations.", Type: schema.TypeBool, @@ -77,15 +82,15 @@ func ResourceOutput() *schema.Resource { } } -func resourceOutputCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceOutputCreateElasticsearch(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { fleetClient, diags := getFleetClient(d, meta) if diags.HasError() { return diags } - req := fleetapi.PostOutputsJSONRequestBody{ + reqData := fleetapi.OutputCreateRequestElasticsearch{ Name: d.Get("name").(string), - Type: fleetapi.PostOutputsJSONBodyType(d.Get("type").(string)), + Type: fleetapi.OutputCreateRequestElasticsearchTypeElasticsearch, } var hosts []string @@ -97,35 +102,124 @@ func resourceOutputCreate(ctx context.Context, d *schema.ResourceData, meta inte } } if hosts != nil { - req.Hosts = &hosts + reqData.Hosts = &hosts + } + if value := d.Get("default_integrations").(bool); value { + reqData.IsDefault = &value + } + if value := d.Get("default_monitoring").(bool); value { + reqData.IsDefaultMonitoring = &value + } + if value, ok := d.Get("ca_sha256").(string); ok && value != "" { + reqData.CaSha256 = &value + } + if value, ok := d.Get("ca_trusted_fingerprint").(string); ok && value != "" { + reqData.CaTrustedFingerprint = &value + } + if value, ok := d.Get("config_yaml").(string); ok && value != "" { + reqData.ConfigYaml = &value + } + + req := fleetapi.PostOutputsJSONRequestBody{} + if err := req.FromOutputCreateRequestElasticsearch(reqData); err != nil { + return diag.FromErr(err) + } + + rawOutput, diags := fleet.CreateOutput(ctx, fleetClient, req) + if diags.HasError() { + return diags + } + + output, err := rawOutput.AsOutputCreateRequestElasticsearch() + if err != nil { + return diag.FromErr(err) + } + + d.SetId(*output.Id) + if err := d.Set("output_id", output.Id); err != nil { + return diag.FromErr(err) + } + + return nil +} + +func resourceOutputCreateLogstash(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + fleetClient, diags := getFleetClient(d, meta) + if diags.HasError() { + return diags + } + + reqData := fleetapi.OutputCreateRequestLogstash{ + Name: d.Get("name").(string), + Type: fleetapi.OutputCreateRequestLogstashTypeLogstash, + } + + var hosts []string + if value := d.Get("hosts").([]interface{}); len(value) > 0 { + for _, v := range value { + if vStr, ok := v.(string); ok && vStr != "" { + hosts = append(hosts, vStr) + } + } } + reqData.Hosts = hosts if value := d.Get("default_integrations").(bool); value { - req.IsDefault = &value + reqData.IsDefault = &value } if value := d.Get("default_monitoring").(bool); value { - req.IsDefaultMonitoring = &value + reqData.IsDefaultMonitoring = &value } if value, ok := d.Get("ca_sha256").(string); ok && value != "" { - req.CaSha256 = &value + reqData.CaSha256 = &value + } + if value, ok := d.Get("ca_trusted_fingerprint").(string); ok && value != "" { + reqData.CaTrustedFingerprint = &value } if value, ok := d.Get("config_yaml").(string); ok && value != "" { - req.ConfigYaml = &value + reqData.ConfigYaml = &value } - host, diags := fleet.CreateOutput(ctx, fleetClient, req) + req := fleetapi.PostOutputsJSONRequestBody{} + if err := req.FromOutputCreateRequestLogstash(reqData); err != nil { + return diag.FromErr(err) + } + + rawOutput, diags := fleet.CreateOutput(ctx, fleetClient, req) if diags.HasError() { return diags } - d.SetId(host.Id) - if err := d.Set("output_id", host.Id); err != nil { + output, err := rawOutput.AsOutputCreateRequestElasticsearch() + if err != nil { + return diag.FromErr(err) + } + + d.SetId(*output.Id) + if err := d.Set("output_id", output.Id); err != nil { return diag.FromErr(err) } + return nil +} + +func resourceOutputCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + outputType := d.Get("type").(string) + var diags diag.Diagnostics + + switch outputType { + case "elasticsearch": + diags = resourceOutputCreateElasticsearch(ctx, d, meta) + case "logstash": + diags = resourceOutputCreateLogstash(ctx, d, meta) + } + if diags.HasError() { + return diags + } + return resourceOutputRead(ctx, d, meta) } -func resourceOutputUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceOutputUpdateElasticsearch(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { fleetClient, diags := getFleetClient(d, meta) if diags.HasError() { return diags @@ -134,8 +228,9 @@ func resourceOutputUpdate(ctx context.Context, d *schema.ResourceData, meta inte id := d.Get("output_id").(string) d.SetId(id) - req := fleetapi.UpdateOutputJSONRequestBody{ + reqData := fleetapi.OutputUpdateRequestElasticsearch{ Name: d.Get("name").(string), + Type: fleetapi.OutputUpdateRequestElasticsearchTypeElasticsearch, } var hosts []string @@ -146,23 +241,23 @@ func resourceOutputUpdate(ctx context.Context, d *schema.ResourceData, meta inte } } } - if hosts != nil { - req.Hosts = &hosts - } + reqData.Hosts = hosts if value := d.Get("default_integrations").(bool); value { - req.IsDefault = &value + reqData.IsDefault = &value } if value := d.Get("default_monitoring").(bool); value { - req.IsDefaultMonitoring = &value + reqData.IsDefaultMonitoring = &value } if value, ok := d.Get("ca_sha256").(string); ok && value != "" { - req.CaSha256 = &value + reqData.CaSha256 = &value } if value, ok := d.Get("config_yaml").(string); ok && value != "" { - req.ConfigYaml = &value + reqData.ConfigYaml = &value } - if value, ok := d.Get("type").(string); ok && value != "" { - req.Type = fleetapi.UpdateOutputJSONBodyType(value) + + req := fleetapi.UpdateOutputJSONRequestBody{} + if err := req.FromOutputUpdateRequestElasticsearch(reqData); err != nil { + return diag.FromErr(err) } _, diags = fleet.UpdateOutput(ctx, fleetClient, id, req) @@ -170,10 +265,10 @@ func resourceOutputUpdate(ctx context.Context, d *schema.ResourceData, meta inte return diags } - return resourceOutputRead(ctx, d, meta) + return nil } -func resourceOutputRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceOutputUpdateLogstash(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { fleetClient, diags := getFleetClient(d, meta) if diags.HasError() { return diags @@ -182,43 +277,174 @@ func resourceOutputRead(ctx context.Context, d *schema.ResourceData, meta interf id := d.Get("output_id").(string) d.SetId(id) - output, diags := fleet.ReadOutput(ctx, fleetClient, id) + reqData := fleetapi.OutputUpdateRequestLogstash{ + Name: d.Get("name").(string), + Type: fleetapi.OutputUpdateRequestLogstashTypeLogstash, + } + + var hosts []string + if value := d.Get("hosts").([]interface{}); len(value) > 0 { + for _, v := range value { + if vStr, ok := v.(string); ok && vStr != "" { + hosts = append(hosts, vStr) + } + } + } + if hosts != nil { + reqData.Hosts = &hosts + } + if value := d.Get("default_integrations").(bool); value { + reqData.IsDefault = &value + } + if value := d.Get("default_monitoring").(bool); value { + reqData.IsDefaultMonitoring = &value + } + if value, ok := d.Get("ca_sha256").(string); ok && value != "" { + reqData.CaSha256 = &value + } + if value, ok := d.Get("config_yaml").(string); ok && value != "" { + reqData.ConfigYaml = &value + } + + req := fleetapi.UpdateOutputJSONRequestBody{} + if err := req.FromOutputUpdateRequestLogstash(reqData); err != nil { + return diag.FromErr(err) + } + + _, diags = fleet.UpdateOutput(ctx, fleetClient, id, req) if diags.HasError() { return diags } - // Not found. - if output == nil { - d.SetId("") - return nil + return nil +} + +func resourceOutputUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + var diags diag.Diagnostics + + outputType := d.Get("type").(string) + switch outputType { + case "elasticsearch": + diags = resourceOutputUpdateElasticsearch(ctx, d, meta) + case "logstash": + diags = resourceOutputUpdateLogstash(ctx, d, meta) } + if diags.HasError() { + return diags + } + + return resourceOutputRead(ctx, d, meta) +} - if err := d.Set("name", output.Name); err != nil { +func resourceOutputReadElasticsearch(d *schema.ResourceData, data fleetapi.OutputCreateRequestElasticsearch) diag.Diagnostics { + if err := d.Set("name", data.Name); err != nil { return diag.FromErr(err) } - if output.Hosts != nil { - if err := d.Set("hosts", *output.Hosts); err != nil { + if data.Hosts != nil { + if err := d.Set("hosts", *data.Hosts); err != nil { return diag.FromErr(err) } } - if err := d.Set("default_integrations", output.IsDefault); err != nil { + if err := d.Set("default_integrations", data.IsDefault); err != nil { return diag.FromErr(err) } - if output.IsDefaultMonitoring != nil { - if err := d.Set("default_monitoring", *output.IsDefaultMonitoring); err != nil { + if data.IsDefaultMonitoring != nil { + if err := d.Set("default_monitoring", *data.IsDefaultMonitoring); err != nil { return diag.FromErr(err) } } - if output.CaSha256 != nil { - if err := d.Set("ca_sha256", *output.CaSha256); err != nil { + if data.CaSha256 != nil { + if err := d.Set("ca_sha256", *data.CaSha256); err != nil { return diag.FromErr(err) } } - if output.ConfigYaml != nil { - if err := d.Set("config_yaml", *output.ConfigYaml); err != nil { + if data.CaTrustedFingerprint != nil { + if err := d.Set("ca_trusted_fingerprint", *data.CaTrustedFingerprint); err != nil { return diag.FromErr(err) } } + if data.ConfigYaml != nil { + if err := d.Set("config_yaml", *data.ConfigYaml); err != nil { + return diag.FromErr(err) + } + } + + return nil +} + +func resourceOutputReadLogstash(d *schema.ResourceData, data fleetapi.OutputCreateRequestLogstash) diag.Diagnostics { + if err := d.Set("name", data.Name); err != nil { + return diag.FromErr(err) + } + if err := d.Set("hosts", data.Hosts); err != nil { + return diag.FromErr(err) + } + if err := d.Set("default_integrations", data.IsDefault); err != nil { + return diag.FromErr(err) + } + if data.IsDefaultMonitoring != nil { + if err := d.Set("default_monitoring", *data.IsDefaultMonitoring); err != nil { + return diag.FromErr(err) + } + } + if data.CaSha256 != nil { + if err := d.Set("ca_sha256", *data.CaSha256); err != nil { + return diag.FromErr(err) + } + } + if data.CaTrustedFingerprint != nil { + if err := d.Set("ca_trusted_fingerprint", *data.CaTrustedFingerprint); err != nil { + return diag.FromErr(err) + } + } + if data.ConfigYaml != nil { + if err := d.Set("config_yaml", *data.ConfigYaml); err != nil { + return diag.FromErr(err) + } + } + + return nil +} + +func resourceOutputRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + fleetClient, diags := getFleetClient(d, meta) + if diags.HasError() { + return diags + } + + id := d.Get("output_id").(string) + d.SetId(id) + + rawOutput, diags := fleet.ReadOutput(ctx, fleetClient, id) + if diags.HasError() { + return diags + } + // Not found. + if rawOutput == nil { + d.SetId("") + return nil + } + + outputType := d.Get("type").(string) + switch outputType { + case "elasticsearch": + output, err := rawOutput.AsOutputCreateRequestElasticsearch() + if err != nil { + return diag.FromErr(err) + } + + diags = resourceOutputReadElasticsearch(d, output) + case "logstash": + output, err := rawOutput.AsOutputCreateRequestLogstash() + if err != nil { + return diag.FromErr(err) + } + + diags = resourceOutputReadLogstash(d, output) + } + if diags.HasError() { + return diags + } return nil } diff --git a/internal/fleet/output_resource_test.go b/internal/fleet/output_resource_test.go index 98f7ca348..583c55579 100644 --- a/internal/fleet/output_resource_test.go +++ b/internal/fleet/output_resource_test.go @@ -17,7 +17,7 @@ import ( var minVersionOutput = version.Must(version.NewVersion("8.6.0")) -func TestAccResourceOutput(t *testing.T) { +func TestAccResourceOutputElasticsearch(t *testing.T) { policyName := sdkacctest.RandStringFromCharSet(22, sdkacctest.CharSetAlphaNum) resource.Test(t, resource.TestCase{ @@ -27,9 +27,9 @@ func TestAccResourceOutput(t *testing.T) { Steps: []resource.TestStep{ { SkipFunc: versionutils.CheckIfVersionIsUnsupported(minVersionOutput), - Config: testAccResourceOutputCreate(policyName), + Config: testAccResourceOutputCreateElasticsearch(policyName), Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("elasticstack_fleet_output.test_output", "name", fmt.Sprintf("Output %s", policyName)), + resource.TestCheckResourceAttr("elasticstack_fleet_output.test_output", "name", fmt.Sprintf("Elasticsearch Output %s", policyName)), resource.TestCheckResourceAttr("elasticstack_fleet_output.test_output", "type", "elasticsearch"), resource.TestCheckResourceAttr("elasticstack_fleet_output.test_output", "config_yaml", "\"ssl.verification_mode\": \"none\"\n"), resource.TestCheckResourceAttr("elasticstack_fleet_output.test_output", "default_integrations", "false"), @@ -39,9 +39,9 @@ func TestAccResourceOutput(t *testing.T) { }, { SkipFunc: versionutils.CheckIfVersionIsUnsupported(minVersionOutput), - Config: testAccResourceOutputUpdate(policyName), + Config: testAccResourceOutputUpdateElasticsearch(policyName), Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("elasticstack_fleet_output.test_output", "name", fmt.Sprintf("Updated Output %s", policyName)), + resource.TestCheckResourceAttr("elasticstack_fleet_output.test_output", "name", fmt.Sprintf("Updated Elasticsearch Output %s", policyName)), resource.TestCheckResourceAttr("elasticstack_fleet_output.test_output", "type", "elasticsearch"), resource.TestCheckResourceAttr("elasticstack_fleet_output.test_output", "config_yaml", "\"ssl.verification_mode\": \"none\"\n"), resource.TestCheckResourceAttr("elasticstack_fleet_output.test_output", "default_integrations", "false"), @@ -53,7 +53,43 @@ func TestAccResourceOutput(t *testing.T) { }) } -func testAccResourceOutputCreate(id string) string { +func TestAccResourceOutputLogstash(t *testing.T) { + policyName := sdkacctest.RandStringFromCharSet(22, sdkacctest.CharSetAlphaNum) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + CheckDestroy: checkResourceOutputDestroy, + ProtoV5ProviderFactories: acctest.Providers, + Steps: []resource.TestStep{ + { + SkipFunc: versionutils.CheckIfVersionIsUnsupported(minVersionOutput), + Config: testAccResourceOutputCreateLogstash(policyName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("elasticstack_fleet_output.test_output", "name", fmt.Sprintf("Logstash Output %s", policyName)), + resource.TestCheckResourceAttr("elasticstack_fleet_output.test_output", "type", "logstash"), + resource.TestCheckResourceAttr("elasticstack_fleet_output.test_output", "config_yaml", "\"ssl.verification_mode\": \"none\"\n"), + resource.TestCheckResourceAttr("elasticstack_fleet_output.test_output", "default_integrations", "false"), + resource.TestCheckResourceAttr("elasticstack_fleet_output.test_output", "default_monitoring", "false"), + resource.TestCheckResourceAttr("elasticstack_fleet_output.test_output", "hosts.0", "logstash:5044"), + ), + }, + { + SkipFunc: versionutils.CheckIfVersionIsUnsupported(minVersionOutput), + Config: testAccResourceOutputLogstashUpdate(policyName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("elasticstack_fleet_output.test_output", "name", fmt.Sprintf("Updated Logstash Output %s", policyName)), + resource.TestCheckResourceAttr("elasticstack_fleet_output.test_output", "type", "logstash"), + resource.TestCheckResourceAttr("elasticstack_fleet_output.test_output", "config_yaml", "\"ssl.verification_mode\": \"none\"\n"), + resource.TestCheckResourceAttr("elasticstack_fleet_output.test_output", "default_integrations", "false"), + resource.TestCheckResourceAttr("elasticstack_fleet_output.test_output", "default_monitoring", "false"), + resource.TestCheckResourceAttr("elasticstack_fleet_output.test_output", "hosts.0", "logstash:5044"), + ), + }, + }, + }) +} + +func testAccResourceOutputCreateElasticsearch(id string) string { return fmt.Sprintf(` provider "elasticstack" { elasticsearch {} @@ -72,10 +108,10 @@ resource "elasticstack_fleet_output" "test_output" { "https://elasticsearch:9200" ] } -`, fmt.Sprintf("Output %s", id)) +`, fmt.Sprintf("Elasticsearch Output %s", id)) } -func testAccResourceOutputUpdate(id string) string { +func testAccResourceOutputUpdateElasticsearch(id string) string { return fmt.Sprintf(` provider "elasticstack" { elasticsearch {} @@ -95,7 +131,52 @@ resource "elasticstack_fleet_output" "test_output" { ] } -`, fmt.Sprintf("Updated Output %s", id)) +`, fmt.Sprintf("Updated Elasticsearch Output %s", id)) +} + +func testAccResourceOutputCreateLogstash(id string) string { + return fmt.Sprintf(` +provider "elasticstack" { + elasticsearch {} + kibana {} +} + +resource "elasticstack_fleet_output" "test_output" { + name = "%s" + type = "logstash" + config_yaml = yamlencode({ + "ssl.verification_mode" : "none" + }) + default_integrations = false + default_monitoring = false + hosts = [ + "logstash:5044" + ] +} +`, fmt.Sprintf("Logstash Output %s", id)) +} + +func testAccResourceOutputLogstashUpdate(id string) string { + return fmt.Sprintf(` +provider "elasticstack" { + elasticsearch {} + kibana {} +} + +resource "elasticstack_fleet_output" "test_output" { + name = "%s" + type = "logstash" + config_yaml = yamlencode({ + "ssl.verification_mode" : "none" + }) + default_integrations = false + default_monitoring = false + hosts = [ + "logstash:5044" + ] +} + +`, fmt.Sprintf("Updated Logstash Output %s", id)) } func checkResourceOutputDestroy(s *terraform.State) error { diff --git a/tools/fleet_gen.go b/tools/fleet_gen.go new file mode 100644 index 000000000..7d0a280fb --- /dev/null +++ b/tools/fleet_gen.go @@ -0,0 +1,4 @@ +package tools + +//go:generate go run ../generated/fleet/getschema.go -v v8.10.0 -o ../generated/fleet/fleet-filtered.json +//go:generate go run github.com/deepmap/oapi-codegen/cmd/oapi-codegen -package=fleet -generate=types,client -o ../generated/fleet/fleet.gen.go ../generated/fleet/fleet-filtered.json