diff --git a/docs/resources/cdn_rule_template.md b/docs/resources/cdn_rule_template.md new file mode 100644 index 0000000..51f9b91 --- /dev/null +++ b/docs/resources/cdn_rule_template.md @@ -0,0 +1,633 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "gcore_cdn_rule_template Resource - terraform-provider-gcore" +subcategory: "" +description: |- + Represent CDN rule template +--- + +# gcore_cdn_rule_template (Resource) + +Represent CDN rule template + +## Example Usage + +```terraform +provider gcore { + permanent_api_token = "251$d3361.............1b35f26d8" +} + +resource "gcore_cdn_rule_template" "cdn_example_com_rule_template_1" { + name = "All PNG images template" + rule = "/folder/images/*.png" + rule_type = 0 + weight = 1 + override_origin_protocol = "HTTPS" + + options { + edge_cache_settings { + default = "14d" + } + gzip_on { + value = true + } + ignore_query_string { + value = true + } + } +} +``` + + +## Schema + +### Required + +- `rule` (String) Path to the file or folder for which the rule will be applied. The rule is applied if the requested URI matches the rule path. We add a leading forward slash to any rule path. Specify a path without a forward slash. +- `rule_type` (Number) Rule type. Possible values are: 0 - Regular expression. Must start with '^/' or '/'. 1 - Regular expression. Note that for this rule type we automatically add / to each rule pattern before your regular expression. This type is legacy, please use 0. + +### Optional + +- `name` (String) Rule template name. +- `options` (Block List, Max: 1) Each option in CDN rule settings. Each option added to CDN rule settings should have the following mandatory request fields: enabled, value. (see [below for nested schema](#nestedblock--options)) +- `override_origin_protocol` (String) Sets a protocol other than the one specified in the CDN resource settings to connect to the origin. If not specified, it will be inherited from the CDN resource settings. Possible values are: HTTPS, HTTP, MATCH. +- `weight` (Number) Rule execution order: from lowest (1) to highest. If requested URI matches multiple rules, the one higher in the order of the rules will be applied. + +### Read-Only + +- `id` (String) The ID of this resource. + + +### Nested Schema for `options` + +Optional: + +- `allowed_http_methods` (Block List, Max: 1) Specify allowed HTTP methods. (see [below for nested schema](#nestedblock--options--allowed_http_methods)) +- `brotli_compression` (Block List, Max: 1) Brotli compression option allows to compress content with brotli on the CDN's end. CDN servers will request only uncompressed content from the origin. (see [below for nested schema](#nestedblock--options--brotli_compression)) +- `browser_cache_settings` (Block List, Max: 1) Specify the cache expiration time for customers' browsers in seconds. (see [below for nested schema](#nestedblock--options--browser_cache_settings)) +- `cors` (Block List, Max: 1) CORS header support option adds the Access-Control-Allow-Origin header to responses from CDN servers. (see [below for nested schema](#nestedblock--options--cors)) +- `country_acl` (Block List, Max: 1) Country access policy enables control access to content for specified countries. (see [below for nested schema](#nestedblock--options--country_acl)) +- `disable_proxy_force_ranges` (Block List, Max: 1) The option allows getting 206 responses regardless settings of an origin source. Enabled by default. (see [below for nested schema](#nestedblock--options--disable_proxy_force_ranges)) +- `edge_cache_settings` (Block List, Max: 1) The cache expiration time for CDN servers. (see [below for nested schema](#nestedblock--options--edge_cache_settings)) +- `fastedge` (Block List, Max: 1) Allows to configure FastEdge app to be called on different request/response phases. (see [below for nested schema](#nestedblock--options--fastedge)) +- `fetch_compressed` (Block List, Max: 1) Option allows to enable fetch compressed. CDN request and cache already compressed content. Your server should support compression. CDN servers will not ungzip your content even if a user's browser doesn't accept compression (nowadays almost all browsers support it). (see [below for nested schema](#nestedblock--options--fetch_compressed)) +- `follow_origin_redirect` (Block List, Max: 1) Enable redirection from origin. If the origin server returns a redirect, the option allows the CDN to pull the requested content from the origin server that was returned in the redirect. (see [below for nested schema](#nestedblock--options--follow_origin_redirect)) +- `force_return` (Block List, Max: 1) Allows to apply custom HTTP code to the CDN content. Specify HTTP-code you need and text or URL if you are going to set up redirect. (see [below for nested schema](#nestedblock--options--force_return)) +- `forward_host_header` (Block List, Max: 1) When a CDN requests content from an origin server, the option allows to forward the Host header used in the request made to a CDN. (see [below for nested schema](#nestedblock--options--forward_host_header)) +- `gzip_on` (Block List, Max: 1) GZip compression option allows to compress content with gzip on the CDN`s end. CDN servers will request only uncompressed content from the origin. (see [below for nested schema](#nestedblock--options--gzip_on)) +- `host_header` (Block List, Max: 1) Option allows to set Host header that CDN servers use when request content from an origin server. Your server must be able to process requests with the chosen header. If the option is NULL, Host Header value is taken from the parent CDN resource's value. (see [below for nested schema](#nestedblock--options--host_header)) +- `ignore_cookie` (Block List, Max: 1) By default, files pulled from an origin source with cookies are not cached in a CDN. Enable this option to cache such objects. (see [below for nested schema](#nestedblock--options--ignore_cookie)) +- `ignore_query_string` (Block List, Max: 1) Ignore query string option determines how files with different query strings will be cached: either as one object (option is enabled) or as different objects (option is disabled). (see [below for nested schema](#nestedblock--options--ignore_query_string)) +- `image_stack` (Block List, Max: 1) Image stack option allows transforming JPG and PNG images (such as resizing or cropping) and automatically converting them to WebP or AVIF format. It is a paid option. (see [below for nested schema](#nestedblock--options--image_stack)) +- `ip_address_acl` (Block List, Max: 1) IP access policy option allows to control access to the CDN Resource content for specific IP addresses. (see [below for nested schema](#nestedblock--options--ip_address_acl)) +- `limit_bandwidth` (Block List, Max: 1) The option allows to control the download speed per connection. (see [below for nested schema](#nestedblock--options--limit_bandwidth)) +- `proxy_cache_key` (Block List, Max: 1) The option allows to modify the cache key. If omitted, the default value is $request_uri. Warning: Enabling and changing this option can invalidate your current cache and affect the cache hit ratio. Furthermore, the "Purge by pattern" option will not work. (see [below for nested schema](#nestedblock--options--proxy_cache_key)) +- `proxy_cache_methods_set` (Block List, Max: 1) Allows caching for GET, HEAD and POST requests. (see [below for nested schema](#nestedblock--options--proxy_cache_methods_set)) +- `proxy_connect_timeout` (Block List, Max: 1) The time limit for establishing a connection with the origin. (see [below for nested schema](#nestedblock--options--proxy_connect_timeout)) +- `proxy_read_timeout` (Block List, Max: 1) The time limit for receiving a partial response from the origin. If no response is received within this time, the connection will be closed. (see [below for nested schema](#nestedblock--options--proxy_read_timeout)) +- `query_params_blacklist` (Block List, Max: 1) Specify list of query strings. Files with those query strings will be cached as one object. (see [below for nested schema](#nestedblock--options--query_params_blacklist)) +- `query_params_whitelist` (Block List, Max: 1) Specify list of query strings. Files with those query strings will be cached as different objects. (see [below for nested schema](#nestedblock--options--query_params_whitelist)) +- `redirect_http_to_https` (Block List, Max: 1) When enabled, HTTP requests are redirected to HTTPS. (see [below for nested schema](#nestedblock--options--redirect_http_to_https)) +- `redirect_https_to_http` (Block List, Max: 1) When enabled, HTTPS requests are redirected to HTTP. (see [below for nested schema](#nestedblock--options--redirect_https_to_http)) +- `referrer_acl` (Block List, Max: 1) Referrer access policy option allows to control access to the CDN Resource content for specified domain names. (see [below for nested schema](#nestedblock--options--referrer_acl)) +- `request_limiter` (Block List, Max: 1) It allows to limit the amount of HTTP requests (see [below for nested schema](#nestedblock--options--request_limiter)) +- `response_headers_hiding_policy` (Block List, Max: 1) Define HTTP headers (specified at an origin server) that a CDN server hides from the response. (see [below for nested schema](#nestedblock--options--response_headers_hiding_policy)) +- `rewrite` (Block List, Max: 1) Rewrite option changes and redirects the requests from the CDN to the origin. It operates according to the Nginx configuration. (see [below for nested schema](#nestedblock--options--rewrite)) +- `secure_key` (Block List, Max: 1) The option allows configuring an access with tokenized URLs. It makes impossible to access content without a valid (unexpired) hash key. When enabled, you need to specify a key that you use to generate a token. (see [below for nested schema](#nestedblock--options--secure_key)) +- `slice` (Block List, Max: 1) When enabled, files larger than 10 MB are requested and cached in parts (no larger than 10 MB each). It reduces time to first byte. The origin must support HTTP Range requests. (see [below for nested schema](#nestedblock--options--slice)) +- `sni` (Block List, Max: 1) Specify the SNI (Server Name Indication). SNI (Server Name Indication) is generally only required if your origin is using shared hosting or does not have a dedicated IP address. If the origin server presents multiple certificates, SNI allows the origin server to know which certificate to use for the connection. The option works only if originProtocol parameter is HTTPS or MATCH. (see [below for nested schema](#nestedblock--options--sni)) +- `stale` (Block List, Max: 1) The list of errors which Always Online option is applied for. (see [below for nested schema](#nestedblock--options--stale)) +- `static_request_headers` (Block List, Max: 1) Specify custom HTTP Headers for a CDN server to add to request. (see [below for nested schema](#nestedblock--options--static_request_headers)) +- `static_response_headers` (Block List, Max: 1) Specify custom HTTP Headers that a CDN server adds to a response. (see [below for nested schema](#nestedblock--options--static_response_headers)) +- `user_agent_acl` (Block List, Max: 1) User agents policy option allows to control access to the content for specified user-agent. (see [below for nested schema](#nestedblock--options--user_agent_acl)) +- `waap` (Block List, Max: 1) Option allows to enable WAAP (Web Application and API Protection). (see [below for nested schema](#nestedblock--options--waap)) +- `waf` (Block List, Max: 1) Option allows to enable Basic WAF to protect you against the most common threats. (see [below for nested schema](#nestedblock--options--waf)) +- `websockets` (Block List, Max: 1) WebSockets option allows WebSockets connections to an origin server. (see [below for nested schema](#nestedblock--options--websockets)) + + +### Nested Schema for `options.allowed_http_methods` + +Required: + +- `value` (Set of String) Available methods: GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS. + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.brotli_compression` + +Required: + +- `value` (Set of String) Specify the content-type for each type of content you wish to have compressed. + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.browser_cache_settings` + +Optional: + +- `enabled` (Boolean) +- `value` (String) Use '0s' to disable caching. The value applies for a response with codes 200, 201, 204, 206, 301, 302, 303, 304, 307, 308. + + + +### Nested Schema for `options.cors` + +Required: + +- `value` (Set of String) Specify a value of the Access-Control-Allow-Origin header. Possible values: '*', '$http_origin', 'example.com'. + +Optional: + +- `always` (Boolean) Specify if the Access-Control-Allow-Origin header should be added to a response from CDN regardless of response code. +- `enabled` (Boolean) + + + +### Nested Schema for `options.country_acl` + +Required: + +- `excepted_values` (Set of String) List of countries according to ISO-3166-1. +- `policy_type` (String) Possible values: allow, deny. + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.disable_proxy_force_ranges` + +Required: + +- `value` (Boolean) + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.edge_cache_settings` + +Optional: + +- `custom_values` (Map of String) Specify caching time in seconds ('0s', '600s' for example) for a response with specific response code ('304', '404' for example). Use 'any' to specify caching time for all response codes. Use '0s' to disable caching for a specific response code. These settings have a higher priority than the value field. +- `default` (String) Content will be cached according to origin cache settings. The value applies for a response with codes 200, 201, 204, 206, 301, 302, 303, 304, 307, 308, if an origin server does not have caching HTTP headers. Responses with other codes will not be cached. +- `enabled` (Boolean) +- `value` (String) Specify caching time for the response with codes 200, 206, 301, 302. Responses with codes 4xx, 5xx will not be cached. Use '0s' to disable caching. Use custom_values field to specify a custom caching time for a response with specific codes. + + + +### Nested Schema for `options.fastedge` + +Required: + +- `on_request_headers` (Block List, Min: 1, Max: 1) Allows to configure FastEdge application that will be called to handle request headers as soon as CDN receives incoming HTTP request. (see [below for nested schema](#nestedblock--options--fastedge--on_request_headers)) + +Optional: + +- `enabled` (Boolean) + + +### Nested Schema for `options.fastedge.on_request_headers` + +Required: + +- `app_id` (String) The ID of the application in FastEdge. + +Optional: + +- `enabled` (Boolean) Determines if the FastEdge application should be called whenever HTTP request headers are received. +- `interrupt_on_error` (Boolean) Determines if the request execution should be interrupted when an error occurs. + + + + +### Nested Schema for `options.fetch_compressed` + +Required: + +- `value` (Boolean) + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.follow_origin_redirect` + +Required: + +- `codes` (Set of Number) Specify the redirect status code that the origin server returns. Possible values: 301, 302, 303, 307, 308. + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.force_return` + +Required: + +- `code` (Number) HTTP response status code. Available codes: 100 <= value <= 599. Reserved codes: 408, 444, 477, 494, 495, 496, 497, 499 + +Optional: + +- `body` (String) Response text or URL if you're going to set up redirection. Max length = 100. +- `enabled` (Boolean) + + + +### Nested Schema for `options.forward_host_header` + +Required: + +- `value` (Boolean) + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.gzip_on` + +Required: + +- `value` (Boolean) + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.host_header` + +Required: + +- `value` (String) + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.ignore_cookie` + +Required: + +- `value` (Boolean) + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.ignore_query_string` + +Required: + +- `value` (Boolean) + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.image_stack` + +Required: + +- `quality` (Number) Quality settings for JPG and PNG images. Specify a value from 1 to 100. The higher the value, the better the image quality and the larger the file size after conversion. + +Optional: + +- `avif_enabled` (Boolean) If enabled, JPG and PNG images automatically convert to AVIF format when supported by the end users browser. +- `enabled` (Boolean) +- `png_lossless` (Boolean) Represents compression without quality loss for PNG format. +- `webp_enabled` (Boolean) If enabled, JPG and PNG images automatically convert to WebP format when supported by the end users browser. + + + +### Nested Schema for `options.ip_address_acl` + +Required: + +- `excepted_values` (Set of String) Specify list of IP address with a subnet mask. +- `policy_type` (String) Possible values: allow, deny. + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.limit_bandwidth` + +Required: + +- `limit_type` (String) The way of controlling the download speed per each connection. Possible values are: static, dynamic. + +Optional: + +- `buffer` (Number) Amount of downloaded data after which the user will be rate limited. +- `enabled` (Boolean) +- `speed` (Number) Maximum download speed per connection. Must be greater than 0. + + + +### Nested Schema for `options.proxy_cache_key` + +Required: + +- `value` (String) Key for caching. Should be a combination of the specified variables: $http_host, $request_uri, $scheme, $uri. + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.proxy_cache_methods_set` + +Required: + +- `value` (Boolean) + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.proxy_connect_timeout` + +Required: + +- `value` (String) Specify time in seconds ('1s', '30s' for example). + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.proxy_read_timeout` + +Required: + +- `value` (String) Specify time in seconds ('1s', '30s' for example). + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.query_params_blacklist` + +Required: + +- `value` (Set of String) + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.query_params_whitelist` + +Required: + +- `value` (Set of String) + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.redirect_http_to_https` + +Required: + +- `value` (Boolean) + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.redirect_https_to_http` + +Required: + +- `value` (Boolean) + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.referrer_acl` + +Required: + +- `excepted_values` (Set of String) Specify list of domain names or wildcard domains (without http:// or https://). For example, example.com or *.example.com. +- `policy_type` (String) Possible values: allow, deny. + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.request_limiter` + +Required: + +- `burst` (Number) +- `rate` (Number) + +Optional: + +- `delay` (Number) +- `enabled` (Boolean) +- `rate_unit` (String) + + + +### Nested Schema for `options.response_headers_hiding_policy` + +Required: + +- `excepted` (Set of String) List of HTTP headers. The following required headers cannot be hidden from response: Connection, Content-Length, Content-Type, Date, Server. +- `mode` (String) Specify a mode of hiding HTTP headers from the response. Possible values are: hide, show. + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.rewrite` + +Required: + +- `body` (String) The pattern for Rewrite. At least one group should be specified. For Example: /rewrite_from/(.*) /rewrite_to/$1 + +Optional: + +- `enabled` (Boolean) +- `flag` (String) Define flag for the Rewrite option. Possible values: last, break, redirect, permanent. + + + +### Nested Schema for `options.secure_key` + +Required: + +- `key` (String) A key generated on your side that will be used for URL signing. +- `type` (Number) Specify the type of URL Signing. It can be either 0 or 2. Type 0 - includes end user's IP to secure token generation. Type 2 - excludes end user's IP from secure token generation. + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.slice` + +Required: + +- `value` (Boolean) + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.sni` + +Optional: + +- `custom_hostname` (String) Custom SNI hostname. Required if sni_type is set to 'custom'. +- `enabled` (Boolean) +- `sni_type` (String) Specify SNI type. Possible values: dynamic, custom. dynamic - SNI hostname depends on the hostHeader and the forward_host_header options. custom - custom SNI hostname. + + + +### Nested Schema for `options.stale` + +Required: + +- `value` (Set of String) Possible values: error, http_403, http_404, http_429, http_500, http_502, http_503, http_504, invalid_header, timeout, updating. + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.static_request_headers` + +Required: + +- `value` (Map of String) Header name is restricted to 255 symbols and can contain latin letters (A-Z, a-z), numbers (0-9), dashes, and underscores. Header value is restricted to 512 symbols and can contain latin letters (a-z), numbers (0-9), spaces, underscores and symbols (-/.:). Space can be used only between words. + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.static_response_headers` + +Required: + +- `value` (Block List, Min: 1) (see [below for nested schema](#nestedblock--options--static_response_headers--value)) + +Optional: + +- `enabled` (Boolean) + + +### Nested Schema for `options.static_response_headers.value` + +Required: + +- `name` (String) Header name. +- `value` (Set of String) Header value. + +Optional: + +- `always` (Boolean) Specifies if the header will be added to a response from CDN regardless of response code. + + + + +### Nested Schema for `options.user_agent_acl` + +Required: + +- `excepted_values` (Set of String) List of User-Agents. Use "" to allow/deny access when the User-Agent header is empty. +- `policy_type` (String) Possible values: allow, deny. + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.waap` + +Required: + +- `value` (Boolean) + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.waf` + +Required: + +- `value` (Boolean) + +Optional: + +- `enabled` (Boolean) + + + +### Nested Schema for `options.websockets` + +Required: + +- `value` (Boolean) + +Optional: + +- `enabled` (Boolean) diff --git a/examples/resources/gcore_cdn_rule_template/resource.tf b/examples/resources/gcore_cdn_rule_template/resource.tf new file mode 100644 index 0000000..5a54110 --- /dev/null +++ b/examples/resources/gcore_cdn_rule_template/resource.tf @@ -0,0 +1,23 @@ +provider gcore { + permanent_api_token = "251$d3361.............1b35f26d8" +} + +resource "gcore_cdn_rule_template" "cdn_example_com_rule_template_1" { + name = "All PNG images template" + rule = "/folder/images/*.png" + rule_type = 0 + weight = 1 + override_origin_protocol = "HTTPS" + + options { + edge_cache_settings { + default = "14d" + } + gzip_on { + value = true + } + ignore_query_string { + value = true + } + } +} diff --git a/gcore/provider.go b/gcore/provider.go index f97e24a..ca82367 100644 --- a/gcore/provider.go +++ b/gcore/provider.go @@ -162,6 +162,7 @@ func Provider() *schema.Provider { "gcore_cdn_applied_preset": resourceCDNAppliedPreset(), "gcore_cdn_rule": resourceCDNRule(), "gcore_cdn_sslcert": resourceCDNCert(), + "gcore_cdn_rule_template": resourceRuleTemplate(), lifecyclePolicyResource: resourceLifecyclePolicy(), "gcore_ddos_protection": resourceDDoSProtection(), }, diff --git a/gcore/resource_gcore_cdn_ruletemplates.go b/gcore/resource_gcore_cdn_ruletemplates.go new file mode 100644 index 0000000..ecd3ca1 --- /dev/null +++ b/gcore/resource_gcore_cdn_ruletemplates.go @@ -0,0 +1,174 @@ +package gcore + +import ( + "context" + "fmt" + "log" + "strconv" + + "github.com/G-Core/gcorelabscdn-go/ruletemplates" + "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" +) + +func resourceRuleTemplate() *schema.Resource { + return &schema.Resource{ + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "Rule template name.", + }, + "rule": { + Type: schema.TypeString, + Required: true, + Description: "Path to the file or folder for which the rule will be applied. The rule is applied if the requested URI matches the rule path. We add a leading forward slash to any rule path. Specify a path without a forward slash.", + }, + "rule_type": { + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IntInSlice([]int{0, 1}), + Description: "Rule type. Possible values are: 0 - Regular expression. Must start with '^/' or '/'. 1 - Regular expression. Note that for this rule type we automatically add / to each rule pattern before your regular expression. This type is legacy, please use 0.", + }, + "weight": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + ValidateFunc: validation.IntAtLeast(1), + Description: "Rule execution order: from lowest (1) to highest. If requested URI matches multiple rules, the one higher in the order of the rules will be applied.", + }, + "override_origin_protocol": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{"HTTP", "HTTPS", "MATCH"}, false), + Description: "Sets a protocol other than the one specified in the CDN resource settings to connect to the origin. If not specified, it will be inherited from the CDN resource settings. Possible values are: HTTPS, HTTP, MATCH.", + }, + "options": ruleOptionsSchema, + }, + CreateContext: resourceRuleTemplateCreate, + ReadContext: resourceRuleTemplateRead, + UpdateContext: resourceRuleTemplateUpdate, + DeleteContext: resourceRuleTemplateDelete, + Description: "Represent CDN rule template", + } +} + +func resourceRuleTemplateCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + log.Println("[DEBUG] Start CDN Rule Template creating") + config := m.(*Config) + client := config.CDNClient + + var req ruletemplates.CreateRequest + req.Name = d.Get("name").(string) + req.Rule = d.Get("rule").(string) + req.RuleType = ruletemplates.RuleType(d.Get("rule_type").(int)) + req.Weight = d.Get("weight").(int) + + if v, ok := d.GetOk("override_origin_protocol"); ok { + overrideOriginProtocol := ruletemplates.Protocol(v.(string)) + req.OverrideOriginProtocol = &overrideOriginProtocol + } else { + req.OverrideOriginProtocol = nil + } + + req.Options = listToOptions(d.Get("options").([]interface{})) + + result, err := client.RuleTemplates().Create(ctx, &req) + if err != nil { + return diag.FromErr(err) + } + + d.SetId(fmt.Sprintf("%d", result.ID)) + resourceRuleTemplateRead(ctx, d, m) + + log.Printf("[DEBUG] Finish CDN Rule Template creating (id=%d)\n", result.ID) + return nil +} + +func resourceRuleTemplateRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + ruleTemplateID := d.Id() + log.Printf("[DEBUG] Start CDN Rule Template reading (id=%s)\n", ruleTemplateID) + config := m.(*Config) + client := config.CDNClient + + id, err := strconv.ParseInt(ruleTemplateID, 10, 64) + if err != nil { + return diag.FromErr(err) + } + + result, err := client.RuleTemplates().Get(ctx, id) + if err != nil { + return diag.FromErr(err) + } + + d.Set("name", result.Name) + d.Set("rule", result.Rule) + d.Set("ruleType", result.RuleType) + d.Set("weight", result.Weight) + d.Set("overrideOriginProtocol", result.OverrideOriginProtocol) + if err := d.Set("options", optionsToList(result.Options)); err != nil { + return diag.FromErr(err) + } + + log.Println("[DEBUG] Finish CDN Rule Template reading") + return nil +} + +func resourceRuleTemplateUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + ruleTemplateID := d.Id() + log.Printf("[DEBUG] Start CDN Rule Template updating (id=%s)\n", ruleTemplateID) + config := m.(*Config) + client := config.CDNClient + + id, err := strconv.ParseInt(ruleTemplateID, 10, 64) + if err != nil { + return diag.FromErr(err) + } + + var req ruletemplates.UpdateRequest + req.Name = d.Get("name").(string) + req.Rule = d.Get("rule").(string) + req.RuleType = ruletemplates.RuleType(d.Get("rule_type").(int)) + req.Weight = d.Get("weight").(int) + + if v, ok := d.GetOk("override_origin_protocol"); ok { + overrideOriginProtocol := ruletemplates.Protocol(v.(string)) + req.OverrideOriginProtocol = &overrideOriginProtocol + } else { + req.OverrideOriginProtocol = nil + } + + req.Options = listToOptions(d.Get("options").([]interface{})) + + if _, err := client.RuleTemplates().Update(ctx, id, &req); err != nil { + return diag.FromErr(err) + } + + log.Println("[DEBUG] Finish CDN Rule Template updating") + return resourceRuleTemplateRead(ctx, d, m) +} + +func resourceRuleTemplateDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + ruleTemplateID := d.Id() + log.Printf("[DEBUG] Start CDN Rule Template deleting (id=%s)\n", ruleTemplateID) + config := m.(*Config) + client := config.CDNClient + + id, err := strconv.ParseInt(ruleTemplateID, 10, 64) + if err != nil { + return diag.FromErr(err) + } + + if err := client.RuleTemplates().Delete(ctx, id); err != nil { + return diag.FromErr(err) + } + + d.SetId("") + log.Println("[DEBUG] Finish CDN Rule Template deleting") + return nil +} diff --git a/go.mod b/go.mod index d651d02..c676d47 100644 --- a/go.mod +++ b/go.mod @@ -6,7 +6,7 @@ require ( github.com/AlekSi/pointer v1.2.0 github.com/G-Core/gcore-dns-sdk-go v0.2.9 github.com/G-Core/gcore-storage-sdk-go v0.1.34 - github.com/G-Core/gcorelabscdn-go v1.0.23 + github.com/G-Core/gcorelabscdn-go v1.0.24 github.com/G-Core/gcorelabscloud-go v0.8.13 github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320 github.com/hashicorp/terraform-plugin-sdk/v2 v2.27.0 diff --git a/go.sum b/go.sum index 3fb83cf..2f21cb7 100644 --- a/go.sum +++ b/go.sum @@ -15,8 +15,8 @@ github.com/G-Core/gcorelabscdn-go v1.0.19 h1:P4qYP+cnO+0DrVftGnL1gt7En8/RYsl20zw github.com/G-Core/gcorelabscdn-go v1.0.19/go.mod h1:iSGXaTvZBzDHQW+rKFS918BgFVpONcyLEijwh8WsXpE= github.com/G-Core/gcorelabscdn-go v1.0.21 h1:ROkbuFy2uyZbnDMaUFrYvjSYqk45GygwU3byOsNIs38= github.com/G-Core/gcorelabscdn-go v1.0.21/go.mod h1:iSGXaTvZBzDHQW+rKFS918BgFVpONcyLEijwh8WsXpE= -github.com/G-Core/gcorelabscdn-go v1.0.23 h1:mn/2BaqiBLux0k9/UDZ2OFMk+uCLTxO+1fLKTRi72mE= -github.com/G-Core/gcorelabscdn-go v1.0.23/go.mod h1:iSGXaTvZBzDHQW+rKFS918BgFVpONcyLEijwh8WsXpE= +github.com/G-Core/gcorelabscdn-go v1.0.24 h1:NhXxdpWzmtJD79ZZPi0zMcsZzy0KoktuOs4xVro/fhE= +github.com/G-Core/gcorelabscdn-go v1.0.24/go.mod h1:iSGXaTvZBzDHQW+rKFS918BgFVpONcyLEijwh8WsXpE= github.com/G-Core/gcorelabscloud-go v0.8.12 h1:qT8rrtSCXT+ol1g4zrl5JzWG+8IicHWCn7+U96tdlj4= github.com/G-Core/gcorelabscloud-go v0.8.12/go.mod h1:13Z1USxlxPbDFuYQyWqfNexlk4kUvOYTXbnvV/Z1lZo= github.com/G-Core/gcorelabscloud-go v0.8.13 h1:MpaT3owpIfbLP3EPZW+NDuxQfezN7FK6b+4VV0WILP8=