Merge branch 'stackitcloud:main' into alpha

This commit is contained in:
Marcel S. Henselin 2025-12-17 16:09:23 +01:00 committed by GitHub
commit c07c81b091
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
125 changed files with 8395 additions and 6044 deletions

View file

@ -27,9 +27,13 @@ data "stackit_affinity_group" "example" {
- `affinity_group_id` (String) The affinity group ID. - `affinity_group_id` (String) The affinity group ID.
- `project_id` (String) STACKIT Project ID to which the affinity group is associated. - `project_id` (String) STACKIT Project ID to which the affinity group is associated.
### Optional
- `region` (String) The resource region. If not defined, the provider region is used.
### Read-Only ### Read-Only
- `id` (String) Terraform's internal resource identifier. It is structured as "`project_id`,`affinity_group_id`". - `id` (String) Terraform's internal resource identifier. It is structured as "`project_id`,`region`,`affinity_group_id`".
- `members` (List of String) Affinity Group schema. Must have a `region` specified in the provider configuration. - `members` (List of String) Affinity Group schema. Must have a `region` specified in the provider configuration.
- `name` (String) The name of the affinity group. - `name` (String) The name of the affinity group.
- `policy` (String) The policy of the affinity group. - `policy` (String) The policy of the affinity group.

View file

@ -31,5 +31,6 @@ data "stackit_iaas_project" "example" {
- `created_at` (String) Date-time when the project was created. - `created_at` (String) Date-time when the project was created.
- `id` (String) Terraform's internal resource ID. It is structured as "`project_id`". - `id` (String) Terraform's internal resource ID. It is structured as "`project_id`".
- `internet_access` (Boolean) Specifies if the project has internet_access - `internet_access` (Boolean) Specifies if the project has internet_access
- `state` (String) Specifies the state of the project. - `state` (String, Deprecated) Specifies the status of the project.
- `status` (String) Specifies the status of the project.
- `updated_at` (String) Date-time when the project was last updated. - `updated_at` (String) Date-time when the project was last updated.

View file

@ -27,12 +27,16 @@ data "stackit_image" "example" {
- `image_id` (String) The image ID. - `image_id` (String) The image ID.
- `project_id` (String) STACKIT project ID to which the image is associated. - `project_id` (String) STACKIT project ID to which the image is associated.
### Optional
- `region` (String) The resource region. If not defined, the provider region is used.
### Read-Only ### Read-Only
- `checksum` (Attributes) Representation of an image checksum. (see [below for nested schema](#nestedatt--checksum)) - `checksum` (Attributes) Representation of an image checksum. (see [below for nested schema](#nestedatt--checksum))
- `config` (Attributes) Properties to set hardware and scheduling settings for an image. (see [below for nested schema](#nestedatt--config)) - `config` (Attributes) Properties to set hardware and scheduling settings for an image. (see [below for nested schema](#nestedatt--config))
- `disk_format` (String) The disk format of the image. - `disk_format` (String) The disk format of the image.
- `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`image_id`". - `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`region`,`image_id`".
- `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container - `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container
- `min_disk_size` (Number) The minimum disk size of the image in GB. - `min_disk_size` (Number) The minimum disk size of the image in GB.
- `min_ram` (Number) The minimum RAM of the image in MB. - `min_ram` (Number) The minimum RAM of the image in MB.

View file

@ -105,6 +105,7 @@ data "stackit_image_v2" "filter_distro_version" {
- `image_id` (String) Image ID to fetch directly - `image_id` (String) Image ID to fetch directly
- `name` (String) Exact image name to match. Optionally applies a `filter` block to further refine results in case multiple images share the same name. The first match is returned, optionally sorted by name in ascending order. Cannot be used together with `name_regex`. - `name` (String) Exact image name to match. Optionally applies a `filter` block to further refine results in case multiple images share the same name. The first match is returned, optionally sorted by name in ascending order. Cannot be used together with `name_regex`.
- `name_regex` (String) Regular expression to match against image names. Optionally applies a `filter` block to narrow down results when multiple image names match the regex. The first match is returned, optionally sorted by name in ascending order. Cannot be used together with `name`. - `name_regex` (String) Regular expression to match against image names. Optionally applies a `filter` block to narrow down results when multiple image names match the regex. The first match is returned, optionally sorted by name in ascending order. Cannot be used together with `name`.
- `region` (String) The resource region. If not defined, the provider region is used.
- `sort_ascending` (Boolean) If set to `true`, images are sorted in ascending lexicographical order by image name (such as `Ubuntu 18.04`, `Ubuntu 20.04`, `Ubuntu 22.04`) before selecting the first match. Defaults to `false` (descending such as `Ubuntu 22.04`, `Ubuntu 20.04`, `Ubuntu 18.04`). - `sort_ascending` (Boolean) If set to `true`, images are sorted in ascending lexicographical order by image name (such as `Ubuntu 18.04`, `Ubuntu 20.04`, `Ubuntu 22.04`) before selecting the first match. Defaults to `false` (descending such as `Ubuntu 22.04`, `Ubuntu 20.04`, `Ubuntu 18.04`).
### Read-Only ### Read-Only
@ -112,7 +113,7 @@ data "stackit_image_v2" "filter_distro_version" {
- `checksum` (Attributes) Representation of an image checksum. (see [below for nested schema](#nestedatt--checksum)) - `checksum` (Attributes) Representation of an image checksum. (see [below for nested schema](#nestedatt--checksum))
- `config` (Attributes) Properties to set hardware and scheduling settings for an image. (see [below for nested schema](#nestedatt--config)) - `config` (Attributes) Properties to set hardware and scheduling settings for an image. (see [below for nested schema](#nestedatt--config))
- `disk_format` (String) The disk format of the image. - `disk_format` (String) The disk format of the image.
- `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`image_id`". - `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`region`,`image_id`".
- `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container - `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container
- `min_disk_size` (Number) The minimum disk size of the image in GB. - `min_disk_size` (Number) The minimum disk size of the image in GB.
- `min_ram` (Number) The minimum RAM of the image in MB. - `min_ram` (Number) The minimum RAM of the image in MB.

View file

@ -63,6 +63,7 @@ stackit server machine-type list
### Optional ### Optional
- `region` (String) The resource region. If not defined, the provider region is used.
- `sort_ascending` (Boolean) Sort machine types by name ascending (`true`) or descending (`false`). Defaults to `false` - `sort_ascending` (Boolean) Sort machine types by name ascending (`true`) or descending (`false`). Defaults to `false`
### Read-Only ### Read-Only
@ -70,7 +71,7 @@ stackit server machine-type list
- `description` (String) Machine type description. - `description` (String) Machine type description.
- `disk` (Number) Disk size in GB. - `disk` (Number) Disk size in GB.
- `extra_specs` (Map of String) Extra specs (e.g., CPU type, overcommit ratio). - `extra_specs` (Map of String) Extra specs (e.g., CPU type, overcommit ratio).
- `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`image_id`". - `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`region`,`image_id`".
- `name` (String) Name of the machine type (e.g. 's1.2'). - `name` (String) Name of the machine type (e.g. 's1.2').
- `ram` (Number) RAM size in MB. - `ram` (Number) RAM size in MB.
- `vcpus` (Number) Number of vCPUs. - `vcpus` (Number) Number of vCPUs.

View file

@ -29,16 +29,16 @@ data "stackit_network_area" "example" {
### Read-Only ### Read-Only
- `default_nameservers` (List of String) List of DNS Servers/Nameservers. - `default_nameservers` (List of String, Deprecated) List of DNS Servers/Nameservers.
- `default_prefix_length` (Number) The default prefix length for networks in the network area. - `default_prefix_length` (Number, Deprecated) The default prefix length for networks in the network area.
- `id` (String) Terraform's internal resource ID. It is structured as "`organization_id`,`network_area_id`". - `id` (String) Terraform's internal resource ID. It is structured as "`organization_id`,`network_area_id`".
- `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container - `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container
- `max_prefix_length` (Number) The maximal prefix length for networks in the network area. - `max_prefix_length` (Number, Deprecated) The maximal prefix length for networks in the network area.
- `min_prefix_length` (Number) The minimal prefix length for networks in the network area. - `min_prefix_length` (Number, Deprecated) The minimal prefix length for networks in the network area.
- `name` (String) The name of the network area. - `name` (String) The name of the network area.
- `network_ranges` (Attributes List) List of Network ranges. (see [below for nested schema](#nestedatt--network_ranges)) - `network_ranges` (Attributes List, Deprecated) List of Network ranges. (see [below for nested schema](#nestedatt--network_ranges))
- `project_count` (Number) The amount of projects currently referencing this area. - `project_count` (Number) The amount of projects currently referencing this area.
- `transfer_network` (String) Classless Inter-Domain Routing (CIDR). - `transfer_network` (String, Deprecated) Classless Inter-Domain Routing (CIDR).
<a id="nestedatt--network_ranges"></a> <a id="nestedatt--network_ranges"></a>
### Nested Schema for `network_ranges` ### Nested Schema for `network_ranges`

View file

@ -0,0 +1,57 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "stackit_network_area_region Data Source - stackit"
subcategory: ""
description: |-
Network area region data source schema.
---
# stackit_network_area_region (Data Source)
Network area region data source schema.
## Example Usage
```terraform
data "stackit_network_area_region" "example" {
organization_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
network_area_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
}
```
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `network_area_id` (String) The network area ID.
- `organization_id` (String) STACKIT organization ID to which the network area is associated.
### Optional
- `region` (String) The resource region. If not defined, the provider region is used.
### Read-Only
- `id` (String) Terraform's internal resource ID. It is structured as "`organization_id`,`network_area_id`,`region`".
- `ipv4` (Attributes) The regional IPv4 config of a network area. (see [below for nested schema](#nestedatt--ipv4))
<a id="nestedatt--ipv4"></a>
### Nested Schema for `ipv4`
Read-Only:
- `default_nameservers` (List of String) List of DNS Servers/Nameservers.
- `default_prefix_length` (Number) The default prefix length for networks in the network area.
- `max_prefix_length` (Number) The maximal prefix length for networks in the network area.
- `min_prefix_length` (Number) The minimal prefix length for networks in the network area.
- `network_ranges` (Attributes List) List of Network ranges. (see [below for nested schema](#nestedatt--ipv4--network_ranges))
- `transfer_network` (String) IPv4 Classless Inter-Domain Routing (CIDR).
<a id="nestedatt--ipv4--network_ranges"></a>
### Nested Schema for `ipv4.network_ranges`
Read-Only:
- `network_range_id` (String)
- `prefix` (String) Classless Inter-Domain Routing (CIDR).

View file

@ -29,9 +29,30 @@ data "stackit_network_area_route" "example" {
- `network_area_route_id` (String) The network area route ID. - `network_area_route_id` (String) The network area route ID.
- `organization_id` (String) STACKIT organization ID to which the network area is associated. - `organization_id` (String) STACKIT organization ID to which the network area is associated.
### Optional
- `region` (String) The resource region. If not defined, the provider region is used.
### Read-Only ### Read-Only
- `id` (String) Terraform's internal data source ID. It is structured as "`organization_id`,`network_area_id`,`network_area_route_id`". - `destination` (Attributes) Destination of the route. (see [below for nested schema](#nestedatt--destination))
- `id` (String) Terraform's internal data source ID. It is structured as "`organization_id`,`region`,`network_area_id`,`network_area_route_id`".
- `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container - `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container
- `next_hop` (String) The IP address of the routing system, that will route the prefix configured. Should be a valid IPv4 address. - `next_hop` (Attributes) Next hop destination. (see [below for nested schema](#nestedatt--next_hop))
- `prefix` (String) The network, that is reachable though the Next Hop. Should use CIDR notation.
<a id="nestedatt--destination"></a>
### Nested Schema for `destination`
Read-Only:
- `type` (String) CIDRV type. Possible values are: `cidrv4`, `cidrv6`.
- `value` (String) An CIDR string.
<a id="nestedatt--next_hop"></a>
### Nested Schema for `next_hop`
Read-Only:
- `type` (String) Type of the next hop. Possible values are: `blackhole`, `internet`, `ipv4`, `ipv6`.
- `value` (String) Either IPv4 or IPv6 (not set for blackhole and internet).

View file

@ -29,11 +29,15 @@ data "stackit_network_interface" "example" {
- `network_interface_id` (String) The network interface ID. - `network_interface_id` (String) The network interface ID.
- `project_id` (String) STACKIT project ID to which the network interface is associated. - `project_id` (String) STACKIT project ID to which the network interface is associated.
### Optional
- `region` (String) The resource region. If not defined, the provider region is used.
### Read-Only ### Read-Only
- `allowed_addresses` (List of String) The list of CIDR (Classless Inter-Domain Routing) notations. - `allowed_addresses` (List of String) The list of CIDR (Classless Inter-Domain Routing) notations.
- `device` (String) The device UUID of the network interface. - `device` (String) The device UUID of the network interface.
- `id` (String) Terraform's internal data source ID. It is structured as "`project_id`,`network_id`,`network_interface_id`". - `id` (String) Terraform's internal data source ID. It is structured as "`project_id`,`region`,`network_id`,`network_interface_id`".
- `ipv4` (String) The IPv4 address. - `ipv4` (String) The IPv4 address.
- `labels` (Map of String) Labels are key-value string pairs which can be attached to a network interface. - `labels` (Map of String) Labels are key-value string pairs which can be attached to a network interface.
- `mac` (String) The MAC address of network interface. - `mac` (String) The MAC address of network interface.

View file

@ -27,9 +27,13 @@ data "stackit_public_ip" "example" {
- `project_id` (String) STACKIT project ID to which the public IP is associated. - `project_id` (String) STACKIT project ID to which the public IP is associated.
- `public_ip_id` (String) The public IP ID. - `public_ip_id` (String) The public IP ID.
### Optional
- `region` (String) The resource region. If not defined, the provider region is used.
### Read-Only ### Read-Only
- `id` (String) Terraform's internal datasource ID. It is structured as "`project_id`,`public_ip_id`". - `id` (String) Terraform's internal datasource ID. It is structured as "`project_id`,`region`,`public_ip_id`".
- `ip` (String) The IP address. - `ip` (String) The IP address.
- `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container - `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container
- `network_interface_id` (String) Associates the public IP with a network interface or a virtual IP (ID). - `network_interface_id` (String) Associates the public IP with a network interface or a virtual IP (ID).

View file

@ -27,10 +27,14 @@ data "stackit_security_group" "example" {
- `project_id` (String) STACKIT project ID to which the security group is associated. - `project_id` (String) STACKIT project ID to which the security group is associated.
- `security_group_id` (String) The security group ID. - `security_group_id` (String) The security group ID.
### Optional
- `region` (String) The resource region. If not defined, the provider region is used.
### Read-Only ### Read-Only
- `description` (String) The description of the security group. - `description` (String) The description of the security group.
- `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`security_group_id`". - `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`region`,`security_group_id`".
- `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container - `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container
- `name` (String) The name of the security group. - `name` (String) The name of the security group.
- `stateful` (Boolean) Configures if a security group is stateful or stateless. There can only be one type of security groups per network interface/server. - `stateful` (Boolean) Configures if a security group is stateful or stateless. There can only be one type of security groups per network interface/server.

View file

@ -29,13 +29,17 @@ data "stackit_security_group_rule" "example" {
- `security_group_id` (String) The security group ID. - `security_group_id` (String) The security group ID.
- `security_group_rule_id` (String) The security group rule ID. - `security_group_rule_id` (String) The security group rule ID.
### Optional
- `region` (String) The resource region. If not defined, the provider region is used.
### Read-Only ### Read-Only
- `description` (String) The description of the security group rule. - `description` (String) The description of the security group rule.
- `direction` (String) The direction of the traffic which the rule should match. Some of the possible values are: Possible values are: `ingress`, `egress`. - `direction` (String) The direction of the traffic which the rule should match. Some of the possible values are: Possible values are: `ingress`, `egress`.
- `ether_type` (String) The ethertype which the rule should match. - `ether_type` (String) The ethertype which the rule should match.
- `icmp_parameters` (Attributes) ICMP Parameters. (see [below for nested schema](#nestedatt--icmp_parameters)) - `icmp_parameters` (Attributes) ICMP Parameters. (see [below for nested schema](#nestedatt--icmp_parameters))
- `id` (String) Terraform's internal datasource ID. It is structured as "`project_id`,`security_group_id`,`security_group_rule_id`". - `id` (String) Terraform's internal datasource ID. It is structured as "`project_id`,`region`,`security_group_id`,`security_group_rule_id`".
- `ip_range` (String) The remote IP range which the rule should match. - `ip_range` (String) The remote IP range which the rule should match.
- `port_range` (Attributes) The range of ports. (see [below for nested schema](#nestedatt--port_range)) - `port_range` (Attributes) The range of ports. (see [below for nested schema](#nestedatt--port_range))
- `protocol` (Attributes) The internet protocol which the rule should match. (see [below for nested schema](#nestedatt--protocol)) - `protocol` (Attributes) The internet protocol which the rule should match. (see [below for nested schema](#nestedatt--protocol))

View file

@ -27,13 +27,17 @@ data "stackit_server" "example" {
- `project_id` (String) STACKIT project ID to which the server is associated. - `project_id` (String) STACKIT project ID to which the server is associated.
- `server_id` (String) The server ID. - `server_id` (String) The server ID.
### Optional
- `region` (String) The resource region. If not defined, the provider region is used.
### Read-Only ### Read-Only
- `affinity_group` (String) The affinity group the server is assigned to. - `affinity_group` (String) The affinity group the server is assigned to.
- `availability_zone` (String) The availability zone of the server. - `availability_zone` (String) The availability zone of the server.
- `boot_volume` (Attributes) The boot volume for the server (see [below for nested schema](#nestedatt--boot_volume)) - `boot_volume` (Attributes) The boot volume for the server (see [below for nested schema](#nestedatt--boot_volume))
- `created_at` (String) Date-time when the server was created - `created_at` (String) Date-time when the server was created
- `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`server_id`". - `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`region`,`server_id`".
- `image_id` (String) The image ID to be used for an ephemeral disk on the server. - `image_id` (String) The image ID to be used for an ephemeral disk on the server.
- `keypair_name` (String) The name of the keypair used during server creation. - `keypair_name` (String) The name of the keypair used during server creation.
- `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container - `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container

View file

@ -27,11 +27,15 @@ data "stackit_volume" "example" {
- `project_id` (String) STACKIT project ID to which the volume is associated. - `project_id` (String) STACKIT project ID to which the volume is associated.
- `volume_id` (String) The volume ID. - `volume_id` (String) The volume ID.
### Optional
- `region` (String) The resource region. If not defined, the provider region is used.
### Read-Only ### Read-Only
- `availability_zone` (String) The availability zone of the volume. - `availability_zone` (String) The availability zone of the volume.
- `description` (String) The description of the volume. - `description` (String) The description of the volume.
- `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`volume_id`". - `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`region`,`volume_id`".
- `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container - `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container
- `name` (String) The name of the volume. - `name` (String) The name of the volume.
- `performance_class` (String) The performance class of the volume. Possible values are documented in [Service plans BlockStorage](https://docs.stackit.cloud/products/storage/block-storage/basics/service-plans/#currently-available-service-plans-performance-classes) - `performance_class` (String) The performance class of the volume. Possible values are documented in [Service plans BlockStorage](https://docs.stackit.cloud/products/storage/block-storage/basics/service-plans/#currently-available-service-plans-performance-classes)

View file

@ -3,7 +3,7 @@
page_title: "stackit_affinity_group Resource - stackit" page_title: "stackit_affinity_group Resource - stackit"
subcategory: "" subcategory: ""
description: |- description: |-
Affinity Group schema. Must have a region specified in the provider configuration. Affinity Group schema.
Usage with server Usage with server
resource "stackit_affinity_group" "affinity-group" { resource "stackit_affinity_group" "affinity-group" {
@ -39,7 +39,7 @@ description: |-
# stackit_affinity_group (Resource) # stackit_affinity_group (Resource)
Affinity Group schema. Must have a `region` specified in the provider configuration. Affinity Group schema.
@ -91,7 +91,7 @@ resource "stackit_affinity_group" "example" {
# Only use the import statement, if you want to import an existing affinity group # Only use the import statement, if you want to import an existing affinity group
import { import {
to = stackit_affinity_group.import-example to = stackit_affinity_group.import-example
id = "${var.project_id},${var.affinity_group_id}" id = "${var.project_id},${var.region},${var.affinity_group_id}"
} }
``` ```
@ -104,8 +104,12 @@ import {
- `policy` (String) The policy of the affinity group. - `policy` (String) The policy of the affinity group.
- `project_id` (String) STACKIT Project ID to which the affinity group is associated. - `project_id` (String) STACKIT Project ID to which the affinity group is associated.
### Optional
- `region` (String) The resource region. If not defined, the provider region is used.
### Read-Only ### Read-Only
- `affinity_group_id` (String) The affinity group ID. - `affinity_group_id` (String) The affinity group ID.
- `id` (String) Terraform's internal resource identifier. It is structured as "`project_id`,`affinity_group_id`". - `id` (String) Terraform's internal resource identifier. It is structured as "`project_id`,`region`,`affinity_group_id`".
- `members` (List of String) The servers that are part of the affinity group. - `members` (List of String) The servers that are part of the affinity group.

View file

@ -31,7 +31,7 @@ resource "stackit_image" "example_image" {
# } # }
import { import {
to = stackit_image.import-example to = stackit_image.import-example
id = "${var.project_id},${var.image_id}" id = "${var.project_id},${var.region},${var.image_id}"
} }
``` ```
@ -51,11 +51,12 @@ import {
- `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container - `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container
- `min_disk_size` (Number) The minimum disk size of the image in GB. - `min_disk_size` (Number) The minimum disk size of the image in GB.
- `min_ram` (Number) The minimum RAM of the image in MB. - `min_ram` (Number) The minimum RAM of the image in MB.
- `region` (String) The resource region. If not defined, the provider region is used.
### Read-Only ### Read-Only
- `checksum` (Attributes) Representation of an image checksum. (see [below for nested schema](#nestedatt--checksum)) - `checksum` (Attributes) Representation of an image checksum. (see [below for nested schema](#nestedatt--checksum))
- `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`image_id`". - `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`region`,`image_id`".
- `image_id` (String) The image ID. - `image_id` (String) The image ID.
- `protected` (Boolean) Whether the image is protected. - `protected` (Boolean) Whether the image is protected.
- `scope` (String) The scope of the image. - `scope` (String) The scope of the image.

View file

@ -34,12 +34,11 @@ resource "stackit_network" "example_routed_network" {
} }
resource "stackit_network" "example_non_routed_network" { resource "stackit_network" "example_non_routed_network" {
project_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" project_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
name = "example-non-routed-network" name = "example-non-routed-network"
ipv4_nameservers = ["1.2.3.4", "5.6.7.8"] ipv4_nameservers = ["1.2.3.4", "5.6.7.8"]
ipv4_prefix_length = 24 ipv4_gateway = "10.1.2.3"
ipv4_gateway = "10.1.2.3" ipv4_prefix = "10.1.2.0/24"
ipv4_prefix = "10.1.2.0/24"
labels = { labels = {
"key" = "value" "key" = "value"
} }
@ -51,7 +50,7 @@ resource "stackit_network" "example_non_routed_network" {
# These attributes cannot be configured together: [ipv4_prefix,ipv4_prefix_length,ipv4_gateway] # These attributes cannot be configured together: [ipv4_prefix,ipv4_prefix_length,ipv4_gateway]
import { import {
to = stackit_network.import-example to = stackit_network.import-example
id = "${var.project_id},${var.network_id}" id = "${var.project_id},${var.region},${var.network_id}"
} }
``` ```
@ -77,15 +76,13 @@ import {
- `nameservers` (List of String, Deprecated) The nameservers of the network. This field is deprecated and will be removed in January 2026, use `ipv4_nameservers` to configure the nameservers for IPv4. - `nameservers` (List of String, Deprecated) The nameservers of the network. This field is deprecated and will be removed in January 2026, use `ipv4_nameservers` to configure the nameservers for IPv4.
- `no_ipv4_gateway` (Boolean) If set to `true`, the network doesn't have a gateway. - `no_ipv4_gateway` (Boolean) If set to `true`, the network doesn't have a gateway.
- `no_ipv6_gateway` (Boolean) If set to `true`, the network doesn't have a gateway. - `no_ipv6_gateway` (Boolean) If set to `true`, the network doesn't have a gateway.
- `region` (String) Can only be used when experimental "network" is set. - `region` (String) The resource region. If not defined, the provider region is used.
The resource region. If not defined, the provider region is used.
- `routed` (Boolean) If set to `true`, the network is routed and therefore accessible from other networks. - `routed` (Boolean) If set to `true`, the network is routed and therefore accessible from other networks.
- `routing_table_id` (String) Can only be used when experimental "network" is set. - `routing_table_id` (String) The ID of the routing table associated with the network.
The ID of the routing table associated with the network.
### Read-Only ### Read-Only
- `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`network_id`". - `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`region`,`network_id`".
- `ipv4_prefixes` (List of String) The IPv4 prefixes of the network. - `ipv4_prefixes` (List of String) The IPv4 prefixes of the network.
- `ipv6_prefixes` (List of String) The IPv6 prefixes of the network. - `ipv6_prefixes` (List of String) The IPv6 prefixes of the network.
- `network_id` (String) The network ID. - `network_id` (String) The network ID.

View file

@ -3,12 +3,12 @@
page_title: "stackit_network_area Resource - stackit" page_title: "stackit_network_area Resource - stackit"
subcategory: "" subcategory: ""
description: |- description: |-
Network area resource schema. Must have a region specified in the provider configuration. Network area resource schema.
--- ---
# stackit_network_area (Resource) # stackit_network_area (Resource)
Network area resource schema. Must have a `region` specified in the provider configuration. Network area resource schema.
## Example Usage ## Example Usage
@ -16,12 +16,6 @@ Network area resource schema. Must have a `region` specified in the provider con
resource "stackit_network_area" "example" { resource "stackit_network_area" "example" {
organization_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" organization_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
name = "example-network-area" name = "example-network-area"
network_ranges = [
{
prefix = "192.168.0.0/24"
}
]
transfer_network = "192.168.1.0/24"
labels = { labels = {
"key" = "value" "key" = "value"
} }
@ -40,17 +34,17 @@ import {
### Required ### Required
- `name` (String) The name of the network area. - `name` (String) The name of the network area.
- `network_ranges` (Attributes List) List of Network ranges. (see [below for nested schema](#nestedatt--network_ranges))
- `organization_id` (String) STACKIT organization ID to which the network area is associated. - `organization_id` (String) STACKIT organization ID to which the network area is associated.
- `transfer_network` (String) Classless Inter-Domain Routing (CIDR).
### Optional ### Optional
- `default_nameservers` (List of String) List of DNS Servers/Nameservers. - `default_nameservers` (List of String, Deprecated) List of DNS Servers/Nameservers for configuration of network area for region `eu01`.
- `default_prefix_length` (Number) The default prefix length for networks in the network area. - `default_prefix_length` (Number, Deprecated) The default prefix length for networks in the network area for region `eu01`.
- `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container - `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container
- `max_prefix_length` (Number) The maximal prefix length for networks in the network area. - `max_prefix_length` (Number, Deprecated) The maximal prefix length for networks in the network area for region `eu01`.
- `min_prefix_length` (Number) The minimal prefix length for networks in the network area. - `min_prefix_length` (Number, Deprecated) The minimal prefix length for networks in the network area for region `eu01`.
- `network_ranges` (Attributes List, Deprecated) List of Network ranges for configuration of network area for region `eu01`. (see [below for nested schema](#nestedatt--network_ranges))
- `transfer_network` (String, Deprecated) Classless Inter-Domain Routing (CIDR) for configuration of network area for region `eu01`.
### Read-Only ### Read-Only
@ -63,8 +57,8 @@ import {
Required: Required:
- `prefix` (String) Classless Inter-Domain Routing (CIDR). - `prefix` (String, Deprecated) Classless Inter-Domain Routing (CIDR).
Read-Only: Read-Only:
- `network_range_id` (String) - `network_range_id` (String, Deprecated)

View file

@ -0,0 +1,77 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "stackit_network_area_region Resource - stackit"
subcategory: ""
description: |-
Network area region resource schema.
---
# stackit_network_area_region (Resource)
Network area region resource schema.
## Example Usage
```terraform
resource "stackit_network_area_region" "example" {
organization_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
network_area_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
ipv4 = {
transfer_network = "10.1.2.0/24"
network_ranges = [
{
prefix = "10.0.0.0/16"
}
]
}
}
# Only use the import statement, if you want to import an existing network area region
import {
to = stackit_network_area_region.import-example
id = "${var.organization_id},${var.network_area_id},${var.region}"
}
```
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `ipv4` (Attributes) The regional IPv4 config of a network area. (see [below for nested schema](#nestedatt--ipv4))
- `network_area_id` (String) The network area ID.
- `organization_id` (String) STACKIT organization ID to which the network area is associated.
### Optional
- `region` (String) The resource region. If not defined, the provider region is used.
### Read-Only
- `id` (String) Terraform's internal resource ID. It is structured as "`organization_id`,`network_area_id`,`region`".
<a id="nestedatt--ipv4"></a>
### Nested Schema for `ipv4`
Required:
- `network_ranges` (Attributes List) List of Network ranges. (see [below for nested schema](#nestedatt--ipv4--network_ranges))
- `transfer_network` (String) IPv4 Classless Inter-Domain Routing (CIDR).
Optional:
- `default_nameservers` (List of String) List of DNS Servers/Nameservers.
- `default_prefix_length` (Number) The default prefix length for networks in the network area.
- `max_prefix_length` (Number) The maximal prefix length for networks in the network area.
- `min_prefix_length` (Number) The minimal prefix length for networks in the network area.
<a id="nestedatt--ipv4--network_ranges"></a>
### Nested Schema for `ipv4.network_ranges`
Required:
- `prefix` (String) Classless Inter-Domain Routing (CIDR).
Read-Only:
- `network_range_id` (String)

View file

@ -3,7 +3,7 @@
page_title: "stackit_network_area_route Resource - stackit" page_title: "stackit_network_area_route Resource - stackit"
subcategory: "" subcategory: ""
description: |- description: |-
Network area route resource schema. Must have a region specified in the provider configuration. Network area route resource schema. Must have a `region` specified in the provider configuration.
--- ---
# stackit_network_area_route (Resource) # stackit_network_area_route (Resource)
@ -16,8 +16,14 @@ Network area route resource schema. Must have a `region` specified in the provid
resource "stackit_network_area_route" "example" { resource "stackit_network_area_route" "example" {
organization_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" organization_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
network_area_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" network_area_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
prefix = "192.168.0.0/24" destination = {
next_hop = "192.168.0.0" type = "cidrv4"
value = "192.168.0.0/24"
}
next_hop = {
type = "ipv4"
value = "192.168.0.0"
}
labels = { labels = {
"key" = "value" "key" = "value"
} }
@ -26,7 +32,43 @@ resource "stackit_network_area_route" "example" {
# Only use the import statement, if you want to import an existing network area route # Only use the import statement, if you want to import an existing network area route
import { import {
to = stackit_network_area_route.import-example to = stackit_network_area_route.import-example
id = "${var.organization_id},${var.network_area_id},${var.network_area_route_id}" id = "${var.organization_id},${var.network_area_id},${var.region},${var.network_area_route_id}"
}
```
## Migration of IaaS resources from versions <= v0.74.0
The release of the STACKIT IaaS API v2 provides a lot of new features, but also includes some breaking changes
(when coming from v1 of the STACKIT IaaS API) which must be somehow represented on Terraform side. The
`stackit_network_area_route` resource did undergo some changes. See the example below how to migrate your resources.
### Breaking change: Network area route resource (stackit_network_area_route)
**Configuration for <= v0.74.0**
```terraform
resource "stackit_network_area_route" "example" {
organization_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
network_area_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
prefix = "192.168.0.0/24" # prefix field got removed for provider versions > v0.74.0, use the new destination field instead
next_hop = "192.168.0.0" # schema of the next_hop field changed, see below
}
```
**Configuration for > v0.74.0**
```terraform
resource "stackit_network_area_route" "example" {
organization_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
network_area_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
destination = { # the new 'destination' field replaces the old 'prefix' field
type = "cidrv4"
value = "192.168.0.0/24" # migration: put the value of the old 'prefix' field here
}
next_hop = {
type = "ipv4"
value = "192.168.0.0" # migration: put the value of the old 'next_hop' field here
}
} }
``` ```
@ -35,16 +77,38 @@ import {
### Required ### Required
- `destination` (Attributes) Destination of the route. (see [below for nested schema](#nestedatt--destination))
- `network_area_id` (String) The network area ID to which the network area route is associated. - `network_area_id` (String) The network area ID to which the network area route is associated.
- `next_hop` (String) The IP address of the routing system, that will route the prefix configured. Should be a valid IPv4 address. - `next_hop` (Attributes) Next hop destination. (see [below for nested schema](#nestedatt--next_hop))
- `organization_id` (String) STACKIT organization ID to which the network area is associated. - `organization_id` (String) STACKIT organization ID to which the network area is associated.
- `prefix` (String) The network, that is reachable though the Next Hop. Should use CIDR notation.
### Optional ### Optional
- `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container - `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container
- `region` (String) The resource region. If not defined, the provider region is used.
### Read-Only ### Read-Only
- `id` (String) Terraform's internal resource ID. It is structured as "`organization_id`,`network_area_id`,`network_area_route_id`". - `id` (String) Terraform's internal resource ID. It is structured as "`organization_id`,`network_area_id`,`region`,`network_area_route_id`".
- `network_area_route_id` (String) The network area route ID. - `network_area_route_id` (String) The network area route ID.
<a id="nestedatt--destination"></a>
### Nested Schema for `destination`
Required:
- `type` (String) CIDRV type. Possible values are: `cidrv4`, `cidrv6`. Only `cidrv4` is supported currently.
- `value` (String) An CIDR string.
<a id="nestedatt--next_hop"></a>
### Nested Schema for `next_hop`
Required:
- `type` (String) Type of the next hop. Possible values are: `blackhole`, `internet`, `ipv4`, `ipv6`. Only `ipv4` supported currently.
Optional:
- `value` (String) Either IPv4 or IPv6 (not set for blackhole and internet). Only IPv4 supported currently.

View file

@ -23,7 +23,7 @@ resource "stackit_network_interface" "example" {
# Only use the import statement, if you want to import an existing network interface # Only use the import statement, if you want to import an existing network interface
import { import {
to = stackit_network_interface.import-example to = stackit_network_interface.import-example
id = "${var.project_id},${var.network_id},${var.network_interface_id}" id = "${var.project_id},${var.region},${var.network_id},${var.network_interface_id}"
} }
``` ```
@ -41,13 +41,14 @@ import {
- `ipv4` (String) The IPv4 address. - `ipv4` (String) The IPv4 address.
- `labels` (Map of String) Labels are key-value string pairs which can be attached to a network interface. - `labels` (Map of String) Labels are key-value string pairs which can be attached to a network interface.
- `name` (String) The name of the network interface. - `name` (String) The name of the network interface.
- `region` (String) The resource region. If not defined, the provider region is used.
- `security` (Boolean) The Network Interface Security. If set to false, then no security groups will apply to this network interface. - `security` (Boolean) The Network Interface Security. If set to false, then no security groups will apply to this network interface.
- `security_group_ids` (List of String) The list of security group UUIDs. If security is set to false, setting this field will lead to an error. - `security_group_ids` (List of String) The list of security group UUIDs. If security is set to false, setting this field will lead to an error.
### Read-Only ### Read-Only
- `device` (String) The device UUID of the network interface. - `device` (String) The device UUID of the network interface.
- `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`network_id`,`network_interface_id`". - `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`region`,`network_id`,`network_interface_id`".
- `mac` (String) The MAC address of network interface. - `mac` (String) The MAC address of network interface.
- `network_interface_id` (String) The network interface ID. - `network_interface_id` (String) The network interface ID.
- `type` (String) Type of network interface. Some of the possible values are: Possible values are: `server`, `metadata`, `gateway`. - `type` (String) Type of network interface. Some of the possible values are: Possible values are: `server`, `metadata`, `gateway`.

View file

@ -24,7 +24,7 @@ resource "stackit_public_ip" "example" {
# Only use the import statement, if you want to import an existing public ip # Only use the import statement, if you want to import an existing public ip
import { import {
to = stackit_public_ip.import-example to = stackit_public_ip.import-example
id = "${var.project_id},${var.public_ip_id}" id = "${var.project_id},${var.region},${var.public_ip_id}"
} }
``` ```
@ -39,9 +39,10 @@ import {
- `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container - `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container
- `network_interface_id` (String) Associates the public IP with a network interface or a virtual IP (ID). If you are using this resource with a Kubernetes Load Balancer or any other resource which associates a network interface implicitly, use the lifecycle `ignore_changes` property in this field to prevent unintentional removal of the network interface due to drift in the Terraform state - `network_interface_id` (String) Associates the public IP with a network interface or a virtual IP (ID). If you are using this resource with a Kubernetes Load Balancer or any other resource which associates a network interface implicitly, use the lifecycle `ignore_changes` property in this field to prevent unintentional removal of the network interface due to drift in the Terraform state
- `region` (String) The resource region. If not defined, the provider region is used.
### Read-Only ### Read-Only
- `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`public_ip_id`". - `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`region`,`public_ip_id`".
- `ip` (String) The IP address. - `ip` (String) The IP address.
- `public_ip_id` (String) The public IP ID. - `public_ip_id` (String) The public IP ID.

View file

@ -27,7 +27,7 @@ resource "stackit_public_ip_associate" "example" {
# Only use the import statement, if you want to import an existing public ip associate # Only use the import statement, if you want to import an existing public ip associate
import { import {
to = stackit_public_ip_associate.import-example to = stackit_public_ip_associate.import-example
id = "${var.project_id},${var.public_ip_id},${var.network_interface_id}" id = "${var.project_id},${var.region},${var.public_ip_id},${var.network_interface_id}"
} }
``` ```
@ -40,7 +40,11 @@ import {
- `project_id` (String) STACKIT project ID to which the public IP is associated. - `project_id` (String) STACKIT project ID to which the public IP is associated.
- `public_ip_id` (String) The public IP ID. - `public_ip_id` (String) The public IP ID.
### Optional
- `region` (String) The resource region. If not defined, the provider region is used.
### Read-Only ### Read-Only
- `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`public_ip_id`,`network_interface_id`". - `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`region`,`public_ip_id`,`network_interface_id`".
- `ip` (String) The IP address. - `ip` (String) The IP address.

View file

@ -40,9 +40,10 @@ import {
- `description` (String) The description of the security group. - `description` (String) The description of the security group.
- `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container - `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container
- `region` (String) The resource region. If not defined, the provider region is used.
- `stateful` (Boolean) Configures if a security group is stateful or stateless. There can only be one type of security groups per network interface/server. - `stateful` (Boolean) Configures if a security group is stateful or stateless. There can only be one type of security groups per network interface/server.
### Read-Only ### Read-Only
- `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`security_group_id`". - `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`region`,`security_group_id`".
- `security_group_id` (String) The security group ID. - `security_group_id` (String) The security group ID.

View file

@ -52,11 +52,12 @@ import {
- `ip_range` (String) The remote IP range which the rule should match. - `ip_range` (String) The remote IP range which the rule should match.
- `port_range` (Attributes) The range of ports. This should only be provided if the protocol is not ICMP. (see [below for nested schema](#nestedatt--port_range)) - `port_range` (Attributes) The range of ports. This should only be provided if the protocol is not ICMP. (see [below for nested schema](#nestedatt--port_range))
- `protocol` (Attributes) The internet protocol which the rule should match. (see [below for nested schema](#nestedatt--protocol)) - `protocol` (Attributes) The internet protocol which the rule should match. (see [below for nested schema](#nestedatt--protocol))
- `region` (String) The resource region. If not defined, the provider region is used.
- `remote_security_group_id` (String) The remote security group which the rule should match. - `remote_security_group_id` (String) The remote security group which the rule should match.
### Read-Only ### Read-Only
- `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`security_group_id`,`security_group_rule_id`". - `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`region`,`security_group_id`,`security_group_rule_id`".
- `security_group_rule_id` (String) The security group rule ID. - `security_group_rule_id` (String) The security group rule ID.
<a id="nestedatt--icmp_parameters"></a> <a id="nestedatt--icmp_parameters"></a>

View file

@ -388,7 +388,7 @@ resource "stackit_server" "example" {
# } # }
import { import {
to = stackit_server.import-example to = stackit_server.import-example
id = "${var.project_id},${var.server_id}" id = "${var.project_id},${var.region},${var.server_id}"
} }
``` ```
@ -410,13 +410,14 @@ import {
- `image_id` (String) The image ID to be used for an ephemeral disk on the server. - `image_id` (String) The image ID to be used for an ephemeral disk on the server.
- `keypair_name` (String) The name of the keypair used during server creation. - `keypair_name` (String) The name of the keypair used during server creation.
- `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container - `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container
- `network_interfaces` (List of String) The IDs of network interfaces which should be attached to the server. Updating it will recreate the server. - `network_interfaces` (List of String) The IDs of network interfaces which should be attached to the server. Updating it will recreate the server. **Required when (re-)creating servers. Still marked as optional in the schema to not introduce breaking changes. There will be a migration path for this field soon.**
- `region` (String) The resource region. If not defined, the provider region is used.
- `user_data` (String) User data that is passed via cloud-init to the server. - `user_data` (String) User data that is passed via cloud-init to the server.
### Read-Only ### Read-Only
- `created_at` (String) Date-time when the server was created - `created_at` (String) Date-time when the server was created
- `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`server_id`". - `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`region`,`server_id`".
- `launched_at` (String) Date-time when the server was launched - `launched_at` (String) Date-time when the server was launched
- `server_id` (String) The server ID. - `server_id` (String) The server ID.
- `updated_at` (String) Date-time when the server was updated - `updated_at` (String) Date-time when the server was updated

View file

@ -3,12 +3,12 @@
page_title: "stackit_server_network_interface_attach Resource - stackit" page_title: "stackit_server_network_interface_attach Resource - stackit"
subcategory: "" subcategory: ""
description: |- description: |-
Network interface attachment resource schema. Attaches a network interface to a server. Must have a region specified in the provider configuration. The attachment only takes full effect after server reboot. Network interface attachment resource schema. Attaches a network interface to a server. The attachment only takes full effect after server reboot.
--- ---
# stackit_server_network_interface_attach (Resource) # stackit_server_network_interface_attach (Resource)
Network interface attachment resource schema. Attaches a network interface to a server. Must have a `region` specified in the provider configuration. The attachment only takes full effect after server reboot. Network interface attachment resource schema. Attaches a network interface to a server. The attachment only takes full effect after server reboot.
## Example Usage ## Example Usage
@ -22,7 +22,7 @@ resource "stackit_server_network_interface_attach" "attached_network_interface"
# Only use the import statement, if you want to import an existing server network interface attachment # Only use the import statement, if you want to import an existing server network interface attachment
import { import {
to = stackit_server_network_interface_attach.import-example to = stackit_server_network_interface_attach.import-example
id = "${var.project_id},${var.server_id},${var.network_interface_id}" id = "${var.project_id},${var.region},${var.server_id},${var.network_interface_id}"
} }
``` ```
@ -35,6 +35,10 @@ import {
- `project_id` (String) STACKIT project ID to which the network interface attachment is associated. - `project_id` (String) STACKIT project ID to which the network interface attachment is associated.
- `server_id` (String) The server ID. - `server_id` (String) The server ID.
### Optional
- `region` (String) The resource region. If not defined, the provider region is used.
### Read-Only ### Read-Only
- `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`server_id`,`network_interface_id`". - `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`region`,`server_id`,`network_interface_id`".

View file

@ -22,7 +22,7 @@ resource "stackit_server_service_account_attach" "attached_service_account" {
# Only use the import statement, if you want to import an existing server service account attachment # Only use the import statement, if you want to import an existing server service account attachment
import { import {
to = stackit_server_service_account_attach.import-example to = stackit_server_service_account_attach.import-example
id = "${var.project_id},${var.server_id},${var.service_account_email}" id = "${var.project_id},${var.region},${var.server_id},${var.service_account_email}"
} }
``` ```
@ -35,6 +35,10 @@ import {
- `server_id` (String) The server ID. - `server_id` (String) The server ID.
- `service_account_email` (String) The service account email. - `service_account_email` (String) The service account email.
### Optional
- `region` (String) The resource region. If not defined, the provider region is used.
### Read-Only ### Read-Only
- `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`server_id`,`service_account_email`". - `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`region`,`server_id`,`service_account_email`".

View file

@ -22,7 +22,7 @@ resource "stackit_server_volume_attach" "attached_volume" {
# Only use the import statement, if you want to import an existing server volume attachment # Only use the import statement, if you want to import an existing server volume attachment
import { import {
to = stackit_server_volume_attach.import-example to = stackit_server_volume_attach.import-example
id = "${var.project_id},${var.server_id},${var.volume_id}" id = "${var.project_id},${var.region},${var.server_id},${var.volume_id}"
} }
``` ```
@ -35,6 +35,10 @@ import {
- `server_id` (String) The server ID. - `server_id` (String) The server ID.
- `volume_id` (String) The volume ID. - `volume_id` (String) The volume ID.
### Optional
- `region` (String) The resource region. If not defined, the provider region is used.
### Read-Only ### Read-Only
- `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`server_id`,`volume_id`". - `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`region`,`server_id`,`volume_id`".

View file

@ -26,7 +26,7 @@ resource "stackit_volume" "example" {
# Only use the import statement, if you want to import an existing volume # Only use the import statement, if you want to import an existing volume
import { import {
to = stackit_volume.import-example to = stackit_volume.import-example
id = "${var.project_id},${var.volume_id}" id = "${var.project_id},${var.region},${var.volume_id}"
} }
``` ```
@ -44,12 +44,13 @@ import {
- `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container - `labels` (Map of String) Labels are key-value string pairs which can be attached to a resource container
- `name` (String) The name of the volume. - `name` (String) The name of the volume.
- `performance_class` (String) The performance class of the volume. Possible values are documented in [Service plans BlockStorage](https://docs.stackit.cloud/products/storage/block-storage/basics/service-plans/#currently-available-service-plans-performance-classes) - `performance_class` (String) The performance class of the volume. Possible values are documented in [Service plans BlockStorage](https://docs.stackit.cloud/products/storage/block-storage/basics/service-plans/#currently-available-service-plans-performance-classes)
- `region` (String) The resource region. If not defined, the provider region is used.
- `size` (Number) The size of the volume in GB. It can only be updated to a larger value than the current size. Either `size` or `source` must be provided - `size` (Number) The size of the volume in GB. It can only be updated to a larger value than the current size. Either `size` or `source` must be provided
- `source` (Attributes) The source of the volume. It can be either a volume, an image, a snapshot or a backup. Either `size` or `source` must be provided (see [below for nested schema](#nestedatt--source)) - `source` (Attributes) The source of the volume. It can be either a volume, an image, a snapshot or a backup. Either `size` or `source` must be provided (see [below for nested schema](#nestedatt--source))
### Read-Only ### Read-Only
- `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`volume_id`". - `id` (String) Terraform's internal resource ID. It is structured as "`project_id`,`region`,`volume_id`".
- `server_id` (String) The server ID of the server to which the volume is attached to. - `server_id` (String) The server ID of the server to which the volume is attached to.
- `volume_id` (String) The volume ID. - `volume_id` (String) The volume ID.

View file

@ -0,0 +1,4 @@
data "stackit_network_area_region" "example" {
organization_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
network_area_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
}

View file

@ -7,5 +7,5 @@ resource "stackit_affinity_group" "example" {
# Only use the import statement, if you want to import an existing affinity group # Only use the import statement, if you want to import an existing affinity group
import { import {
to = stackit_affinity_group.import-example to = stackit_affinity_group.import-example
id = "${var.project_id},${var.affinity_group_id}" id = "${var.project_id},${var.region},${var.affinity_group_id}"
} }

View file

@ -16,5 +16,5 @@ resource "stackit_image" "example_image" {
# } # }
import { import {
to = stackit_image.import-example to = stackit_image.import-example
id = "${var.project_id},${var.image_id}" id = "${var.project_id},${var.region},${var.image_id}"
} }

View file

@ -13,12 +13,11 @@ resource "stackit_network" "example_routed_network" {
} }
resource "stackit_network" "example_non_routed_network" { resource "stackit_network" "example_non_routed_network" {
project_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" project_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
name = "example-non-routed-network" name = "example-non-routed-network"
ipv4_nameservers = ["1.2.3.4", "5.6.7.8"] ipv4_nameservers = ["1.2.3.4", "5.6.7.8"]
ipv4_prefix_length = 24 ipv4_gateway = "10.1.2.3"
ipv4_gateway = "10.1.2.3" ipv4_prefix = "10.1.2.0/24"
ipv4_prefix = "10.1.2.0/24"
labels = { labels = {
"key" = "value" "key" = "value"
} }
@ -30,5 +29,5 @@ resource "stackit_network" "example_non_routed_network" {
# These attributes cannot be configured together: [ipv4_prefix,ipv4_prefix_length,ipv4_gateway] # These attributes cannot be configured together: [ipv4_prefix,ipv4_prefix_length,ipv4_gateway]
import { import {
to = stackit_network.import-example to = stackit_network.import-example
id = "${var.project_id},${var.network_id}" id = "${var.project_id},${var.region},${var.network_id}"
} }

View file

@ -1,12 +1,6 @@
resource "stackit_network_area" "example" { resource "stackit_network_area" "example" {
organization_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" organization_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
name = "example-network-area" name = "example-network-area"
network_ranges = [
{
prefix = "192.168.0.0/24"
}
]
transfer_network = "192.168.1.0/24"
labels = { labels = {
"key" = "value" "key" = "value"
} }

View file

@ -0,0 +1,18 @@
resource "stackit_network_area_region" "example" {
organization_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
network_area_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
ipv4 = {
transfer_network = "10.1.2.0/24"
network_ranges = [
{
prefix = "10.0.0.0/16"
}
]
}
}
# Only use the import statement, if you want to import an existing network area region
import {
to = stackit_network_area_region.import-example
id = "${var.organization_id},${var.network_area_id},${var.region}"
}

View file

@ -1,8 +1,14 @@
resource "stackit_network_area_route" "example" { resource "stackit_network_area_route" "example" {
organization_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" organization_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
network_area_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" network_area_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
prefix = "192.168.0.0/24" destination = {
next_hop = "192.168.0.0" type = "cidrv4"
value = "192.168.0.0/24"
}
next_hop = {
type = "ipv4"
value = "192.168.0.0"
}
labels = { labels = {
"key" = "value" "key" = "value"
} }
@ -11,5 +17,5 @@ resource "stackit_network_area_route" "example" {
# Only use the import statement, if you want to import an existing network area route # Only use the import statement, if you want to import an existing network area route
import { import {
to = stackit_network_area_route.import-example to = stackit_network_area_route.import-example
id = "${var.organization_id},${var.network_area_id},${var.network_area_route_id}" id = "${var.organization_id},${var.network_area_id},${var.region},${var.network_area_route_id}"
} }

View file

@ -8,5 +8,5 @@ resource "stackit_network_interface" "example" {
# Only use the import statement, if you want to import an existing network interface # Only use the import statement, if you want to import an existing network interface
import { import {
to = stackit_network_interface.import-example to = stackit_network_interface.import-example
id = "${var.project_id},${var.network_id},${var.network_interface_id}" id = "${var.project_id},${var.region},${var.network_id},${var.network_interface_id}"
} }

View file

@ -9,5 +9,5 @@ resource "stackit_public_ip" "example" {
# Only use the import statement, if you want to import an existing public ip # Only use the import statement, if you want to import an existing public ip
import { import {
to = stackit_public_ip.import-example to = stackit_public_ip.import-example
id = "${var.project_id},${var.public_ip_id}" id = "${var.project_id},${var.region},${var.public_ip_id}"
} }

View file

@ -7,5 +7,5 @@ resource "stackit_public_ip_associate" "example" {
# Only use the import statement, if you want to import an existing public ip associate # Only use the import statement, if you want to import an existing public ip associate
import { import {
to = stackit_public_ip_associate.import-example to = stackit_public_ip_associate.import-example
id = "${var.project_id},${var.public_ip_id},${var.network_interface_id}" id = "${var.project_id},${var.region},${var.public_ip_id},${var.network_interface_id}"
} }

View file

@ -23,5 +23,5 @@ resource "stackit_server" "example" {
# } # }
import { import {
to = stackit_server.import-example to = stackit_server.import-example
id = "${var.project_id},${var.server_id}" id = "${var.project_id},${var.region},${var.server_id}"
} }

View file

@ -7,5 +7,5 @@ resource "stackit_server_network_interface_attach" "attached_network_interface"
# Only use the import statement, if you want to import an existing server network interface attachment # Only use the import statement, if you want to import an existing server network interface attachment
import { import {
to = stackit_server_network_interface_attach.import-example to = stackit_server_network_interface_attach.import-example
id = "${var.project_id},${var.server_id},${var.network_interface_id}" id = "${var.project_id},${var.region},${var.server_id},${var.network_interface_id}"
} }

View file

@ -7,5 +7,5 @@ resource "stackit_server_service_account_attach" "attached_service_account" {
# Only use the import statement, if you want to import an existing server service account attachment # Only use the import statement, if you want to import an existing server service account attachment
import { import {
to = stackit_server_service_account_attach.import-example to = stackit_server_service_account_attach.import-example
id = "${var.project_id},${var.server_id},${var.service_account_email}" id = "${var.project_id},${var.region},${var.server_id},${var.service_account_email}"
} }

View file

@ -7,5 +7,5 @@ resource "stackit_server_volume_attach" "attached_volume" {
# Only use the import statement, if you want to import an existing server volume attachment # Only use the import statement, if you want to import an existing server volume attachment
import { import {
to = stackit_server_volume_attach.import-example to = stackit_server_volume_attach.import-example
id = "${var.project_id},${var.server_id},${var.volume_id}" id = "${var.project_id},${var.region},${var.server_id},${var.volume_id}"
} }

View file

@ -11,5 +11,5 @@ resource "stackit_volume" "example" {
# Only use the import statement, if you want to import an existing volume # Only use the import statement, if you want to import an existing volume
import { import {
to = stackit_volume.import-example to = stackit_volume.import-example
id = "${var.project_id},${var.volume_id}" id = "${var.project_id},${var.region},${var.volume_id}"
} }

6
go.mod
View file

@ -11,11 +11,11 @@ require (
github.com/hashicorp/terraform-plugin-go v0.29.0 github.com/hashicorp/terraform-plugin-go v0.29.0
github.com/hashicorp/terraform-plugin-log v0.10.0 github.com/hashicorp/terraform-plugin-log v0.10.0
github.com/hashicorp/terraform-plugin-testing v1.14.0 github.com/hashicorp/terraform-plugin-testing v1.14.0
github.com/stackitcloud/stackit-sdk-go/core v0.20.0 github.com/stackitcloud/stackit-sdk-go/core v0.20.1
github.com/stackitcloud/stackit-sdk-go/services/cdn v1.6.0 github.com/stackitcloud/stackit-sdk-go/services/cdn v1.6.0
github.com/stackitcloud/stackit-sdk-go/services/dns v0.17.1 github.com/stackitcloud/stackit-sdk-go/services/dns v0.17.1
github.com/stackitcloud/stackit-sdk-go/services/git v0.8.0 github.com/stackitcloud/stackit-sdk-go/services/git v0.8.0
github.com/stackitcloud/stackit-sdk-go/services/iaas v0.31.0 github.com/stackitcloud/stackit-sdk-go/services/iaas v1.3.0
github.com/stackitcloud/stackit-sdk-go/services/iaasalpha v0.1.21-alpha github.com/stackitcloud/stackit-sdk-go/services/iaasalpha v0.1.21-alpha
github.com/stackitcloud/stackit-sdk-go/services/kms v1.0.0 github.com/stackitcloud/stackit-sdk-go/services/kms v1.0.0
github.com/stackitcloud/stackit-sdk-go/services/loadbalancer v1.6.0 github.com/stackitcloud/stackit-sdk-go/services/loadbalancer v1.6.0
@ -29,7 +29,7 @@ require (
github.com/stackitcloud/stackit-sdk-go/services/postgresflex v1.2.1 github.com/stackitcloud/stackit-sdk-go/services/postgresflex v1.2.1
github.com/stackitcloud/stackit-sdk-go/services/rabbitmq v0.25.1 github.com/stackitcloud/stackit-sdk-go/services/rabbitmq v0.25.1
github.com/stackitcloud/stackit-sdk-go/services/redis v0.25.1 github.com/stackitcloud/stackit-sdk-go/services/redis v0.25.1
github.com/stackitcloud/stackit-sdk-go/services/resourcemanager v0.17.1 github.com/stackitcloud/stackit-sdk-go/services/resourcemanager v0.18.2
github.com/stackitcloud/stackit-sdk-go/services/scf v0.2.1 github.com/stackitcloud/stackit-sdk-go/services/scf v0.2.1
github.com/stackitcloud/stackit-sdk-go/services/secretsmanager v0.13.1 github.com/stackitcloud/stackit-sdk-go/services/secretsmanager v0.13.1
github.com/stackitcloud/stackit-sdk-go/services/serverbackup v1.3.2 github.com/stackitcloud/stackit-sdk-go/services/serverbackup v1.3.2

12
go.sum
View file

@ -149,8 +149,8 @@ github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 h1:n661drycOFuPLCN
github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
github.com/skeema/knownhosts v1.3.1 h1:X2osQ+RAjK76shCbvhHHHVl3ZlgDm8apHEHFqRjnBY8= github.com/skeema/knownhosts v1.3.1 h1:X2osQ+RAjK76shCbvhHHHVl3ZlgDm8apHEHFqRjnBY8=
github.com/skeema/knownhosts v1.3.1/go.mod h1:r7KTdC8l4uxWRyK2TpQZ/1o5HaSzh06ePQNxPwTcfiY= github.com/skeema/knownhosts v1.3.1/go.mod h1:r7KTdC8l4uxWRyK2TpQZ/1o5HaSzh06ePQNxPwTcfiY=
github.com/stackitcloud/stackit-sdk-go/core v0.20.0 h1:4rrUk6uT1g4nOn5/g1uXukP07Tux/o5xbMz/f/qE1rY= github.com/stackitcloud/stackit-sdk-go/core v0.20.1 h1:odiuhhRXmxvEvnVTeZSN9u98edvw2Cd3DcnkepncP3M=
github.com/stackitcloud/stackit-sdk-go/core v0.20.0/go.mod h1:fqto7M82ynGhEnpZU6VkQKYWYoFG5goC076JWXTUPRQ= github.com/stackitcloud/stackit-sdk-go/core v0.20.1/go.mod h1:fqto7M82ynGhEnpZU6VkQKYWYoFG5goC076JWXTUPRQ=
github.com/stackitcloud/stackit-sdk-go/services/authorization v0.9.0 h1:7ZKd3b+E/R4TEVShLTXxx5FrsuDuJBOyuVOuKTMa4mo= github.com/stackitcloud/stackit-sdk-go/services/authorization v0.9.0 h1:7ZKd3b+E/R4TEVShLTXxx5FrsuDuJBOyuVOuKTMa4mo=
github.com/stackitcloud/stackit-sdk-go/services/authorization v0.9.0/go.mod h1:/FoXa6hF77Gv8brrvLBCKa5ie1Xy9xn39yfHwaln9Tw= github.com/stackitcloud/stackit-sdk-go/services/authorization v0.9.0/go.mod h1:/FoXa6hF77Gv8brrvLBCKa5ie1Xy9xn39yfHwaln9Tw=
github.com/stackitcloud/stackit-sdk-go/services/cdn v1.6.0 h1:Q+qIdejeMsYMkbtVoI9BpGlKGdSVFRBhH/zj44SP8TM= github.com/stackitcloud/stackit-sdk-go/services/cdn v1.6.0 h1:Q+qIdejeMsYMkbtVoI9BpGlKGdSVFRBhH/zj44SP8TM=
@ -159,8 +159,8 @@ github.com/stackitcloud/stackit-sdk-go/services/dns v0.17.1 h1:CnhAMLql0MNmAeq4r
github.com/stackitcloud/stackit-sdk-go/services/dns v0.17.1/go.mod h1:7Bx85knfNSBxulPdJUFuBePXNee3cO+sOTYnUG6M+iQ= github.com/stackitcloud/stackit-sdk-go/services/dns v0.17.1/go.mod h1:7Bx85knfNSBxulPdJUFuBePXNee3cO+sOTYnUG6M+iQ=
github.com/stackitcloud/stackit-sdk-go/services/git v0.8.0 h1:/weT7P5Uwy1Qlhw0NidqtQBlbbb/dQehweDV/I9ShXg= github.com/stackitcloud/stackit-sdk-go/services/git v0.8.0 h1:/weT7P5Uwy1Qlhw0NidqtQBlbbb/dQehweDV/I9ShXg=
github.com/stackitcloud/stackit-sdk-go/services/git v0.8.0/go.mod h1:AXFfYBJZIW1o0W0zZEb/proQMhMsb3Nn5E1htS8NDPE= github.com/stackitcloud/stackit-sdk-go/services/git v0.8.0/go.mod h1:AXFfYBJZIW1o0W0zZEb/proQMhMsb3Nn5E1htS8NDPE=
github.com/stackitcloud/stackit-sdk-go/services/iaas v0.31.0 h1:dnEjyapuv8WwRN5vE2z6+4/+ZqQTBx+bX27x2nOF7Jw= github.com/stackitcloud/stackit-sdk-go/services/iaas v1.3.0 h1:U/x0tc487X9msMS5yZYjrBAAKrCx87Trmt0kh8JiARA=
github.com/stackitcloud/stackit-sdk-go/services/iaas v0.31.0/go.mod h1:854gnLR92NvAbJAA1xZEumrtNh1DoBP1FXTMvhwYA6w= github.com/stackitcloud/stackit-sdk-go/services/iaas v1.3.0/go.mod h1:6+5+RCDfU7eQN3+/SGdOtx7Bq9dEa2FrHz/jflgY1M4=
github.com/stackitcloud/stackit-sdk-go/services/iaasalpha v0.1.21-alpha h1:m1jq6a8dbUe+suFuUNdHmM/cSehpGLUtDbK1CqLqydg= github.com/stackitcloud/stackit-sdk-go/services/iaasalpha v0.1.21-alpha h1:m1jq6a8dbUe+suFuUNdHmM/cSehpGLUtDbK1CqLqydg=
github.com/stackitcloud/stackit-sdk-go/services/iaasalpha v0.1.21-alpha/go.mod h1:Nu1b5Phsv8plgZ51+fkxPVsU91ZJ5Ayz+cthilxdmQ8= github.com/stackitcloud/stackit-sdk-go/services/iaasalpha v0.1.21-alpha/go.mod h1:Nu1b5Phsv8plgZ51+fkxPVsU91ZJ5Ayz+cthilxdmQ8=
github.com/stackitcloud/stackit-sdk-go/services/kms v1.0.0 h1:zxoOv7Fu+FmdsvTKiKkbmLItrMKfL+QoVtz9ReEF30E= github.com/stackitcloud/stackit-sdk-go/services/kms v1.0.0 h1:zxoOv7Fu+FmdsvTKiKkbmLItrMKfL+QoVtz9ReEF30E=
@ -187,8 +187,8 @@ github.com/stackitcloud/stackit-sdk-go/services/rabbitmq v0.25.1 h1:ALrDCBih8Fu8
github.com/stackitcloud/stackit-sdk-go/services/rabbitmq v0.25.1/go.mod h1:+qGWSehoV0Js3FalgvT/bOgPj+UqW4I7lP5s8uAxP+o= github.com/stackitcloud/stackit-sdk-go/services/rabbitmq v0.25.1/go.mod h1:+qGWSehoV0Js3FalgvT/bOgPj+UqW4I7lP5s8uAxP+o=
github.com/stackitcloud/stackit-sdk-go/services/redis v0.25.1 h1:8uPt82Ez34OYMOijjEYxB1zUW6kiybkt6veQKl0AL68= github.com/stackitcloud/stackit-sdk-go/services/redis v0.25.1 h1:8uPt82Ez34OYMOijjEYxB1zUW6kiybkt6veQKl0AL68=
github.com/stackitcloud/stackit-sdk-go/services/redis v0.25.1/go.mod h1:1Y2GEICmZDt+kr8aGnBx/sjYVAIYHmtfC8xYi9oxNEE= github.com/stackitcloud/stackit-sdk-go/services/redis v0.25.1/go.mod h1:1Y2GEICmZDt+kr8aGnBx/sjYVAIYHmtfC8xYi9oxNEE=
github.com/stackitcloud/stackit-sdk-go/services/resourcemanager v0.17.1 h1:r7oaINTwLmIG31AaqKTuQHHFF8YNuYGzi+46DOuSjw4= github.com/stackitcloud/stackit-sdk-go/services/resourcemanager v0.18.2 h1:VDIXOvRNmSYMeF0qQ2+w4/ez04YutVDz73hSMuuOJ54=
github.com/stackitcloud/stackit-sdk-go/services/resourcemanager v0.17.1/go.mod h1:ipcrPRbwfQXHH18dJVfY7K5ujHF5dTT6isoXgmA7YwQ= github.com/stackitcloud/stackit-sdk-go/services/resourcemanager v0.18.2/go.mod h1:9zyEzPL4DnmU/SHq+SuMWTSO5BPxM1Z4g8Fp28n00ds=
github.com/stackitcloud/stackit-sdk-go/services/scf v0.2.1 h1:OdofRB6uj6lwN/TXLVHVrEOwNMG34MlFNwkiHD+eOts= github.com/stackitcloud/stackit-sdk-go/services/scf v0.2.1 h1:OdofRB6uj6lwN/TXLVHVrEOwNMG34MlFNwkiHD+eOts=
github.com/stackitcloud/stackit-sdk-go/services/scf v0.2.1/go.mod h1:5p7Xi8jadpJNDYr0t+07DXS104/RJLfhhA1r6P7PlGs= github.com/stackitcloud/stackit-sdk-go/services/scf v0.2.1/go.mod h1:5p7Xi8jadpJNDYr0t+07DXS104/RJLfhhA1r6P7PlGs=
github.com/stackitcloud/stackit-sdk-go/services/secretsmanager v0.13.1 h1:WKFzlHllql3JsVcAq+Y1m5pSMkvwp1qH3Vf2N7i8CPg= github.com/stackitcloud/stackit-sdk-go/services/secretsmanager v0.13.1 h1:WKFzlHllql3JsVcAq+Y1m5pSMkvwp1qH3Vf2N7i8CPg=

View file

@ -33,16 +33,18 @@ func NewAffinityGroupDatasource() datasource.DataSource {
} }
type affinityGroupDatasource struct { type affinityGroupDatasource struct {
client *iaas.APIClient client *iaas.APIClient
providerData core.ProviderData
} }
func (d *affinityGroupDatasource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) { func (d *affinityGroupDatasource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
providerData, ok := conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics) var ok bool
d.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
if !ok { if !ok {
return return
} }
apiClient := iaasUtils.ConfigureClient(ctx, &providerData, &resp.Diagnostics) apiClient := iaasUtils.ConfigureClient(ctx, &d.providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
@ -61,7 +63,7 @@ func (d *affinityGroupDatasource) Schema(_ context.Context, _ datasource.SchemaR
MarkdownDescription: descriptionMain, MarkdownDescription: descriptionMain,
Attributes: map[string]schema.Attribute{ Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{ "id": schema.StringAttribute{
Description: "Terraform's internal resource identifier. It is structured as \"`project_id`,`affinity_group_id`\".", Description: "Terraform's internal resource identifier. It is structured as \"`project_id`,`region`,`affinity_group_id`\".",
Computed: true, Computed: true,
}, },
"project_id": schema.StringAttribute{ "project_id": schema.StringAttribute{
@ -72,6 +74,11 @@ func (d *affinityGroupDatasource) Schema(_ context.Context, _ datasource.SchemaR
validate.NoSeparator(), validate.NoSeparator(),
}, },
}, },
"region": schema.StringAttribute{
Description: "The resource region. If not defined, the provider region is used.",
// the region cannot be found, so it has to be passed
Optional: true,
},
"affinity_group_id": schema.StringAttribute{ "affinity_group_id": schema.StringAttribute{
Description: "The affinity group ID.", Description: "The affinity group ID.",
Required: true, Required: true,
@ -117,14 +124,16 @@ func (d *affinityGroupDatasource) Read(ctx context.Context, req datasource.ReadR
return return
} }
projectId := model.ProjectId.ValueString() projectId := model.ProjectId.ValueString()
region := d.providerData.GetRegionWithOverride(model.Region)
affinityGroupId := model.AffinityGroupId.ValueString() affinityGroupId := model.AffinityGroupId.ValueString()
ctx = core.InitProviderContext(ctx) ctx = core.InitProviderContext(ctx)
ctx = tflog.SetField(ctx, "project_id", projectId) ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "affinity_group_id", affinityGroupId) ctx = tflog.SetField(ctx, "affinity_group_id", affinityGroupId)
affinityGroupResp, err := d.client.GetAffinityGroupExecute(ctx, projectId, affinityGroupId) affinityGroupResp, err := d.client.GetAffinityGroupExecute(ctx, projectId, region, affinityGroupId)
if err != nil { if err != nil {
utils.LogError( utils.LogError(
ctx, ctx,
@ -142,7 +151,7 @@ func (d *affinityGroupDatasource) Read(ctx context.Context, req datasource.ReadR
ctx = core.LogResponse(ctx) ctx = core.LogResponse(ctx)
err = mapFields(ctx, affinityGroupResp, &model) err = mapFields(ctx, affinityGroupResp, &model, region)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading affinity group", fmt.Sprintf("Processing API payload: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading affinity group", fmt.Sprintf("Processing API payload: %v", err))
} }

View file

@ -17,7 +17,6 @@ import (
"github.com/hashicorp/terraform-plugin-framework-validators/listvalidator" "github.com/hashicorp/terraform-plugin-framework-validators/listvalidator"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema" "github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
@ -33,12 +32,14 @@ var (
_ resource.Resource = &affinityGroupResource{} _ resource.Resource = &affinityGroupResource{}
_ resource.ResourceWithConfigure = &affinityGroupResource{} _ resource.ResourceWithConfigure = &affinityGroupResource{}
_ resource.ResourceWithImportState = &affinityGroupResource{} _ resource.ResourceWithImportState = &affinityGroupResource{}
_ resource.ResourceWithModifyPlan = &affinityGroupResource{}
) )
// Model is the provider's internal model // Model is the provider's internal model
type Model struct { type Model struct {
Id types.String `tfsdk:"id"` Id types.String `tfsdk:"id"`
ProjectId types.String `tfsdk:"project_id"` ProjectId types.String `tfsdk:"project_id"`
Region types.String `tfsdk:"region"`
AffinityGroupId types.String `tfsdk:"affinity_group_id"` AffinityGroupId types.String `tfsdk:"affinity_group_id"`
Name types.String `tfsdk:"name"` Name types.String `tfsdk:"name"`
Policy types.String `tfsdk:"policy"` Policy types.String `tfsdk:"policy"`
@ -51,7 +52,8 @@ func NewAffinityGroupResource() resource.Resource {
// affinityGroupResource is the resource implementation. // affinityGroupResource is the resource implementation.
type affinityGroupResource struct { type affinityGroupResource struct {
client *iaas.APIClient client *iaas.APIClient
providerData core.ProviderData
} }
// Metadata returns the resource type name. // Metadata returns the resource type name.
@ -59,14 +61,45 @@ func (r *affinityGroupResource) Metadata(_ context.Context, req resource.Metadat
resp.TypeName = req.ProviderTypeName + "_affinity_group" resp.TypeName = req.ProviderTypeName + "_affinity_group"
} }
// ModifyPlan implements resource.ResourceWithModifyPlan.
// Use the modifier to set the effective region in the current plan.
func (r *affinityGroupResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { // nolint:gocritic // function signature required by Terraform
var configModel Model
// skip initial empty configuration to avoid follow-up errors
if req.Config.Raw.IsNull() {
return
}
resp.Diagnostics.Append(req.Config.Get(ctx, &configModel)...)
if resp.Diagnostics.HasError() {
return
}
var planModel Model
resp.Diagnostics.Append(req.Plan.Get(ctx, &planModel)...)
if resp.Diagnostics.HasError() {
return
}
utils.AdaptRegion(ctx, configModel.Region, &planModel.Region, r.providerData.GetRegion(), resp)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.Plan.Set(ctx, planModel)...)
if resp.Diagnostics.HasError() {
return
}
}
// Configure adds the provider configured client to the resource. // Configure adds the provider configured client to the resource.
func (r *affinityGroupResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { func (r *affinityGroupResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
providerData, ok := conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics) var ok bool
r.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
if !ok { if !ok {
return return
} }
apiClient := iaasUtils.ConfigureClient(ctx, &providerData, &resp.Diagnostics) apiClient := iaasUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
@ -75,13 +108,13 @@ func (r *affinityGroupResource) Configure(ctx context.Context, req resource.Conf
} }
func (r *affinityGroupResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) { func (r *affinityGroupResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
description := "Affinity Group schema. Must have a `region` specified in the provider configuration." description := "Affinity Group schema."
resp.Schema = schema.Schema{ resp.Schema = schema.Schema{
Description: description, Description: description,
MarkdownDescription: description + "\n\n" + exampleUsageWithServer + policies, MarkdownDescription: description + "\n\n" + exampleUsageWithServer + policies,
Attributes: map[string]schema.Attribute{ Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{ "id": schema.StringAttribute{
Description: "Terraform's internal resource identifier. It is structured as \"`project_id`,`affinity_group_id`\".", Description: "Terraform's internal resource identifier. It is structured as \"`project_id`,`region`,`affinity_group_id`\".",
Computed: true, Computed: true,
PlanModifiers: []planmodifier.String{ PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(), stringplanmodifier.UseStateForUnknown(),
@ -98,6 +131,15 @@ func (r *affinityGroupResource) Schema(_ context.Context, _ resource.SchemaReque
validate.NoSeparator(), validate.NoSeparator(),
}, },
}, },
"region": schema.StringAttribute{
Description: "The resource region. If not defined, the provider region is used.",
Optional: true,
// must be computed to allow for storing the override value from the provider
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"affinity_group_id": schema.StringAttribute{ "affinity_group_id": schema.StringAttribute{
Description: "The affinity group ID.", Description: "The affinity group ID.",
Computed: true, Computed: true,
@ -153,19 +195,21 @@ func (r *affinityGroupResource) Create(ctx context.Context, req resource.CreateR
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
projectId := model.ProjectId.ValueString() projectId := model.ProjectId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = core.InitProviderContext(ctx) ctx = core.InitProviderContext(ctx)
ctx = tflog.SetField(ctx, "project_id", projectId)
// Create new affinityGroup // Create new affinityGroup
payload, err := toCreatePayload(&model) payload, err := toCreatePayload(&model)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating affinity group", fmt.Sprintf("Creating API payload: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating affinity group", fmt.Sprintf("Creating API payload: %v", err))
return return
} }
affinityGroupResp, err := r.client.CreateAffinityGroup(ctx, projectId).CreateAffinityGroupPayload(*payload).Execute() affinityGroupResp, err := r.client.CreateAffinityGroup(ctx, projectId, region).CreateAffinityGroupPayload(*payload).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating affinity group", fmt.Sprintf("Calling API: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating affinity group", fmt.Sprintf("Calling API: %v", err))
return return
@ -176,7 +220,7 @@ func (r *affinityGroupResource) Create(ctx context.Context, req resource.CreateR
ctx = tflog.SetField(ctx, "affinity_group_id", affinityGroupResp.Id) ctx = tflog.SetField(ctx, "affinity_group_id", affinityGroupResp.Id)
// Map response body to schema // Map response body to schema
err = mapFields(ctx, affinityGroupResp, &model) err = mapFields(ctx, affinityGroupResp, &model, region)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating affinity group", fmt.Sprintf("Processing API payload: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating affinity group", fmt.Sprintf("Processing API payload: %v", err))
return return
@ -199,14 +243,16 @@ func (r *affinityGroupResource) Read(ctx context.Context, req resource.ReadReque
return return
} }
projectId := model.ProjectId.ValueString() projectId := model.ProjectId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
affinityGroupId := model.AffinityGroupId.ValueString() affinityGroupId := model.AffinityGroupId.ValueString()
ctx = core.InitProviderContext(ctx) ctx = core.InitProviderContext(ctx)
ctx = tflog.SetField(ctx, "project_id", projectId) ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "affinity_group_id", affinityGroupId) ctx = tflog.SetField(ctx, "affinity_group_id", affinityGroupId)
affinityGroupResp, err := r.client.GetAffinityGroupExecute(ctx, projectId, affinityGroupId) affinityGroupResp, err := r.client.GetAffinityGroupExecute(ctx, projectId, region, affinityGroupId)
if err != nil { if err != nil {
oapiErr, ok := err.(*oapierror.GenericOpenAPIError) //nolint:errorlint //complaining that error.As should be used to catch wrapped errors, but this error should not be wrapped oapiErr, ok := err.(*oapierror.GenericOpenAPIError) //nolint:errorlint //complaining that error.As should be used to catch wrapped errors, but this error should not be wrapped
if ok && oapiErr.StatusCode == http.StatusNotFound { if ok && oapiErr.StatusCode == http.StatusNotFound {
@ -219,7 +265,7 @@ func (r *affinityGroupResource) Read(ctx context.Context, req resource.ReadReque
ctx = core.LogResponse(ctx) ctx = core.LogResponse(ctx)
err = mapFields(ctx, affinityGroupResp, &model) err = mapFields(ctx, affinityGroupResp, &model, region)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading affinity group", fmt.Sprintf("Processing API payload: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading affinity group", fmt.Sprintf("Processing API payload: %v", err))
} }
@ -247,15 +293,17 @@ func (r *affinityGroupResource) Delete(ctx context.Context, req resource.DeleteR
} }
projectId := model.ProjectId.ValueString() projectId := model.ProjectId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
affinityGroupId := model.AffinityGroupId.ValueString() affinityGroupId := model.AffinityGroupId.ValueString()
ctx = core.InitProviderContext(ctx) ctx = core.InitProviderContext(ctx)
ctx = tflog.SetField(ctx, "project_id", projectId) ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "affinity_group_id", affinityGroupId) ctx = tflog.SetField(ctx, "affinity_group_id", affinityGroupId)
// Delete existing affinity group // Delete existing affinity group
err := r.client.DeleteAffinityGroupExecute(ctx, projectId, affinityGroupId) err := r.client.DeleteAffinityGroupExecute(ctx, projectId, region, affinityGroupId)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting affinity group", fmt.Sprintf("Calling API: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting affinity group", fmt.Sprintf("Calling API: %v", err))
return return
@ -269,21 +317,20 @@ func (r *affinityGroupResource) Delete(ctx context.Context, req resource.DeleteR
func (r *affinityGroupResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { func (r *affinityGroupResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
idParts := strings.Split(req.ID, core.Separator) idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" { if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
core.LogAndAddError(ctx, &resp.Diagnostics, core.LogAndAddError(ctx, &resp.Diagnostics,
"Error importing affinity group", "Error importing affinity group",
fmt.Sprintf("Expected import indentifier with format: [project_id],[affinity_group_id], got: %q", req.ID), fmt.Sprintf("Expected import indentifier with format: [project_id],[region],[affinity_group_id], got: %q", req.ID),
) )
return return
} }
projectId := idParts[0] utils.SetAndLogStateFields(ctx, &resp.Diagnostics, &resp.State, map[string]any{
affinityGroupId := idParts[1] "project_id": idParts[0],
ctx = tflog.SetField(ctx, "project_id", projectId) "region": idParts[1],
ctx = tflog.SetField(ctx, "affinity_group_id", affinityGroupId) "affinity_group_id": idParts[2],
})
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), projectId)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("affinity_group_id"), affinityGroupId)...)
tflog.Info(ctx, "affinity group state imported") tflog.Info(ctx, "affinity group state imported")
} }
@ -301,7 +348,7 @@ func toCreatePayload(model *Model) (*iaas.CreateAffinityGroupPayload, error) {
}, nil }, nil
} }
func mapFields(ctx context.Context, affinityGroupResp *iaas.AffinityGroup, model *Model) error { func mapFields(ctx context.Context, affinityGroupResp *iaas.AffinityGroup, model *Model, region string) error {
if affinityGroupResp == nil { if affinityGroupResp == nil {
return fmt.Errorf("response input is nil") return fmt.Errorf("response input is nil")
} }
@ -319,7 +366,8 @@ func mapFields(ctx context.Context, affinityGroupResp *iaas.AffinityGroup, model
return fmt.Errorf("affinity group id not present") return fmt.Errorf("affinity group id not present")
} }
model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), affinityGroupId) model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), region, affinityGroupId)
model.Region = types.StringValue(region)
if affinityGroupResp.Members != nil && len(*affinityGroupResp.Members) > 0 { if affinityGroupResp.Members != nil && len(*affinityGroupResp.Members) > 0 {
members, diags := types.ListValueFrom(ctx, types.StringType, *affinityGroupResp.Members) members, diags := types.ListValueFrom(ctx, types.StringType, *affinityGroupResp.Members)

View file

@ -11,52 +11,56 @@ import (
) )
func TestMapFields(t *testing.T) { func TestMapFields(t *testing.T) {
type args struct {
state Model
input *iaas.AffinityGroup
region string
}
tests := []struct { tests := []struct {
description string description string
state Model args args
input *iaas.AffinityGroup
expected Model expected Model
isValid bool isValid bool
}{ }{
{ {
"default_values", description: "default_values",
Model{ args: args{
ProjectId: types.StringValue("pid"), state: Model{
AffinityGroupId: types.StringValue("aid"), ProjectId: types.StringValue("pid"),
AffinityGroupId: types.StringValue("aid"),
},
input: &iaas.AffinityGroup{
Id: utils.Ptr("aid"),
},
region: "eu01",
}, },
&iaas.AffinityGroup{ expected: Model{
Id: utils.Ptr("aid"), Id: types.StringValue("pid,eu01,aid"),
},
Model{
Id: types.StringValue("pid,aid"),
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
AffinityGroupId: types.StringValue("aid"), AffinityGroupId: types.StringValue("aid"),
Name: types.StringNull(), Name: types.StringNull(),
Policy: types.StringNull(), Policy: types.StringNull(),
Members: types.ListNull(types.StringType), Members: types.ListNull(types.StringType),
Region: types.StringValue("eu01"),
}, },
true, isValid: true,
}, },
{ {
"response_nil_fail", description: "response_nil_fail",
Model{},
nil,
Model{},
false,
}, },
{ {
"no_affinity_group_id", description: "no_affinity_group_id",
Model{ args: args{
ProjectId: types.StringValue("pid"), state: Model{
ProjectId: types.StringValue("pid"),
},
input: &iaas.AffinityGroup{},
}, },
&iaas.AffinityGroup{},
Model{},
false,
}, },
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.description, func(t *testing.T) { t.Run(tt.description, func(t *testing.T) {
err := mapFields(context.Background(), tt.input, &tt.state) err := mapFields(context.Background(), tt.args.input, &tt.args.state, tt.args.region)
if !tt.isValid && err == nil { if !tt.isValid && err == nil {
t.Fatalf("Should have failed") t.Fatalf("Should have failed")
} }
@ -64,7 +68,7 @@ func TestMapFields(t *testing.T) {
t.Fatalf("Should not have failed") t.Fatalf("Should not have failed")
} }
if tt.isValid { if tt.isValid {
diff := cmp.Diff(tt.state, tt.expected) diff := cmp.Diff(tt.args.state, tt.expected)
if diff != "" { if diff != "" {
t.Fatalf("Data does not match: %v", diff) t.Fatalf("Data does not match: %v", diff)
} }

File diff suppressed because it is too large Load diff

View file

@ -30,6 +30,7 @@ var (
type DataSourceModel struct { type DataSourceModel struct {
Id types.String `tfsdk:"id"` // needed by TF Id types.String `tfsdk:"id"` // needed by TF
ProjectId types.String `tfsdk:"project_id"` ProjectId types.String `tfsdk:"project_id"`
Region types.String `tfsdk:"region"`
ImageId types.String `tfsdk:"image_id"` ImageId types.String `tfsdk:"image_id"`
Name types.String `tfsdk:"name"` Name types.String `tfsdk:"name"`
DiskFormat types.String `tfsdk:"disk_format"` DiskFormat types.String `tfsdk:"disk_format"`
@ -49,7 +50,8 @@ func NewImageDataSource() datasource.DataSource {
// imageDataSource is the data source implementation. // imageDataSource is the data source implementation.
type imageDataSource struct { type imageDataSource struct {
client *iaas.APIClient client *iaas.APIClient
providerData core.ProviderData
} }
// Metadata returns the data source type name. // Metadata returns the data source type name.
@ -58,12 +60,13 @@ func (d *imageDataSource) Metadata(_ context.Context, req datasource.MetadataReq
} }
func (d *imageDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) { func (d *imageDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
providerData, ok := conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics) var ok bool
d.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
if !ok { if !ok {
return return
} }
apiClient := iaasUtils.ConfigureClient(ctx, &providerData, &resp.Diagnostics) apiClient := iaasUtils.ConfigureClient(ctx, &d.providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
@ -72,14 +75,14 @@ func (d *imageDataSource) Configure(ctx context.Context, req datasource.Configur
} }
// Schema defines the schema for the datasource. // Schema defines the schema for the datasource.
func (r *imageDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { func (d *imageDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
description := "Image datasource schema. Must have a `region` specified in the provider configuration." description := "Image datasource schema. Must have a `region` specified in the provider configuration."
resp.Schema = schema.Schema{ resp.Schema = schema.Schema{
MarkdownDescription: description, MarkdownDescription: description,
Description: description, Description: description,
Attributes: map[string]schema.Attribute{ Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{ "id": schema.StringAttribute{
Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`image_id`\".", Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`region`,`image_id`\".",
Computed: true, Computed: true,
}, },
"project_id": schema.StringAttribute{ "project_id": schema.StringAttribute{
@ -90,6 +93,11 @@ func (r *imageDataSource) Schema(_ context.Context, _ datasource.SchemaRequest,
validate.NoSeparator(), validate.NoSeparator(),
}, },
}, },
"region": schema.StringAttribute{
Description: "The resource region. If not defined, the provider region is used.",
// the region cannot be found, so it has to be passed
Optional: true,
},
"image_id": schema.StringAttribute{ "image_id": schema.StringAttribute{
Description: "The image ID.", Description: "The image ID.",
Required: true, Required: true,
@ -203,23 +211,26 @@ func (r *imageDataSource) Schema(_ context.Context, _ datasource.SchemaRequest,
} }
} }
// // Read refreshes the Terraform state with the latest data. // Read refreshes the Terraform state with the latest data.
func (r *imageDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform func (d *imageDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var model DataSourceModel var model DataSourceModel
diags := req.Config.Get(ctx, &model) diags := req.Config.Get(ctx, &model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
projectId := model.ProjectId.ValueString() projectId := model.ProjectId.ValueString()
region := d.providerData.GetRegionWithOverride(model.Region)
imageId := model.ImageId.ValueString() imageId := model.ImageId.ValueString()
ctx = core.InitProviderContext(ctx) ctx = core.InitProviderContext(ctx)
ctx = tflog.SetField(ctx, "project_id", projectId) ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "image_id", imageId) ctx = tflog.SetField(ctx, "image_id", imageId)
imageResp, err := r.client.GetImage(ctx, projectId, imageId).Execute() imageResp, err := d.client.GetImage(ctx, projectId, region, imageId).Execute()
if err != nil { if err != nil {
utils.LogError( utils.LogError(
ctx, ctx,
@ -238,7 +249,7 @@ func (r *imageDataSource) Read(ctx context.Context, req datasource.ReadRequest,
ctx = core.LogResponse(ctx) ctx = core.LogResponse(ctx)
// Map response body to schema // Map response body to schema
err = mapDataSourceFields(ctx, imageResp, &model) err = mapDataSourceFields(ctx, imageResp, &model, region)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading image", fmt.Sprintf("Processing API payload: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading image", fmt.Sprintf("Processing API payload: %v", err))
return return
@ -252,7 +263,7 @@ func (r *imageDataSource) Read(ctx context.Context, req datasource.ReadRequest,
tflog.Info(ctx, "image read") tflog.Info(ctx, "image read")
} }
func mapDataSourceFields(ctx context.Context, imageResp *iaas.Image, model *DataSourceModel) error { func mapDataSourceFields(ctx context.Context, imageResp *iaas.Image, model *DataSourceModel, region string) error {
if imageResp == nil { if imageResp == nil {
return fmt.Errorf("response input is nil") return fmt.Errorf("response input is nil")
} }
@ -269,7 +280,8 @@ func mapDataSourceFields(ctx context.Context, imageResp *iaas.Image, model *Data
return fmt.Errorf("image id not present") return fmt.Errorf("image id not present")
} }
model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), imageId) model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), region, imageId)
model.Region = types.StringValue(region)
// Map config // Map config
var configModel = &configModel{} var configModel = &configModel{}

View file

@ -12,69 +12,81 @@ import (
) )
func TestMapDataSourceFields(t *testing.T) { func TestMapDataSourceFields(t *testing.T) {
type args struct {
state DataSourceModel
input *iaas.Image
region string
}
tests := []struct { tests := []struct {
description string description string
state DataSourceModel args args
input *iaas.Image
expected DataSourceModel expected DataSourceModel
isValid bool isValid bool
}{ }{
{ {
"default_values", description: "default_values",
DataSourceModel{ args: args{
ProjectId: types.StringValue("pid"), state: DataSourceModel{
ImageId: types.StringValue("iid"), ProjectId: types.StringValue("pid"),
ImageId: types.StringValue("iid"),
},
input: &iaas.Image{
Id: utils.Ptr("iid"),
},
region: "eu01",
}, },
&iaas.Image{ expected: DataSourceModel{
Id: utils.Ptr("iid"), Id: types.StringValue("pid,eu01,iid"),
},
DataSourceModel{
Id: types.StringValue("pid,iid"),
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
ImageId: types.StringValue("iid"), ImageId: types.StringValue("iid"),
Labels: types.MapNull(types.StringType), Labels: types.MapNull(types.StringType),
Region: types.StringValue("eu01"),
}, },
true, isValid: true,
}, },
{ {
"simple_values", description: "simple_values",
DataSourceModel{ args: args{
ProjectId: types.StringValue("pid"), state: DataSourceModel{
ImageId: types.StringValue("iid"), ProjectId: types.StringValue("pid"),
ImageId: types.StringValue("iid"),
Region: types.StringValue("eu01"),
},
input: &iaas.Image{
Id: utils.Ptr("iid"),
Name: utils.Ptr("name"),
DiskFormat: utils.Ptr("format"),
MinDiskSize: utils.Ptr(int64(1)),
MinRam: utils.Ptr(int64(1)),
Protected: utils.Ptr(true),
Scope: utils.Ptr("scope"),
Config: &iaas.ImageConfig{
BootMenu: utils.Ptr(true),
CdromBus: iaas.NewNullableString(utils.Ptr("cdrom_bus")),
DiskBus: iaas.NewNullableString(utils.Ptr("disk_bus")),
NicModel: iaas.NewNullableString(utils.Ptr("model")),
OperatingSystem: utils.Ptr("os"),
OperatingSystemDistro: iaas.NewNullableString(utils.Ptr("os_distro")),
OperatingSystemVersion: iaas.NewNullableString(utils.Ptr("os_version")),
RescueBus: iaas.NewNullableString(utils.Ptr("rescue_bus")),
RescueDevice: iaas.NewNullableString(utils.Ptr("rescue_device")),
SecureBoot: utils.Ptr(true),
Uefi: utils.Ptr(true),
VideoModel: iaas.NewNullableString(utils.Ptr("model")),
VirtioScsi: utils.Ptr(true),
},
Checksum: &iaas.ImageChecksum{
Algorithm: utils.Ptr("algorithm"),
Digest: utils.Ptr("digest"),
},
Labels: &map[string]interface{}{
"key": "value",
},
},
region: "eu02",
}, },
&iaas.Image{ expected: DataSourceModel{
Id: utils.Ptr("iid"), Id: types.StringValue("pid,eu02,iid"),
Name: utils.Ptr("name"),
DiskFormat: utils.Ptr("format"),
MinDiskSize: utils.Ptr(int64(1)),
MinRam: utils.Ptr(int64(1)),
Protected: utils.Ptr(true),
Scope: utils.Ptr("scope"),
Config: &iaas.ImageConfig{
BootMenu: utils.Ptr(true),
CdromBus: iaas.NewNullableString(utils.Ptr("cdrom_bus")),
DiskBus: iaas.NewNullableString(utils.Ptr("disk_bus")),
NicModel: iaas.NewNullableString(utils.Ptr("model")),
OperatingSystem: utils.Ptr("os"),
OperatingSystemDistro: iaas.NewNullableString(utils.Ptr("os_distro")),
OperatingSystemVersion: iaas.NewNullableString(utils.Ptr("os_version")),
RescueBus: iaas.NewNullableString(utils.Ptr("rescue_bus")),
RescueDevice: iaas.NewNullableString(utils.Ptr("rescue_device")),
SecureBoot: utils.Ptr(true),
Uefi: utils.Ptr(true),
VideoModel: iaas.NewNullableString(utils.Ptr("model")),
VirtioScsi: utils.Ptr(true),
},
Checksum: &iaas.ImageChecksum{
Algorithm: utils.Ptr("algorithm"),
Digest: utils.Ptr("digest"),
},
Labels: &map[string]interface{}{
"key": "value",
},
},
DataSourceModel{
Id: types.StringValue("pid,iid"),
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
ImageId: types.StringValue("iid"), ImageId: types.StringValue("iid"),
Name: types.StringValue("name"), Name: types.StringValue("name"),
@ -105,47 +117,50 @@ func TestMapDataSourceFields(t *testing.T) {
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{ Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
"key": types.StringValue("value"), "key": types.StringValue("value"),
}), }),
Region: types.StringValue("eu02"),
}, },
true, isValid: true,
}, },
{ {
"empty_labels", description: "empty_labels",
DataSourceModel{ args: args{
state: DataSourceModel{
ProjectId: types.StringValue("pid"),
ImageId: types.StringValue("iid"),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{}),
},
input: &iaas.Image{
Id: utils.Ptr("iid"),
},
region: "eu01",
},
expected: DataSourceModel{
Id: types.StringValue("pid,eu01,iid"),
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
ImageId: types.StringValue("iid"), ImageId: types.StringValue("iid"),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{}), Labels: types.MapValueMust(types.StringType, map[string]attr.Value{}),
Region: types.StringValue("eu01"),
}, },
&iaas.Image{ isValid: true,
Id: utils.Ptr("iid"),
},
DataSourceModel{
Id: types.StringValue("pid,iid"),
ProjectId: types.StringValue("pid"),
ImageId: types.StringValue("iid"),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{}),
},
true,
}, },
{ {
"response_nil_fail", description: "response_nil_fail",
DataSourceModel{},
nil,
DataSourceModel{},
false,
}, },
{ {
"no_resource_id", description: "no_resource_id",
DataSourceModel{ args: args{
ProjectId: types.StringValue("pid"), state: DataSourceModel{
ProjectId: types.StringValue("pid"),
},
input: &iaas.Image{},
}, },
&iaas.Image{}, expected: DataSourceModel{},
DataSourceModel{}, isValid: false,
false,
}, },
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.description, func(t *testing.T) { t.Run(tt.description, func(t *testing.T) {
err := mapDataSourceFields(context.Background(), tt.input, &tt.state) err := mapDataSourceFields(context.Background(), tt.args.input, &tt.args.state, tt.args.region)
if !tt.isValid && err == nil { if !tt.isValid && err == nil {
t.Fatalf("Should have failed") t.Fatalf("Should have failed")
} }
@ -153,7 +168,7 @@ func TestMapDataSourceFields(t *testing.T) {
t.Fatalf("Should not have failed: %v", err) t.Fatalf("Should not have failed: %v", err)
} }
if tt.isValid { if tt.isValid {
diff := cmp.Diff(tt.state, tt.expected) diff := cmp.Diff(tt.args.state, tt.expected)
if diff != "" { if diff != "" {
t.Fatalf("Data does not match: %s", diff) t.Fatalf("Data does not match: %s", diff)
} }

View file

@ -15,7 +15,6 @@ import (
"github.com/hashicorp/terraform-plugin-framework/attr" "github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/diag" "github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema" "github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/boolplanmodifier" "github.com/hashicorp/terraform-plugin-framework/resource/schema/boolplanmodifier"
@ -40,11 +39,13 @@ var (
_ resource.Resource = &imageResource{} _ resource.Resource = &imageResource{}
_ resource.ResourceWithConfigure = &imageResource{} _ resource.ResourceWithConfigure = &imageResource{}
_ resource.ResourceWithImportState = &imageResource{} _ resource.ResourceWithImportState = &imageResource{}
_ resource.ResourceWithModifyPlan = &imageResource{}
) )
type Model struct { type Model struct {
Id types.String `tfsdk:"id"` // needed by TF Id types.String `tfsdk:"id"` // needed by TF
ProjectId types.String `tfsdk:"project_id"` ProjectId types.String `tfsdk:"project_id"`
Region types.String `tfsdk:"region"`
ImageId types.String `tfsdk:"image_id"` ImageId types.String `tfsdk:"image_id"`
Name types.String `tfsdk:"name"` Name types.String `tfsdk:"name"`
DiskFormat types.String `tfsdk:"disk_format"` DiskFormat types.String `tfsdk:"disk_format"`
@ -111,7 +112,8 @@ func NewImageResource() resource.Resource {
// imageResource is the resource implementation. // imageResource is the resource implementation.
type imageResource struct { type imageResource struct {
client *iaas.APIClient client *iaas.APIClient
providerData core.ProviderData
} }
// Metadata returns the resource type name. // Metadata returns the resource type name.
@ -119,14 +121,45 @@ func (r *imageResource) Metadata(_ context.Context, req resource.MetadataRequest
resp.TypeName = req.ProviderTypeName + "_image" resp.TypeName = req.ProviderTypeName + "_image"
} }
// ModifyPlan implements resource.ResourceWithModifyPlan.
// Use the modifier to set the effective region in the current plan.
func (r *imageResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { // nolint:gocritic // function signature required by Terraform
var configModel Model
// skip initial empty configuration to avoid follow-up errors
if req.Config.Raw.IsNull() {
return
}
resp.Diagnostics.Append(req.Config.Get(ctx, &configModel)...)
if resp.Diagnostics.HasError() {
return
}
var planModel Model
resp.Diagnostics.Append(req.Plan.Get(ctx, &planModel)...)
if resp.Diagnostics.HasError() {
return
}
utils.AdaptRegion(ctx, configModel.Region, &planModel.Region, r.providerData.GetRegion(), resp)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.Plan.Set(ctx, planModel)...)
if resp.Diagnostics.HasError() {
return
}
}
// Configure adds the provider configured client to the resource. // Configure adds the provider configured client to the resource.
func (r *imageResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { func (r *imageResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
providerData, ok := conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics) var ok bool
r.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
if !ok { if !ok {
return return
} }
apiClient := iaasUtils.ConfigureClient(ctx, &providerData, &resp.Diagnostics) apiClient := iaasUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
@ -140,7 +173,7 @@ func (r *imageResource) Schema(_ context.Context, _ resource.SchemaRequest, resp
Description: "Image resource schema. Must have a `region` specified in the provider configuration.", Description: "Image resource schema. Must have a `region` specified in the provider configuration.",
Attributes: map[string]schema.Attribute{ Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{ "id": schema.StringAttribute{
Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`image_id`\".", Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`region`,`image_id`\".",
Computed: true, Computed: true,
PlanModifiers: []planmodifier.String{ PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(), stringplanmodifier.UseStateForUnknown(),
@ -157,6 +190,15 @@ func (r *imageResource) Schema(_ context.Context, _ resource.SchemaRequest, resp
validate.NoSeparator(), validate.NoSeparator(),
}, },
}, },
"region": schema.StringAttribute{
Description: "The resource region. If not defined, the provider region is used.",
Optional: true,
// must be computed to allow for storing the override value from the provider
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"image_id": schema.StringAttribute{ "image_id": schema.StringAttribute{
Description: "The image ID.", Description: "The image ID.",
Computed: true, Computed: true,
@ -378,11 +420,12 @@ func (r *imageResource) Create(ctx context.Context, req resource.CreateRequest,
} }
projectId := model.ProjectId.ValueString() projectId := model.ProjectId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = core.InitProviderContext(ctx) ctx = core.InitProviderContext(ctx)
ctx = tflog.SetField(ctx, "project_id", projectId)
// Generate API request body from model // Generate API request body from model
payload, err := toCreatePayload(ctx, &model) payload, err := toCreatePayload(ctx, &model)
if err != nil { if err != nil {
@ -391,7 +434,7 @@ func (r *imageResource) Create(ctx context.Context, req resource.CreateRequest,
} }
// Create new image // Create new image
imageCreateResp, err := r.client.CreateImage(ctx, projectId).CreateImagePayload(*payload).Execute() imageCreateResp, err := r.client.CreateImage(ctx, projectId, region).CreateImagePayload(*payload).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating image", fmt.Sprintf("Calling API: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating image", fmt.Sprintf("Calling API: %v", err))
return return
@ -401,15 +444,15 @@ func (r *imageResource) Create(ctx context.Context, req resource.CreateRequest,
ctx = tflog.SetField(ctx, "image_id", *imageCreateResp.Id) ctx = tflog.SetField(ctx, "image_id", *imageCreateResp.Id)
// Get the image object, as the create response does not contain all fields // Get the image object, as the creation response does not contain all fields
image, err := r.client.GetImage(ctx, projectId, *imageCreateResp.Id).Execute() image, err := r.client.GetImage(ctx, projectId, region, *imageCreateResp.Id).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating image", fmt.Sprintf("Calling API: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating image", fmt.Sprintf("Calling API: %v", err))
return return
} }
// Map response body to schema // Map response body to schema
err = mapFields(ctx, image, &model) err = mapFields(ctx, image, &model, region)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating image", fmt.Sprintf("Processing API payload: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating image", fmt.Sprintf("Processing API payload: %v", err))
return return
@ -430,7 +473,7 @@ func (r *imageResource) Create(ctx context.Context, req resource.CreateRequest,
} }
// Wait for image to become available // Wait for image to become available
waiter := wait.UploadImageWaitHandler(ctx, r.client, projectId, *imageCreateResp.Id) waiter := wait.UploadImageWaitHandler(ctx, r.client, projectId, region, *imageCreateResp.Id)
waiter = waiter.SetTimeout(7 * 24 * time.Hour) // Set timeout to one week, to make the timeout useless waiter = waiter.SetTimeout(7 * 24 * time.Hour) // Set timeout to one week, to make the timeout useless
waitResp, err := waiter.WaitWithContext(ctx) waitResp, err := waiter.WaitWithContext(ctx)
if err != nil { if err != nil {
@ -439,7 +482,7 @@ func (r *imageResource) Create(ctx context.Context, req resource.CreateRequest,
} }
// Map response body to schema // Map response body to schema
err = mapFields(ctx, waitResp, &model) err = mapFields(ctx, waitResp, &model, region)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating image", fmt.Sprintf("Processing API payload: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating image", fmt.Sprintf("Processing API payload: %v", err))
return return
@ -454,7 +497,7 @@ func (r *imageResource) Create(ctx context.Context, req resource.CreateRequest,
tflog.Info(ctx, "Image created") tflog.Info(ctx, "Image created")
} }
// // Read refreshes the Terraform state with the latest data. // Read refreshes the Terraform state with the latest data.
func (r *imageResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform func (r *imageResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var model Model var model Model
diags := req.State.Get(ctx, &model) diags := req.State.Get(ctx, &model)
@ -462,15 +505,18 @@ func (r *imageResource) Read(ctx context.Context, req resource.ReadRequest, resp
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
projectId := model.ProjectId.ValueString() projectId := model.ProjectId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
imageId := model.ImageId.ValueString() imageId := model.ImageId.ValueString()
ctx = core.InitProviderContext(ctx) ctx = core.InitProviderContext(ctx)
ctx = tflog.SetField(ctx, "project_id", projectId) ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "image_id", imageId) ctx = tflog.SetField(ctx, "image_id", imageId)
imageResp, err := r.client.GetImage(ctx, projectId, imageId).Execute() imageResp, err := r.client.GetImage(ctx, projectId, region, imageId).Execute()
if err != nil { if err != nil {
oapiErr, ok := err.(*oapierror.GenericOpenAPIError) //nolint:errorlint //complaining that error.As should be used to catch wrapped errors, but this error should not be wrapped oapiErr, ok := err.(*oapierror.GenericOpenAPIError) //nolint:errorlint //complaining that error.As should be used to catch wrapped errors, but this error should not be wrapped
if ok && oapiErr.StatusCode == http.StatusNotFound { if ok && oapiErr.StatusCode == http.StatusNotFound {
@ -484,7 +530,7 @@ func (r *imageResource) Read(ctx context.Context, req resource.ReadRequest, resp
ctx = core.LogResponse(ctx) ctx = core.LogResponse(ctx)
// Map response body to schema // Map response body to schema
err = mapFields(ctx, imageResp, &model) err = mapFields(ctx, imageResp, &model, region)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading image", fmt.Sprintf("Processing API payload: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading image", fmt.Sprintf("Processing API payload: %v", err))
return return
@ -507,12 +553,15 @@ func (r *imageResource) Update(ctx context.Context, req resource.UpdateRequest,
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
projectId := model.ProjectId.ValueString() projectId := model.ProjectId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
imageId := model.ImageId.ValueString() imageId := model.ImageId.ValueString()
ctx = core.InitProviderContext(ctx) ctx = core.InitProviderContext(ctx)
ctx = tflog.SetField(ctx, "project_id", projectId) ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "image_id", imageId) ctx = tflog.SetField(ctx, "image_id", imageId)
// Retrieve values from state // Retrieve values from state
@ -530,7 +579,7 @@ func (r *imageResource) Update(ctx context.Context, req resource.UpdateRequest,
return return
} }
// Update existing image // Update existing image
updatedImage, err := r.client.UpdateImage(ctx, projectId, imageId).UpdateImagePayload(*payload).Execute() updatedImage, err := r.client.UpdateImage(ctx, projectId, region, imageId).UpdateImagePayload(*payload).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating image", fmt.Sprintf("Calling API: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating image", fmt.Sprintf("Calling API: %v", err))
return return
@ -538,7 +587,7 @@ func (r *imageResource) Update(ctx context.Context, req resource.UpdateRequest,
ctx = core.LogResponse(ctx) ctx = core.LogResponse(ctx)
err = mapFields(ctx, updatedImage, &model) err = mapFields(ctx, updatedImage, &model, region)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating image", fmt.Sprintf("Processing API payload: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating image", fmt.Sprintf("Processing API payload: %v", err))
return return
@ -563,14 +612,15 @@ func (r *imageResource) Delete(ctx context.Context, req resource.DeleteRequest,
projectId := model.ProjectId.ValueString() projectId := model.ProjectId.ValueString()
imageId := model.ImageId.ValueString() imageId := model.ImageId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "image_id", imageId)
ctx = tflog.SetField(ctx, "region", region)
ctx = core.InitProviderContext(ctx) ctx = core.InitProviderContext(ctx)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "image_id", imageId)
// Delete existing image // Delete existing image
err := r.client.DeleteImage(ctx, projectId, imageId).Execute() err := r.client.DeleteImage(ctx, projectId, region, imageId).Execute()
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting image", fmt.Sprintf("Calling API: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting image", fmt.Sprintf("Calling API: %v", err))
return return
@ -578,7 +628,7 @@ func (r *imageResource) Delete(ctx context.Context, req resource.DeleteRequest,
ctx = core.LogResponse(ctx) ctx = core.LogResponse(ctx)
_, err = wait.DeleteImageWaitHandler(ctx, r.client, projectId, imageId).WaitWithContext(ctx) _, err = wait.DeleteImageWaitHandler(ctx, r.client, projectId, region, imageId).WaitWithContext(ctx)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting image", fmt.Sprintf("image deletion waiting: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting image", fmt.Sprintf("image deletion waiting: %v", err))
return return
@ -588,29 +638,28 @@ func (r *imageResource) Delete(ctx context.Context, req resource.DeleteRequest,
} }
// ImportState imports a resource into the Terraform state on success. // ImportState imports a resource into the Terraform state on success.
// The expected format of the resource import identifier is: project_id,image_id // The expected format of the resource import identifier is: project_id,region,image_id
func (r *imageResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { func (r *imageResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
idParts := strings.Split(req.ID, core.Separator) idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" { if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
core.LogAndAddError(ctx, &resp.Diagnostics, core.LogAndAddError(ctx, &resp.Diagnostics,
"Error importing image", "Error importing image",
fmt.Sprintf("Expected import identifier with format: [project_id],[image_id] Got: %q", req.ID), fmt.Sprintf("Expected import identifier with format: [project_id],[region],[image_id] Got: %q", req.ID),
) )
return return
} }
projectId := idParts[0] utils.SetAndLogStateFields(ctx, &resp.Diagnostics, &resp.State, map[string]any{
imageId := idParts[1] "project_id": idParts[0],
ctx = tflog.SetField(ctx, "project_id", projectId) "region": idParts[1],
ctx = tflog.SetField(ctx, "image_id", imageId) "image_id": idParts[2],
})
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), projectId)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("image_id"), imageId)...)
tflog.Info(ctx, "Image state imported") tflog.Info(ctx, "Image state imported")
} }
func mapFields(ctx context.Context, imageResp *iaas.Image, model *Model) error { func mapFields(ctx context.Context, imageResp *iaas.Image, model *Model, region string) error {
if imageResp == nil { if imageResp == nil {
return fmt.Errorf("response input is nil") return fmt.Errorf("response input is nil")
} }
@ -627,7 +676,8 @@ func mapFields(ctx context.Context, imageResp *iaas.Image, model *Model) error {
return fmt.Errorf("image id not present") return fmt.Errorf("image id not present")
} }
model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), imageId) model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), region, imageId)
model.Region = types.StringValue(region)
// Map config // Map config
var configModel = &configModel{} var configModel = &configModel{}

View file

@ -17,69 +17,81 @@ import (
) )
func TestMapFields(t *testing.T) { func TestMapFields(t *testing.T) {
type args struct {
state Model
input *iaas.Image
region string
}
tests := []struct { tests := []struct {
description string description string
state Model args args
input *iaas.Image
expected Model expected Model
isValid bool isValid bool
}{ }{
{ {
"default_values", description: "default_values",
Model{ args: args{
ProjectId: types.StringValue("pid"), state: Model{
ImageId: types.StringValue("iid"), ProjectId: types.StringValue("pid"),
ImageId: types.StringValue("iid"),
},
input: &iaas.Image{
Id: utils.Ptr("iid"),
},
region: "eu01",
}, },
&iaas.Image{ expected: Model{
Id: utils.Ptr("iid"), Id: types.StringValue("pid,eu01,iid"),
},
Model{
Id: types.StringValue("pid,iid"),
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
ImageId: types.StringValue("iid"), ImageId: types.StringValue("iid"),
Labels: types.MapNull(types.StringType), Labels: types.MapNull(types.StringType),
Region: types.StringValue("eu01"),
}, },
true, isValid: true,
}, },
{ {
"simple_values", description: "simple_values",
Model{ args: args{
ProjectId: types.StringValue("pid"), state: Model{
ImageId: types.StringValue("iid"), ProjectId: types.StringValue("pid"),
ImageId: types.StringValue("iid"),
Region: types.StringValue("eu01"),
},
input: &iaas.Image{
Id: utils.Ptr("iid"),
Name: utils.Ptr("name"),
DiskFormat: utils.Ptr("format"),
MinDiskSize: utils.Ptr(int64(1)),
MinRam: utils.Ptr(int64(1)),
Protected: utils.Ptr(true),
Scope: utils.Ptr("scope"),
Config: &iaas.ImageConfig{
BootMenu: utils.Ptr(true),
CdromBus: iaas.NewNullableString(utils.Ptr("cdrom_bus")),
DiskBus: iaas.NewNullableString(utils.Ptr("disk_bus")),
NicModel: iaas.NewNullableString(utils.Ptr("model")),
OperatingSystem: utils.Ptr("os"),
OperatingSystemDistro: iaas.NewNullableString(utils.Ptr("os_distro")),
OperatingSystemVersion: iaas.NewNullableString(utils.Ptr("os_version")),
RescueBus: iaas.NewNullableString(utils.Ptr("rescue_bus")),
RescueDevice: iaas.NewNullableString(utils.Ptr("rescue_device")),
SecureBoot: utils.Ptr(true),
Uefi: utils.Ptr(true),
VideoModel: iaas.NewNullableString(utils.Ptr("model")),
VirtioScsi: utils.Ptr(true),
},
Checksum: &iaas.ImageChecksum{
Algorithm: utils.Ptr("algorithm"),
Digest: utils.Ptr("digest"),
},
Labels: &map[string]interface{}{
"key": "value",
},
},
region: "eu02",
}, },
&iaas.Image{ expected: Model{
Id: utils.Ptr("iid"), Id: types.StringValue("pid,eu02,iid"),
Name: utils.Ptr("name"),
DiskFormat: utils.Ptr("format"),
MinDiskSize: utils.Ptr(int64(1)),
MinRam: utils.Ptr(int64(1)),
Protected: utils.Ptr(true),
Scope: utils.Ptr("scope"),
Config: &iaas.ImageConfig{
BootMenu: utils.Ptr(true),
CdromBus: iaas.NewNullableString(utils.Ptr("cdrom_bus")),
DiskBus: iaas.NewNullableString(utils.Ptr("disk_bus")),
NicModel: iaas.NewNullableString(utils.Ptr("model")),
OperatingSystem: utils.Ptr("os"),
OperatingSystemDistro: iaas.NewNullableString(utils.Ptr("os_distro")),
OperatingSystemVersion: iaas.NewNullableString(utils.Ptr("os_version")),
RescueBus: iaas.NewNullableString(utils.Ptr("rescue_bus")),
RescueDevice: iaas.NewNullableString(utils.Ptr("rescue_device")),
SecureBoot: utils.Ptr(true),
Uefi: utils.Ptr(true),
VideoModel: iaas.NewNullableString(utils.Ptr("model")),
VirtioScsi: utils.Ptr(true),
},
Checksum: &iaas.ImageChecksum{
Algorithm: utils.Ptr("algorithm"),
Digest: utils.Ptr("digest"),
},
Labels: &map[string]interface{}{
"key": "value",
},
},
Model{
Id: types.StringValue("pid,iid"),
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
ImageId: types.StringValue("iid"), ImageId: types.StringValue("iid"),
Name: types.StringValue("name"), Name: types.StringValue("name"),
@ -110,47 +122,48 @@ func TestMapFields(t *testing.T) {
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{ Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
"key": types.StringValue("value"), "key": types.StringValue("value"),
}), }),
Region: types.StringValue("eu02"),
}, },
true, isValid: true,
}, },
{ {
"empty_labels", description: "empty_labels",
Model{ args: args{
state: Model{
ProjectId: types.StringValue("pid"),
ImageId: types.StringValue("iid"),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{}),
},
input: &iaas.Image{
Id: utils.Ptr("iid"),
},
region: "eu01",
},
expected: Model{
Id: types.StringValue("pid,eu01,iid"),
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
ImageId: types.StringValue("iid"), ImageId: types.StringValue("iid"),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{}), Labels: types.MapValueMust(types.StringType, map[string]attr.Value{}),
Region: types.StringValue("eu01"),
}, },
&iaas.Image{ isValid: true,
Id: utils.Ptr("iid"),
},
Model{
Id: types.StringValue("pid,iid"),
ProjectId: types.StringValue("pid"),
ImageId: types.StringValue("iid"),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{}),
},
true,
}, },
{ {
"response_nil_fail", description: "response_nil_fail",
Model{},
nil,
Model{},
false,
}, },
{ {
"no_resource_id", description: "no_resource_id",
Model{ args: args{
ProjectId: types.StringValue("pid"), state: Model{
ProjectId: types.StringValue("pid"),
},
input: &iaas.Image{},
}, },
&iaas.Image{},
Model{},
false,
}, },
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.description, func(t *testing.T) { t.Run(tt.description, func(t *testing.T) {
err := mapFields(context.Background(), tt.input, &tt.state) err := mapFields(context.Background(), tt.args.input, &tt.args.state, tt.args.region)
if !tt.isValid && err == nil { if !tt.isValid && err == nil {
t.Fatalf("Should have failed") t.Fatalf("Should have failed")
} }
@ -158,7 +171,7 @@ func TestMapFields(t *testing.T) {
t.Fatalf("Should not have failed: %v", err) t.Fatalf("Should not have failed: %v", err)
} }
if tt.isValid { if tt.isValid {
diff := cmp.Diff(tt.state, tt.expected) diff := cmp.Diff(tt.args.state, tt.expected)
if diff != "" { if diff != "" {
t.Fatalf("Data does not match: %s", diff) t.Fatalf("Data does not match: %s", diff)
} }

View file

@ -36,6 +36,7 @@ var (
type DataSourceModel struct { type DataSourceModel struct {
Id types.String `tfsdk:"id"` // needed by TF Id types.String `tfsdk:"id"` // needed by TF
ProjectId types.String `tfsdk:"project_id"` ProjectId types.String `tfsdk:"project_id"`
Region types.String `tfsdk:"region"`
ImageId types.String `tfsdk:"image_id"` ImageId types.String `tfsdk:"image_id"`
Name types.String `tfsdk:"name"` Name types.String `tfsdk:"name"`
NameRegex types.String `tfsdk:"name_regex"` NameRegex types.String `tfsdk:"name_regex"`
@ -113,7 +114,8 @@ func NewImageV2DataSource() datasource.DataSource {
// imageDataV2Source is the data source implementation. // imageDataV2Source is the data source implementation.
type imageDataV2Source struct { type imageDataV2Source struct {
client *iaas.APIClient client *iaas.APIClient
providerData core.ProviderData
} }
// Metadata returns the data source type name. // Metadata returns the data source type name.
@ -122,17 +124,18 @@ func (d *imageDataV2Source) Metadata(_ context.Context, req datasource.MetadataR
} }
func (d *imageDataV2Source) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) { func (d *imageDataV2Source) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
providerData, ok := conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics) var ok bool
d.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
if !ok { if !ok {
return return
} }
features.CheckBetaResourcesEnabled(ctx, &providerData, &resp.Diagnostics, "stackit_image_v2", "datasource") features.CheckBetaResourcesEnabled(ctx, &d.providerData, &resp.Diagnostics, "stackit_image_v2", "datasource")
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
apiClient := iaasUtils.ConfigureClient(ctx, &providerData, &resp.Diagnostics) apiClient := iaasUtils.ConfigureClient(ctx, &d.providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
@ -189,7 +192,7 @@ func (d *imageDataV2Source) Schema(_ context.Context, _ datasource.SchemaRequest
Description: description, Description: description,
Attributes: map[string]schema.Attribute{ Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{ "id": schema.StringAttribute{
Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`image_id`\".", Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`region`,`image_id`\".",
Computed: true, Computed: true,
}, },
"project_id": schema.StringAttribute{ "project_id": schema.StringAttribute{
@ -200,6 +203,11 @@ func (d *imageDataV2Source) Schema(_ context.Context, _ datasource.SchemaRequest
validate.NoSeparator(), validate.NoSeparator(),
}, },
}, },
"region": schema.StringAttribute{
Description: "The resource region. If not defined, the provider region is used.",
// the region cannot be found, so it has to be passed
Optional: true,
},
"image_id": schema.StringAttribute{ "image_id": schema.StringAttribute{
Description: "Image ID to fetch directly", Description: "Image ID to fetch directly",
Optional: true, Optional: true,
@ -357,6 +365,7 @@ func (d *imageDataV2Source) Read(ctx context.Context, req datasource.ReadRequest
} }
projectID := model.ProjectId.ValueString() projectID := model.ProjectId.ValueString()
region := d.providerData.GetRegionWithOverride(model.Region)
imageID := model.ImageId.ValueString() imageID := model.ImageId.ValueString()
name := model.Name.ValueString() name := model.Name.ValueString()
nameRegex := model.NameRegex.ValueString() nameRegex := model.NameRegex.ValueString()
@ -373,6 +382,7 @@ func (d *imageDataV2Source) Read(ctx context.Context, req datasource.ReadRequest
ctx = core.InitProviderContext(ctx) ctx = core.InitProviderContext(ctx)
ctx = tflog.SetField(ctx, "project_id", projectID) ctx = tflog.SetField(ctx, "project_id", projectID)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "image_id", imageID) ctx = tflog.SetField(ctx, "image_id", imageID)
ctx = tflog.SetField(ctx, "name", name) ctx = tflog.SetField(ctx, "name", name)
ctx = tflog.SetField(ctx, "name_regex", nameRegex) ctx = tflog.SetField(ctx, "name_regex", nameRegex)
@ -383,7 +393,7 @@ func (d *imageDataV2Source) Read(ctx context.Context, req datasource.ReadRequest
// Case 1: Direct lookup by image ID // Case 1: Direct lookup by image ID
if imageID != "" { if imageID != "" {
imageResp, err = d.client.GetImage(ctx, projectID, imageID).Execute() imageResp, err = d.client.GetImage(ctx, projectID, region, imageID).Execute()
if err != nil { if err != nil {
utils.LogError(ctx, &resp.Diagnostics, err, "Reading image", utils.LogError(ctx, &resp.Diagnostics, err, "Reading image",
fmt.Sprintf("Image with ID %q does not exist in project %q.", imageID, projectID), fmt.Sprintf("Image with ID %q does not exist in project %q.", imageID, projectID),
@ -409,7 +419,7 @@ func (d *imageDataV2Source) Read(ctx context.Context, req datasource.ReadRequest
} }
// Fetch all available images // Fetch all available images
imageList, err := d.client.ListImages(ctx, projectID).Execute() imageList, err := d.client.ListImages(ctx, projectID, region).Execute()
if err != nil { if err != nil {
utils.LogError(ctx, &resp.Diagnostics, err, "List images", "Unable to fetch images", nil) utils.LogError(ctx, &resp.Diagnostics, err, "List images", "Unable to fetch images", nil)
return return
@ -457,7 +467,7 @@ func (d *imageDataV2Source) Read(ctx context.Context, req datasource.ReadRequest
imageResp = filteredImages[0] imageResp = filteredImages[0]
} }
err = mapDataSourceFields(ctx, imageResp, &model) err = mapDataSourceFields(ctx, imageResp, &model, region)
if err != nil { if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading image", fmt.Sprintf("Processing API payload: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading image", fmt.Sprintf("Processing API payload: %v", err))
return return
@ -473,7 +483,7 @@ func (d *imageDataV2Source) Read(ctx context.Context, req datasource.ReadRequest
tflog.Info(ctx, "image read") tflog.Info(ctx, "image read")
} }
func mapDataSourceFields(ctx context.Context, imageResp *iaas.Image, model *DataSourceModel) error { func mapDataSourceFields(ctx context.Context, imageResp *iaas.Image, model *DataSourceModel, region string) error {
if imageResp == nil { if imageResp == nil {
return fmt.Errorf("response input is nil") return fmt.Errorf("response input is nil")
} }
@ -490,7 +500,8 @@ func mapDataSourceFields(ctx context.Context, imageResp *iaas.Image, model *Data
return fmt.Errorf("image id not present") return fmt.Errorf("image id not present")
} }
model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), imageId) model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), region, imageId)
model.Region = types.StringValue(region)
// Map config // Map config
var configModel = &configModel{} var configModel = &configModel{}

View file

@ -12,69 +12,81 @@ import (
) )
func TestMapDataSourceFields(t *testing.T) { func TestMapDataSourceFields(t *testing.T) {
type args struct {
state DataSourceModel
input *iaas.Image
region string
}
tests := []struct { tests := []struct {
description string description string
state DataSourceModel args args
input *iaas.Image
expected DataSourceModel expected DataSourceModel
isValid bool isValid bool
}{ }{
{ {
"default_values", description: "default_values",
DataSourceModel{ args: args{
ProjectId: types.StringValue("pid"), state: DataSourceModel{
ImageId: types.StringValue("iid"), ProjectId: types.StringValue("pid"),
ImageId: types.StringValue("iid"),
},
input: &iaas.Image{
Id: utils.Ptr("iid"),
},
region: "eu01",
}, },
&iaas.Image{ expected: DataSourceModel{
Id: utils.Ptr("iid"), Id: types.StringValue("pid,eu01,iid"),
},
DataSourceModel{
Id: types.StringValue("pid,iid"),
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
ImageId: types.StringValue("iid"), ImageId: types.StringValue("iid"),
Labels: types.MapNull(types.StringType), Labels: types.MapNull(types.StringType),
Region: types.StringValue("eu01"),
}, },
true, isValid: true,
}, },
{ {
"simple_values", description: "simple_values",
DataSourceModel{ args: args{
ProjectId: types.StringValue("pid"), state: DataSourceModel{
ImageId: types.StringValue("iid"), ProjectId: types.StringValue("pid"),
ImageId: types.StringValue("iid"),
Region: types.StringValue("eu01"),
},
input: &iaas.Image{
Id: utils.Ptr("iid"),
Name: utils.Ptr("name"),
DiskFormat: utils.Ptr("format"),
MinDiskSize: utils.Ptr(int64(1)),
MinRam: utils.Ptr(int64(1)),
Protected: utils.Ptr(true),
Scope: utils.Ptr("scope"),
Config: &iaas.ImageConfig{
BootMenu: utils.Ptr(true),
CdromBus: iaas.NewNullableString(utils.Ptr("cdrom_bus")),
DiskBus: iaas.NewNullableString(utils.Ptr("disk_bus")),
NicModel: iaas.NewNullableString(utils.Ptr("model")),
OperatingSystem: utils.Ptr("os"),
OperatingSystemDistro: iaas.NewNullableString(utils.Ptr("os_distro")),
OperatingSystemVersion: iaas.NewNullableString(utils.Ptr("os_version")),
RescueBus: iaas.NewNullableString(utils.Ptr("rescue_bus")),
RescueDevice: iaas.NewNullableString(utils.Ptr("rescue_device")),
SecureBoot: utils.Ptr(true),
Uefi: utils.Ptr(true),
VideoModel: iaas.NewNullableString(utils.Ptr("model")),
VirtioScsi: utils.Ptr(true),
},
Checksum: &iaas.ImageChecksum{
Algorithm: utils.Ptr("algorithm"),
Digest: utils.Ptr("digest"),
},
Labels: &map[string]interface{}{
"key": "value",
},
},
region: "eu02",
}, },
&iaas.Image{ expected: DataSourceModel{
Id: utils.Ptr("iid"), Id: types.StringValue("pid,eu02,iid"),
Name: utils.Ptr("name"),
DiskFormat: utils.Ptr("format"),
MinDiskSize: utils.Ptr(int64(1)),
MinRam: utils.Ptr(int64(1)),
Protected: utils.Ptr(true),
Scope: utils.Ptr("scope"),
Config: &iaas.ImageConfig{
BootMenu: utils.Ptr(true),
CdromBus: iaas.NewNullableString(utils.Ptr("cdrom_bus")),
DiskBus: iaas.NewNullableString(utils.Ptr("disk_bus")),
NicModel: iaas.NewNullableString(utils.Ptr("model")),
OperatingSystem: utils.Ptr("os"),
OperatingSystemDistro: iaas.NewNullableString(utils.Ptr("os_distro")),
OperatingSystemVersion: iaas.NewNullableString(utils.Ptr("os_version")),
RescueBus: iaas.NewNullableString(utils.Ptr("rescue_bus")),
RescueDevice: iaas.NewNullableString(utils.Ptr("rescue_device")),
SecureBoot: utils.Ptr(true),
Uefi: utils.Ptr(true),
VideoModel: iaas.NewNullableString(utils.Ptr("model")),
VirtioScsi: utils.Ptr(true),
},
Checksum: &iaas.ImageChecksum{
Algorithm: utils.Ptr("algorithm"),
Digest: utils.Ptr("digest"),
},
Labels: &map[string]interface{}{
"key": "value",
},
},
DataSourceModel{
Id: types.StringValue("pid,iid"),
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
ImageId: types.StringValue("iid"), ImageId: types.StringValue("iid"),
Name: types.StringValue("name"), Name: types.StringValue("name"),
@ -105,47 +117,48 @@ func TestMapDataSourceFields(t *testing.T) {
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{ Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
"key": types.StringValue("value"), "key": types.StringValue("value"),
}), }),
Region: types.StringValue("eu02"),
}, },
true, isValid: true,
}, },
{ {
"empty_labels", description: "empty_labels",
DataSourceModel{ args: args{
state: DataSourceModel{
ProjectId: types.StringValue("pid"),
ImageId: types.StringValue("iid"),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{}),
},
input: &iaas.Image{
Id: utils.Ptr("iid"),
},
region: "eu01",
},
expected: DataSourceModel{
Id: types.StringValue("pid,eu01,iid"),
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
ImageId: types.StringValue("iid"), ImageId: types.StringValue("iid"),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{}), Labels: types.MapValueMust(types.StringType, map[string]attr.Value{}),
Region: types.StringValue("eu01"),
}, },
&iaas.Image{ isValid: true,
Id: utils.Ptr("iid"),
},
DataSourceModel{
Id: types.StringValue("pid,iid"),
ProjectId: types.StringValue("pid"),
ImageId: types.StringValue("iid"),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{}),
},
true,
}, },
{ {
"response_nil_fail", description: "response_nil_fail",
DataSourceModel{},
nil,
DataSourceModel{},
false,
}, },
{ {
"no_resource_id", description: "no_resource_id",
DataSourceModel{ args: args{
ProjectId: types.StringValue("pid"), state: DataSourceModel{
ProjectId: types.StringValue("pid"),
},
input: &iaas.Image{},
}, },
&iaas.Image{},
DataSourceModel{},
false,
}, },
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.description, func(t *testing.T) { t.Run(tt.description, func(t *testing.T) {
err := mapDataSourceFields(context.Background(), tt.input, &tt.state) err := mapDataSourceFields(context.Background(), tt.args.input, &tt.args.state, tt.args.region)
if !tt.isValid && err == nil { if !tt.isValid && err == nil {
t.Fatalf("Should have failed") t.Fatalf("Should have failed")
} }
@ -153,7 +166,7 @@ func TestMapDataSourceFields(t *testing.T) {
t.Fatalf("Should not have failed: %v", err) t.Fatalf("Should not have failed: %v", err)
} }
if tt.isValid { if tt.isValid {
diff := cmp.Diff(tt.state, tt.expected) diff := cmp.Diff(tt.args.state, tt.expected)
if diff != "" { if diff != "" {
t.Fatalf("Data does not match: %s", diff) t.Fatalf("Data does not match: %s", diff)
} }

View file

@ -21,7 +21,7 @@ var (
_ datasource.DataSource = &keyPairDataSource{} _ datasource.DataSource = &keyPairDataSource{}
) )
// NewVolumeDataSource is a helper function to simplify the provider implementation. // NewKeyPairDataSource is a helper function to simplify the provider implementation.
func NewKeyPairDataSource() datasource.DataSource { func NewKeyPairDataSource() datasource.DataSource {
return &keyPairDataSource{} return &keyPairDataSource{}
} }
@ -51,7 +51,7 @@ func (d *keyPairDataSource) Configure(ctx context.Context, req datasource.Config
} }
// Schema defines the schema for the resource. // Schema defines the schema for the resource.
func (r *keyPairDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { func (d *keyPairDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
description := "Key pair resource schema. Must have a `region` specified in the provider configuration." description := "Key pair resource schema. Must have a `region` specified in the provider configuration."
resp.Schema = schema.Schema{ resp.Schema = schema.Schema{
@ -84,7 +84,7 @@ func (r *keyPairDataSource) Schema(_ context.Context, _ datasource.SchemaRequest
} }
// Read refreshes the Terraform state with the latest data. // Read refreshes the Terraform state with the latest data.
func (r *keyPairDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform func (d *keyPairDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var model Model var model Model
diags := req.Config.Get(ctx, &model) diags := req.Config.Get(ctx, &model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
@ -97,7 +97,7 @@ func (r *keyPairDataSource) Read(ctx context.Context, req datasource.ReadRequest
ctx = tflog.SetField(ctx, "name", name) ctx = tflog.SetField(ctx, "name", name)
keypairResp, err := r.client.GetKeyPair(ctx, name).Execute() keypairResp, err := d.client.GetKeyPair(ctx, name).Execute()
if err != nil { if err != nil {
utils.LogError( utils.LogError(
ctx, ctx,

View file

@ -7,10 +7,12 @@ import (
"sort" "sort"
"strings" "strings"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
"github.com/hashicorp/terraform-plugin-framework/datasource" "github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema" "github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/diag" "github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types" "github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/stackitcloud/stackit-sdk-go/services/iaas" "github.com/stackitcloud/stackit-sdk-go/services/iaas"
@ -19,7 +21,6 @@ import (
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/features" "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/features"
iaasUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaas/utils" iaasUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaas/utils"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils" "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
) )
// Ensure the implementation satisfies the expected interfaces. // Ensure the implementation satisfies the expected interfaces.
@ -28,6 +29,7 @@ var _ datasource.DataSource = &machineTypeDataSource{}
type DataSourceModel struct { type DataSourceModel struct {
Id types.String `tfsdk:"id"` // required by Terraform to identify state Id types.String `tfsdk:"id"` // required by Terraform to identify state
ProjectId types.String `tfsdk:"project_id"` ProjectId types.String `tfsdk:"project_id"`
Region types.String `tfsdk:"region"`
SortAscending types.Bool `tfsdk:"sort_ascending"` SortAscending types.Bool `tfsdk:"sort_ascending"`
Filter types.String `tfsdk:"filter"` Filter types.String `tfsdk:"filter"`
Description types.String `tfsdk:"description"` Description types.String `tfsdk:"description"`
@ -44,7 +46,8 @@ func NewMachineTypeDataSource() datasource.DataSource {
} }
type machineTypeDataSource struct { type machineTypeDataSource struct {
client *iaas.APIClient client *iaas.APIClient
providerData core.ProviderData
} }
func (d *machineTypeDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { func (d *machineTypeDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
@ -52,17 +55,18 @@ func (d *machineTypeDataSource) Metadata(_ context.Context, req datasource.Metad
} }
func (d *machineTypeDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) { func (d *machineTypeDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
providerData, ok := conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics) var ok bool
d.providerData, ok = conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
if !ok { if !ok {
return return
} }
features.CheckBetaResourcesEnabled(ctx, &providerData, &resp.Diagnostics, "stackit_machine_type", "datasource") features.CheckBetaResourcesEnabled(ctx, &d.providerData, &resp.Diagnostics, "stackit_machine_type", "datasource")
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
client := iaasUtils.ConfigureClient(ctx, &providerData, &resp.Diagnostics) client := iaasUtils.ConfigureClient(ctx, &d.providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
@ -76,7 +80,7 @@ func (d *machineTypeDataSource) Schema(_ context.Context, _ datasource.SchemaReq
MarkdownDescription: features.AddBetaDescription("Machine type data source.", core.Datasource), MarkdownDescription: features.AddBetaDescription("Machine type data source.", core.Datasource),
Attributes: map[string]schema.Attribute{ Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{ "id": schema.StringAttribute{
Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`image_id`\".", Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`region`,`image_id`\".",
Computed: true, Computed: true,
}, },
"project_id": schema.StringAttribute{ "project_id": schema.StringAttribute{
@ -87,6 +91,11 @@ func (d *machineTypeDataSource) Schema(_ context.Context, _ datasource.SchemaReq
validate.NoSeparator(), validate.NoSeparator(),
}, },
}, },
"region": schema.StringAttribute{
Description: "The resource region. If not defined, the provider region is used.",
// the region cannot be found, so it has to be passed
Optional: true,
},
"sort_ascending": schema.BoolAttribute{ "sort_ascending": schema.BoolAttribute{
Description: "Sort machine types by name ascending (`true`) or descending (`false`). Defaults to `false`", Description: "Sort machine types by name ascending (`true`) or descending (`false`). Defaults to `false`",
Optional: true, Optional: true,
@ -142,15 +151,17 @@ func (d *machineTypeDataSource) Read(ctx context.Context, req datasource.ReadReq
} }
projectId := model.ProjectId.ValueString() projectId := model.ProjectId.ValueString()
region := d.providerData.GetRegionWithOverride(model.Region)
sortAscending := model.SortAscending.ValueBool() sortAscending := model.SortAscending.ValueBool()
ctx = core.InitProviderContext(ctx) ctx = core.InitProviderContext(ctx)
ctx = tflog.SetField(ctx, "project_id", projectId) ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "filter_is_null", model.Filter.IsNull()) ctx = tflog.SetField(ctx, "filter_is_null", model.Filter.IsNull())
ctx = tflog.SetField(ctx, "filter_is_unknown", model.Filter.IsUnknown()) ctx = tflog.SetField(ctx, "filter_is_unknown", model.Filter.IsUnknown())
listMachineTypeReq := d.client.ListMachineTypes(ctx, projectId) listMachineTypeReq := d.client.ListMachineTypes(ctx, projectId, region)
if !model.Filter.IsNull() && !model.Filter.IsUnknown() && strings.TrimSpace(model.Filter.ValueString()) != "" { if !model.Filter.IsNull() && !model.Filter.IsUnknown() && strings.TrimSpace(model.Filter.ValueString()) != "" {
listMachineTypeReq = listMachineTypeReq.Filter(strings.TrimSpace(model.Filter.ValueString())) listMachineTypeReq = listMachineTypeReq.Filter(strings.TrimSpace(model.Filter.ValueString()))
@ -187,7 +198,7 @@ func (d *machineTypeDataSource) Read(ctx context.Context, req datasource.ReadReq
return return
} }
if err := mapDataSourceFields(ctx, sorted[0], &model); err != nil { if err := mapDataSourceFields(ctx, sorted[0], &model, region); err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading machine type", fmt.Sprintf("Failed to translate API response: %v", err)) core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading machine type", fmt.Sprintf("Failed to translate API response: %v", err))
return return
} }
@ -199,7 +210,7 @@ func (d *machineTypeDataSource) Read(ctx context.Context, req datasource.ReadReq
tflog.Info(ctx, "Successfully read machine type") tflog.Info(ctx, "Successfully read machine type")
} }
func mapDataSourceFields(ctx context.Context, machineType *iaas.MachineType, model *DataSourceModel) error { func mapDataSourceFields(ctx context.Context, machineType *iaas.MachineType, model *DataSourceModel, region string) error {
if machineType == nil || model == nil { if machineType == nil || model == nil {
return fmt.Errorf("nil input provided") return fmt.Errorf("nil input provided")
} }
@ -208,7 +219,8 @@ func mapDataSourceFields(ctx context.Context, machineType *iaas.MachineType, mod
return fmt.Errorf("machine type name is missing") return fmt.Errorf("machine type name is missing")
} }
model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), *machineType.Name) model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), region, *machineType.Name)
model.Region = types.StringValue(region)
model.Name = types.StringPointerValue(machineType.Name) model.Name = types.StringPointerValue(machineType.Name)
model.Description = types.StringPointerValue(machineType.Description) model.Description = types.StringPointerValue(machineType.Description)
model.Disk = types.Int64PointerValue(machineType.Disk) model.Disk = types.Int64PointerValue(machineType.Disk)

View file

@ -13,32 +13,39 @@ import (
) )
func TestMapDataSourceFields(t *testing.T) { func TestMapDataSourceFields(t *testing.T) {
type args struct {
initial DataSourceModel
input *iaas.MachineType
region string
}
tests := []struct { tests := []struct {
name string name string
initial DataSourceModel args args
input *iaas.MachineType
expected DataSourceModel expected DataSourceModel
expectError bool expectError bool
}{ }{
{ {
name: "valid simple values", name: "valid simple values",
initial: DataSourceModel{ args: args{
ProjectId: types.StringValue("pid"), initial: DataSourceModel{
}, ProjectId: types.StringValue("pid"),
input: &iaas.MachineType{
Name: utils.Ptr("s1.2"),
Description: utils.Ptr("general-purpose small"),
Disk: utils.Ptr(int64(20)),
Ram: utils.Ptr(int64(2048)),
Vcpus: utils.Ptr(int64(2)),
ExtraSpecs: &map[string]interface{}{
"cpu": "amd-epycrome-7702",
"overcommit": "1",
"environment": "general",
}, },
input: &iaas.MachineType{
Name: utils.Ptr("s1.2"),
Description: utils.Ptr("general-purpose small"),
Disk: utils.Ptr(int64(20)),
Ram: utils.Ptr(int64(2048)),
Vcpus: utils.Ptr(int64(2)),
ExtraSpecs: &map[string]interface{}{
"cpu": "amd-epycrome-7702",
"overcommit": "1",
"environment": "general",
},
},
region: "eu01",
}, },
expected: DataSourceModel{ expected: DataSourceModel{
Id: types.StringValue("pid,s1.2"), Id: types.StringValue("pid,eu01,s1.2"),
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
Name: types.StringValue("s1.2"), Name: types.StringValue("s1.2"),
Description: types.StringValue("general-purpose small"), Description: types.StringValue("general-purpose small"),
@ -50,42 +57,50 @@ func TestMapDataSourceFields(t *testing.T) {
"overcommit": types.StringValue("1"), "overcommit": types.StringValue("1"),
"environment": types.StringValue("general"), "environment": types.StringValue("general"),
}), }),
Region: types.StringValue("eu01"),
}, },
expectError: false, expectError: false,
}, },
{ {
name: "missing name should fail", name: "missing name should fail",
initial: DataSourceModel{ args: args{
ProjectId: types.StringValue("pid-456"), initial: DataSourceModel{
}, ProjectId: types.StringValue("pid-456"),
input: &iaas.MachineType{ },
Description: utils.Ptr("gp-medium"), input: &iaas.MachineType{
Description: utils.Ptr("gp-medium"),
},
}, },
expected: DataSourceModel{}, expected: DataSourceModel{},
expectError: true, expectError: true,
}, },
{ {
name: "nil machineType should fail", name: "nil machineType should fail",
initial: DataSourceModel{}, args: args{
input: nil, initial: DataSourceModel{},
input: nil,
},
expected: DataSourceModel{}, expected: DataSourceModel{},
expectError: true, expectError: true,
}, },
{ {
name: "empty extraSpecs should return null map", name: "empty extraSpecs should return null map",
initial: DataSourceModel{ args: args{
ProjectId: types.StringValue("pid-789"), initial: DataSourceModel{
}, ProjectId: types.StringValue("pid-789"),
input: &iaas.MachineType{ },
Name: utils.Ptr("m1.noextras"), input: &iaas.MachineType{
Description: utils.Ptr("no extras"), Name: utils.Ptr("m1.noextras"),
Disk: utils.Ptr(int64(10)), Description: utils.Ptr("no extras"),
Ram: utils.Ptr(int64(1024)), Disk: utils.Ptr(int64(10)),
Vcpus: utils.Ptr(int64(1)), Ram: utils.Ptr(int64(1024)),
ExtraSpecs: &map[string]interface{}{}, Vcpus: utils.Ptr(int64(1)),
ExtraSpecs: &map[string]interface{}{},
},
region: "eu01",
}, },
expected: DataSourceModel{ expected: DataSourceModel{
Id: types.StringValue("pid-789,m1.noextras"), Id: types.StringValue("pid-789,eu01,m1.noextras"),
ProjectId: types.StringValue("pid-789"), ProjectId: types.StringValue("pid-789"),
Name: types.StringValue("m1.noextras"), Name: types.StringValue("m1.noextras"),
Description: types.StringValue("no extras"), Description: types.StringValue("no extras"),
@ -93,24 +108,28 @@ func TestMapDataSourceFields(t *testing.T) {
Ram: types.Int64Value(1024), Ram: types.Int64Value(1024),
Vcpus: types.Int64Value(1), Vcpus: types.Int64Value(1),
ExtraSpecs: types.MapNull(types.StringType), ExtraSpecs: types.MapNull(types.StringType),
Region: types.StringValue("eu01"),
}, },
expectError: false, expectError: false,
}, },
{ {
name: "nil extrasSpecs should return null map", name: "nil extrasSpecs should return null map",
initial: DataSourceModel{ args: args{
ProjectId: types.StringValue("pid-987"), initial: DataSourceModel{
}, ProjectId: types.StringValue("pid-987"),
input: &iaas.MachineType{ },
Name: utils.Ptr("g1.nil"), input: &iaas.MachineType{
Description: utils.Ptr("missing extras"), Name: utils.Ptr("g1.nil"),
Disk: utils.Ptr(int64(40)), Description: utils.Ptr("missing extras"),
Ram: utils.Ptr(int64(8096)), Disk: utils.Ptr(int64(40)),
Vcpus: utils.Ptr(int64(4)), Ram: utils.Ptr(int64(8096)),
ExtraSpecs: nil, Vcpus: utils.Ptr(int64(4)),
ExtraSpecs: nil,
},
region: "eu01",
}, },
expected: DataSourceModel{ expected: DataSourceModel{
Id: types.StringValue("pid-987,g1.nil"), Id: types.StringValue("pid-987,eu01,g1.nil"),
ProjectId: types.StringValue("pid-987"), ProjectId: types.StringValue("pid-987"),
Name: types.StringValue("g1.nil"), Name: types.StringValue("g1.nil"),
Description: types.StringValue("missing extras"), Description: types.StringValue("missing extras"),
@ -118,24 +137,27 @@ func TestMapDataSourceFields(t *testing.T) {
Ram: types.Int64Value(8096), Ram: types.Int64Value(8096),
Vcpus: types.Int64Value(4), Vcpus: types.Int64Value(4),
ExtraSpecs: types.MapNull(types.StringType), ExtraSpecs: types.MapNull(types.StringType),
Region: types.StringValue("eu01"),
}, },
expectError: false, expectError: false,
}, },
{ {
name: "invalid extraSpecs with non-string values", name: "invalid extraSpecs with non-string values",
initial: DataSourceModel{ args: args{
ProjectId: types.StringValue("test-err"), initial: DataSourceModel{
}, ProjectId: types.StringValue("test-err"),
input: &iaas.MachineType{ },
Name: utils.Ptr("invalid"), input: &iaas.MachineType{
Description: utils.Ptr("bad map"), Name: utils.Ptr("invalid"),
Disk: utils.Ptr(int64(10)), Description: utils.Ptr("bad map"),
Ram: utils.Ptr(int64(4096)), Disk: utils.Ptr(int64(10)),
Vcpus: utils.Ptr(int64(2)), Ram: utils.Ptr(int64(4096)),
ExtraSpecs: &map[string]interface{}{ Vcpus: utils.Ptr(int64(2)),
"cpu": "intel", ExtraSpecs: &map[string]interface{}{
"burst": true, // not a string "cpu": "intel",
"gen": 8, // not a string "burst": true, // not a string
"gen": 8, // not a string
},
}, },
}, },
expected: DataSourceModel{}, expected: DataSourceModel{},
@ -145,7 +167,7 @@ func TestMapDataSourceFields(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
err := mapDataSourceFields(context.Background(), tt.input, &tt.initial) err := mapDataSourceFields(context.Background(), tt.args.input, &tt.args.initial, tt.args.region)
if tt.expectError { if tt.expectError {
if err == nil { if err == nil {
t.Errorf("expected error but got none") t.Errorf("expected error but got none")
@ -157,13 +179,13 @@ func TestMapDataSourceFields(t *testing.T) {
t.Fatalf("unexpected error: %v", err) t.Fatalf("unexpected error: %v", err)
} }
diff := cmp.Diff(tt.expected, tt.initial) diff := cmp.Diff(tt.expected, tt.args.initial)
if diff != "" { if diff != "" {
t.Errorf("unexpected diff (-want +got):\n%s", diff) t.Errorf("unexpected diff (-want +got):\n%s", diff)
} }
// Extra sanity check for proper ID format // Extra sanity check for proper ID format
if id := tt.initial.Id.ValueString(); !strings.HasPrefix(id, tt.initial.ProjectId.ValueString()+",") { if id := tt.args.initial.Id.ValueString(); !strings.HasPrefix(id, tt.args.initial.ProjectId.ValueString()+",") {
t.Errorf("unexpected ID format: got %q", id) t.Errorf("unexpected ID format: got %q", id)
} }
}) })

View file

@ -2,14 +2,11 @@ package network
import ( import (
"context" "context"
"fmt"
"net"
"net/http"
"github.com/stackitcloud/stackit-sdk-go/services/iaasalpha" "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/features"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaas/network/utils/v1network"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaas/network/utils/v2network"
iaasUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaas/utils"
iaasAlphaUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaasalpha/utils"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/datasource" "github.com/hashicorp/terraform-plugin-framework/datasource"
@ -18,7 +15,9 @@ import (
"github.com/hashicorp/terraform-plugin-framework/types" "github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/stackitcloud/stackit-sdk-go/services/iaas" "github.com/stackitcloud/stackit-sdk-go/services/iaas"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core" "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
iaasUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaas/utils"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate" "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
) )
@ -27,6 +26,30 @@ var (
_ datasource.DataSource = &networkDataSource{} _ datasource.DataSource = &networkDataSource{}
) )
type DataSourceModel struct {
Id types.String `tfsdk:"id"` // needed by TF
ProjectId types.String `tfsdk:"project_id"`
NetworkId types.String `tfsdk:"network_id"`
Name types.String `tfsdk:"name"`
Nameservers types.List `tfsdk:"nameservers"`
IPv4Gateway types.String `tfsdk:"ipv4_gateway"`
IPv4Nameservers types.List `tfsdk:"ipv4_nameservers"`
IPv4Prefix types.String `tfsdk:"ipv4_prefix"`
IPv4PrefixLength types.Int64 `tfsdk:"ipv4_prefix_length"`
Prefixes types.List `tfsdk:"prefixes"`
IPv4Prefixes types.List `tfsdk:"ipv4_prefixes"`
IPv6Gateway types.String `tfsdk:"ipv6_gateway"`
IPv6Nameservers types.List `tfsdk:"ipv6_nameservers"`
IPv6Prefix types.String `tfsdk:"ipv6_prefix"`
IPv6PrefixLength types.Int64 `tfsdk:"ipv6_prefix_length"`
IPv6Prefixes types.List `tfsdk:"ipv6_prefixes"`
PublicIP types.String `tfsdk:"public_ip"`
Labels types.Map `tfsdk:"labels"`
Routed types.Bool `tfsdk:"routed"`
Region types.String `tfsdk:"region"`
RoutingTableID types.String `tfsdk:"routing_table_id"`
}
// NewNetworkDataSource is a helper function to simplify the provider implementation. // NewNetworkDataSource is a helper function to simplify the provider implementation.
func NewNetworkDataSource() datasource.DataSource { func NewNetworkDataSource() datasource.DataSource {
return &networkDataSource{} return &networkDataSource{}
@ -34,11 +57,8 @@ func NewNetworkDataSource() datasource.DataSource {
// networkDataSource is the data source implementation. // networkDataSource is the data source implementation.
type networkDataSource struct { type networkDataSource struct {
client *iaas.APIClient client *iaas.APIClient
// alphaClient will be used in case the experimental flag "network" is set providerData core.ProviderData
alphaClient *iaasalpha.APIClient
isExperimental bool
providerData core.ProviderData
} }
// Metadata returns the data source type name. // Metadata returns the data source type name.
@ -53,24 +73,11 @@ func (d *networkDataSource) Configure(ctx context.Context, req datasource.Config
return return
} }
d.isExperimental = features.CheckExperimentEnabledWithoutError(ctx, &d.providerData, features.NetworkExperiment, "stackit_network", core.Datasource, &resp.Diagnostics) apiClient := iaasUtils.ConfigureClient(ctx, &d.providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
d.client = apiClient
if d.isExperimental {
alphaApiClient := iaasAlphaUtils.ConfigureClient(ctx, &d.providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
d.alphaClient = alphaApiClient
} else {
apiClient := iaasUtils.ConfigureClient(ctx, &d.providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
d.client = apiClient
}
tflog.Info(ctx, "IaaS client configured") tflog.Info(ctx, "IaaS client configured")
} }
@ -197,9 +204,199 @@ func (d *networkDataSource) Schema(_ context.Context, _ datasource.SchemaRequest
// Read refreshes the Terraform state with the latest data. // Read refreshes the Terraform state with the latest data.
func (d *networkDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform func (d *networkDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
if !d.isExperimental { var model DataSourceModel
v1network.DatasourceRead(ctx, req, resp, d.client) diags := req.Config.Get(ctx, &model)
} else { resp.Diagnostics.Append(diags...)
v2network.DatasourceRead(ctx, req, resp, d.alphaClient, d.providerData) if resp.Diagnostics.HasError() {
return
} }
projectId := model.ProjectId.ValueString()
networkId := model.NetworkId.ValueString()
region := d.providerData.GetRegionWithOverride(model.Region)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "network_id", networkId)
networkResp, err := d.client.GetNetwork(ctx, projectId, region, networkId).Execute()
if err != nil {
utils.LogError(
ctx,
&resp.Diagnostics,
err,
"Reading network",
fmt.Sprintf("Network with ID %q does not exist in project %q.", networkId, projectId),
map[int]string{
http.StatusForbidden: fmt.Sprintf("Project with ID %q not found or forbidden access", projectId),
},
)
resp.State.RemoveResource(ctx)
return
}
err = mapDataSourceFields(ctx, networkResp, &model, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading network", fmt.Sprintf("Processing API payload: %v", err))
return
}
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Network read")
}
func mapDataSourceFields(ctx context.Context, networkResp *iaas.Network, model *DataSourceModel, region string) error {
if networkResp == nil {
return fmt.Errorf("response input is nil")
}
if model == nil {
return fmt.Errorf("model input is nil")
}
var networkId string
if model.NetworkId.ValueString() != "" {
networkId = model.NetworkId.ValueString()
} else if networkResp.Id != nil {
networkId = *networkResp.Id
} else {
return fmt.Errorf("network id not present")
}
model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), region, networkId)
labels, err := iaasUtils.MapLabels(ctx, networkResp.Labels, model.Labels)
if err != nil {
return err
}
// IPv4
if networkResp.Ipv4 == nil || networkResp.Ipv4.Nameservers == nil {
model.Nameservers = types.ListNull(types.StringType)
model.IPv4Nameservers = types.ListNull(types.StringType)
} else {
respNameservers := *networkResp.Ipv4.Nameservers
modelNameservers, err := utils.ListValuetoStringSlice(model.Nameservers)
modelIPv4Nameservers, errIpv4 := utils.ListValuetoStringSlice(model.IPv4Nameservers)
if err != nil {
return fmt.Errorf("get current network nameservers from model: %w", err)
}
if errIpv4 != nil {
return fmt.Errorf("get current IPv4 network nameservers from model: %w", errIpv4)
}
reconciledNameservers := utils.ReconcileStringSlices(modelNameservers, respNameservers)
reconciledIPv4Nameservers := utils.ReconcileStringSlices(modelIPv4Nameservers, respNameservers)
nameserversTF, diags := types.ListValueFrom(ctx, types.StringType, reconciledNameservers)
ipv4NameserversTF, ipv4Diags := types.ListValueFrom(ctx, types.StringType, reconciledIPv4Nameservers)
if diags.HasError() {
return fmt.Errorf("map network nameservers: %w", core.DiagsToError(diags))
}
if ipv4Diags.HasError() {
return fmt.Errorf("map IPv4 network nameservers: %w", core.DiagsToError(ipv4Diags))
}
model.Nameservers = nameserversTF
model.IPv4Nameservers = ipv4NameserversTF
}
if networkResp.Ipv4 == nil || networkResp.Ipv4.Prefixes == nil {
model.Prefixes = types.ListNull(types.StringType)
model.IPv4Prefixes = types.ListNull(types.StringType)
} else {
respPrefixes := *networkResp.Ipv4.Prefixes
prefixesTF, diags := types.ListValueFrom(ctx, types.StringType, respPrefixes)
if diags.HasError() {
return fmt.Errorf("map network prefixes: %w", core.DiagsToError(diags))
}
if len(respPrefixes) > 0 {
model.IPv4Prefix = types.StringValue(respPrefixes[0])
_, netmask, err := net.ParseCIDR(respPrefixes[0])
if err != nil {
// silently ignore parsing error for the netmask
model.IPv4PrefixLength = types.Int64Null()
} else {
ones, _ := netmask.Mask.Size()
model.IPv4PrefixLength = types.Int64Value(int64(ones))
}
}
model.Prefixes = prefixesTF
model.IPv4Prefixes = prefixesTF
}
if networkResp.Ipv4 == nil || networkResp.Ipv4.Gateway == nil {
model.IPv4Gateway = types.StringNull()
} else {
model.IPv4Gateway = types.StringPointerValue(networkResp.Ipv4.GetGateway())
}
if networkResp.Ipv4 == nil || networkResp.Ipv4.PublicIp == nil {
model.PublicIP = types.StringNull()
} else {
model.PublicIP = types.StringPointerValue(networkResp.Ipv4.PublicIp)
}
// IPv6
if networkResp.Ipv6 == nil || networkResp.Ipv6.Nameservers == nil {
model.IPv6Nameservers = types.ListNull(types.StringType)
} else {
respIPv6Nameservers := *networkResp.Ipv6.Nameservers
modelIPv6Nameservers, errIpv6 := utils.ListValuetoStringSlice(model.IPv6Nameservers)
if errIpv6 != nil {
return fmt.Errorf("get current IPv6 network nameservers from model: %w", errIpv6)
}
reconciledIPv6Nameservers := utils.ReconcileStringSlices(modelIPv6Nameservers, respIPv6Nameservers)
ipv6NameserversTF, ipv6Diags := types.ListValueFrom(ctx, types.StringType, reconciledIPv6Nameservers)
if ipv6Diags.HasError() {
return fmt.Errorf("map IPv6 network nameservers: %w", core.DiagsToError(ipv6Diags))
}
model.IPv6Nameservers = ipv6NameserversTF
}
if networkResp.Ipv6 == nil || networkResp.Ipv6.Prefixes == nil {
model.IPv6Prefixes = types.ListNull(types.StringType)
} else {
respPrefixesV6 := *networkResp.Ipv6.Prefixes
prefixesV6TF, diags := types.ListValueFrom(ctx, types.StringType, respPrefixesV6)
if diags.HasError() {
return fmt.Errorf("map network IPv6 prefixes: %w", core.DiagsToError(diags))
}
if len(respPrefixesV6) > 0 {
model.IPv6Prefix = types.StringValue(respPrefixesV6[0])
_, netmask, err := net.ParseCIDR(respPrefixesV6[0])
if err != nil {
// silently ignore parsing error for the netmask
model.IPv6PrefixLength = types.Int64Null()
} else {
ones, _ := netmask.Mask.Size()
model.IPv6PrefixLength = types.Int64Value(int64(ones))
}
}
model.IPv6Prefixes = prefixesV6TF
}
if networkResp.Ipv6 == nil || networkResp.Ipv6.Gateway == nil {
model.IPv6Gateway = types.StringNull()
} else {
model.IPv6Gateway = types.StringPointerValue(networkResp.Ipv6.GetGateway())
}
model.RoutingTableID = types.StringNull()
if networkResp.RoutingTableId != nil {
model.RoutingTableID = types.StringValue(*networkResp.RoutingTableId)
}
model.NetworkId = types.StringValue(networkId)
model.Name = types.StringPointerValue(networkResp.Name)
model.Labels = labels
model.Routed = types.BoolPointerValue(networkResp.Routed)
model.Region = types.StringValue(region)
return nil
} }

View file

@ -1,15 +1,15 @@
package v2network package network
import ( import (
"context" "context"
"testing" "testing"
"github.com/stackitcloud/stackit-sdk-go/services/iaas"
"github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp"
"github.com/hashicorp/terraform-plugin-framework/attr" "github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/types" "github.com/hashicorp/terraform-plugin-framework/types"
"github.com/stackitcloud/stackit-sdk-go/core/utils" "github.com/stackitcloud/stackit-sdk-go/core/utils"
"github.com/stackitcloud/stackit-sdk-go/services/iaasalpha"
networkModel "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaas/network/utils/model"
) )
const ( const (
@ -19,26 +19,26 @@ const (
func TestMapDataSourceFields(t *testing.T) { func TestMapDataSourceFields(t *testing.T) {
tests := []struct { tests := []struct {
description string description string
state networkModel.DataSourceModel state DataSourceModel
input *iaasalpha.Network input *iaas.Network
region string region string
expected networkModel.DataSourceModel expected DataSourceModel
isValid bool isValid bool
}{ }{
{ {
"id_ok", "id_ok",
networkModel.DataSourceModel{ DataSourceModel{
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
}, },
&iaasalpha.Network{ &iaas.Network{
Id: utils.Ptr("nid"), Id: utils.Ptr("nid"),
Ipv4: &iaasalpha.NetworkIPv4{ Ipv4: &iaas.NetworkIPv4{
Gateway: iaasalpha.NewNullableString(nil), Gateway: iaas.NewNullableString(nil),
}, },
}, },
testRegion, testRegion,
networkModel.DataSourceModel{ DataSourceModel{
Id: types.StringValue("pid,region,nid"), Id: types.StringValue("pid,region,nid"),
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
@ -64,14 +64,14 @@ func TestMapDataSourceFields(t *testing.T) {
}, },
{ {
"values_ok", "values_ok",
networkModel.DataSourceModel{ DataSourceModel{
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
}, },
&iaasalpha.Network{ &iaas.Network{
Id: utils.Ptr("nid"), Id: utils.Ptr("nid"),
Name: utils.Ptr("name"), Name: utils.Ptr("name"),
Ipv4: &iaasalpha.NetworkIPv4{ Ipv4: &iaas.NetworkIPv4{
Nameservers: &[]string{ Nameservers: &[]string{
"ns1", "ns1",
"ns2", "ns2",
@ -81,9 +81,9 @@ func TestMapDataSourceFields(t *testing.T) {
"10.100.10.0/16", "10.100.10.0/16",
}, },
PublicIp: utils.Ptr("publicIp"), PublicIp: utils.Ptr("publicIp"),
Gateway: iaasalpha.NewNullableString(utils.Ptr("gateway")), Gateway: iaas.NewNullableString(utils.Ptr("gateway")),
}, },
Ipv6: &iaasalpha.NetworkIPv6{ Ipv6: &iaas.NetworkIPv6{
Nameservers: &[]string{ Nameservers: &[]string{
"ns1", "ns1",
"ns2", "ns2",
@ -92,7 +92,7 @@ func TestMapDataSourceFields(t *testing.T) {
"fd12:3456:789a:1::/64", "fd12:3456:789a:1::/64",
"fd12:3456:789a:2::/64", "fd12:3456:789a:2::/64",
}, },
Gateway: iaasalpha.NewNullableString(utils.Ptr("gateway")), Gateway: iaas.NewNullableString(utils.Ptr("gateway")),
}, },
Labels: &map[string]interface{}{ Labels: &map[string]interface{}{
"key": "value", "key": "value",
@ -100,7 +100,7 @@ func TestMapDataSourceFields(t *testing.T) {
Routed: utils.Ptr(true), Routed: utils.Ptr(true),
}, },
testRegion, testRegion,
networkModel.DataSourceModel{ DataSourceModel{
Id: types.StringValue("pid,region,nid"), Id: types.StringValue("pid,region,nid"),
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
@ -146,7 +146,7 @@ func TestMapDataSourceFields(t *testing.T) {
}, },
{ {
"ipv4_nameservers_changed_outside_tf", "ipv4_nameservers_changed_outside_tf",
networkModel.DataSourceModel{ DataSourceModel{
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
Nameservers: types.ListValueMust(types.StringType, []attr.Value{ Nameservers: types.ListValueMust(types.StringType, []attr.Value{
@ -158,9 +158,9 @@ func TestMapDataSourceFields(t *testing.T) {
types.StringValue("ns2"), types.StringValue("ns2"),
}), }),
}, },
&iaasalpha.Network{ &iaas.Network{
Id: utils.Ptr("nid"), Id: utils.Ptr("nid"),
Ipv4: &iaasalpha.NetworkIPv4{ Ipv4: &iaas.NetworkIPv4{
Nameservers: &[]string{ Nameservers: &[]string{
"ns2", "ns2",
"ns3", "ns3",
@ -168,7 +168,7 @@ func TestMapDataSourceFields(t *testing.T) {
}, },
}, },
testRegion, testRegion,
networkModel.DataSourceModel{ DataSourceModel{
Id: types.StringValue("pid,region,nid"), Id: types.StringValue("pid,region,nid"),
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
@ -192,7 +192,7 @@ func TestMapDataSourceFields(t *testing.T) {
}, },
{ {
"ipv6_nameservers_changed_outside_tf", "ipv6_nameservers_changed_outside_tf",
networkModel.DataSourceModel{ DataSourceModel{
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
IPv6Nameservers: types.ListValueMust(types.StringType, []attr.Value{ IPv6Nameservers: types.ListValueMust(types.StringType, []attr.Value{
@ -200,9 +200,9 @@ func TestMapDataSourceFields(t *testing.T) {
types.StringValue("ns2"), types.StringValue("ns2"),
}), }),
}, },
&iaasalpha.Network{ &iaas.Network{
Id: utils.Ptr("nid"), Id: utils.Ptr("nid"),
Ipv6: &iaasalpha.NetworkIPv6{ Ipv6: &iaas.NetworkIPv6{
Nameservers: &[]string{ Nameservers: &[]string{
"ns2", "ns2",
"ns3", "ns3",
@ -210,7 +210,7 @@ func TestMapDataSourceFields(t *testing.T) {
}, },
}, },
testRegion, testRegion,
networkModel.DataSourceModel{ DataSourceModel{
Id: types.StringValue("pid,region,nid"), Id: types.StringValue("pid,region,nid"),
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
@ -231,7 +231,7 @@ func TestMapDataSourceFields(t *testing.T) {
}, },
{ {
"ipv4_prefixes_changed_outside_tf", "ipv4_prefixes_changed_outside_tf",
networkModel.DataSourceModel{ DataSourceModel{
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
Prefixes: types.ListValueMust(types.StringType, []attr.Value{ Prefixes: types.ListValueMust(types.StringType, []attr.Value{
@ -239,9 +239,9 @@ func TestMapDataSourceFields(t *testing.T) {
types.StringValue("10.100.10.0/16"), types.StringValue("10.100.10.0/16"),
}), }),
}, },
&iaasalpha.Network{ &iaas.Network{
Id: utils.Ptr("nid"), Id: utils.Ptr("nid"),
Ipv4: &iaasalpha.NetworkIPv4{ Ipv4: &iaas.NetworkIPv4{
Prefixes: &[]string{ Prefixes: &[]string{
"10.100.20.0/16", "10.100.20.0/16",
"10.100.10.0/16", "10.100.10.0/16",
@ -249,7 +249,7 @@ func TestMapDataSourceFields(t *testing.T) {
}, },
}, },
testRegion, testRegion,
networkModel.DataSourceModel{ DataSourceModel{
Id: types.StringValue("pid,region,nid"), Id: types.StringValue("pid,region,nid"),
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
@ -276,7 +276,7 @@ func TestMapDataSourceFields(t *testing.T) {
}, },
{ {
"ipv6_prefixes_changed_outside_tf", "ipv6_prefixes_changed_outside_tf",
networkModel.DataSourceModel{ DataSourceModel{
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
IPv6Prefixes: types.ListValueMust(types.StringType, []attr.Value{ IPv6Prefixes: types.ListValueMust(types.StringType, []attr.Value{
@ -284,9 +284,9 @@ func TestMapDataSourceFields(t *testing.T) {
types.StringValue("fd12:3456:789a:2::/64"), types.StringValue("fd12:3456:789a:2::/64"),
}), }),
}, },
&iaasalpha.Network{ &iaas.Network{
Id: utils.Ptr("nid"), Id: utils.Ptr("nid"),
Ipv6: &iaasalpha.NetworkIPv6{ Ipv6: &iaas.NetworkIPv6{
Prefixes: &[]string{ Prefixes: &[]string{
"fd12:3456:789a:3::/64", "fd12:3456:789a:3::/64",
"fd12:3456:789a:4::/64", "fd12:3456:789a:4::/64",
@ -294,7 +294,7 @@ func TestMapDataSourceFields(t *testing.T) {
}, },
}, },
testRegion, testRegion,
networkModel.DataSourceModel{ DataSourceModel{
Id: types.StringValue("pid,region,nid"), Id: types.StringValue("pid,region,nid"),
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
@ -318,15 +318,15 @@ func TestMapDataSourceFields(t *testing.T) {
}, },
{ {
"ipv4_ipv6_gateway_nil", "ipv4_ipv6_gateway_nil",
networkModel.DataSourceModel{ DataSourceModel{
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
}, },
&iaasalpha.Network{ &iaas.Network{
Id: utils.Ptr("nid"), Id: utils.Ptr("nid"),
}, },
testRegion, testRegion,
networkModel.DataSourceModel{ DataSourceModel{
Id: types.StringValue("pid,region,nid"), Id: types.StringValue("pid,region,nid"),
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
@ -350,20 +350,20 @@ func TestMapDataSourceFields(t *testing.T) {
}, },
{ {
"response_nil_fail", "response_nil_fail",
networkModel.DataSourceModel{}, DataSourceModel{},
nil, nil,
testRegion, testRegion,
networkModel.DataSourceModel{}, DataSourceModel{},
false, false,
}, },
{ {
"no_resource_id", "no_resource_id",
networkModel.DataSourceModel{ DataSourceModel{
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
}, },
&iaasalpha.Network{}, &iaas.Network{},
testRegion, testRegion,
networkModel.DataSourceModel{}, DataSourceModel{},
false, false,
}, },
} }

View file

@ -3,9 +3,13 @@ package network
import ( import (
"context" "context"
"fmt" "fmt"
"net"
"net/http"
"strings"
"github.com/hashicorp/terraform-plugin-framework-validators/resourcevalidator" "github.com/hashicorp/terraform-plugin-framework-validators/resourcevalidator"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/diag" "github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path" "github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/resource"
@ -18,16 +22,12 @@ import (
"github.com/hashicorp/terraform-plugin-framework/schema/validator" "github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types" "github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/stackitcloud/stackit-sdk-go/core/oapierror"
"github.com/stackitcloud/stackit-sdk-go/services/iaas" "github.com/stackitcloud/stackit-sdk-go/services/iaas"
"github.com/stackitcloud/stackit-sdk-go/services/iaasalpha" "github.com/stackitcloud/stackit-sdk-go/services/iaas/wait"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion" "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core" "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/features"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaas/network/utils/model"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaas/network/utils/v1network"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaas/network/utils/v2network"
iaasUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaas/utils" iaasUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaas/utils"
iaasAlphaUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaasalpha/utils"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils" "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate" "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
) )
@ -37,6 +37,7 @@ var (
_ resource.Resource = &networkResource{} _ resource.Resource = &networkResource{}
_ resource.ResourceWithConfigure = &networkResource{} _ resource.ResourceWithConfigure = &networkResource{}
_ resource.ResourceWithImportState = &networkResource{} _ resource.ResourceWithImportState = &networkResource{}
_ resource.ResourceWithModifyPlan = &networkResource{}
) )
const ( const (
@ -46,6 +47,32 @@ const (
"In cases where `ipv4_nameservers` are defined within the resource, the existing behavior will remain unchanged." "In cases where `ipv4_nameservers` are defined within the resource, the existing behavior will remain unchanged."
) )
type Model struct {
Id types.String `tfsdk:"id"` // needed by TF
ProjectId types.String `tfsdk:"project_id"`
NetworkId types.String `tfsdk:"network_id"`
Name types.String `tfsdk:"name"`
Nameservers types.List `tfsdk:"nameservers"`
IPv4Gateway types.String `tfsdk:"ipv4_gateway"`
IPv4Nameservers types.List `tfsdk:"ipv4_nameservers"`
IPv4Prefix types.String `tfsdk:"ipv4_prefix"`
IPv4PrefixLength types.Int64 `tfsdk:"ipv4_prefix_length"`
Prefixes types.List `tfsdk:"prefixes"`
IPv4Prefixes types.List `tfsdk:"ipv4_prefixes"`
IPv6Gateway types.String `tfsdk:"ipv6_gateway"`
IPv6Nameservers types.List `tfsdk:"ipv6_nameservers"`
IPv6Prefix types.String `tfsdk:"ipv6_prefix"`
IPv6PrefixLength types.Int64 `tfsdk:"ipv6_prefix_length"`
IPv6Prefixes types.List `tfsdk:"ipv6_prefixes"`
PublicIP types.String `tfsdk:"public_ip"`
Labels types.Map `tfsdk:"labels"`
Routed types.Bool `tfsdk:"routed"`
NoIPv4Gateway types.Bool `tfsdk:"no_ipv4_gateway"`
NoIPv6Gateway types.Bool `tfsdk:"no_ipv6_gateway"`
Region types.String `tfsdk:"region"`
RoutingTableID types.String `tfsdk:"routing_table_id"`
}
// NewNetworkResource is a helper function to simplify the provider implementation. // NewNetworkResource is a helper function to simplify the provider implementation.
func NewNetworkResource() resource.Resource { func NewNetworkResource() resource.Resource {
return &networkResource{} return &networkResource{}
@ -53,11 +80,8 @@ func NewNetworkResource() resource.Resource {
// networkResource is the resource implementation. // networkResource is the resource implementation.
type networkResource struct { type networkResource struct {
client *iaas.APIClient client *iaas.APIClient
// alphaClient will be used in case the experimental flag "network" is set providerData core.ProviderData
alphaClient *iaasalpha.APIClient
isExperimental bool
providerData core.ProviderData
} }
// Metadata returns the resource type name. // Metadata returns the resource type name.
@ -73,31 +97,18 @@ func (r *networkResource) Configure(ctx context.Context, req resource.ConfigureR
return return
} }
r.isExperimental = features.CheckExperimentEnabledWithoutError(ctx, &r.providerData, features.NetworkExperiment, "stackit_network", core.Resource, &resp.Diagnostics) apiClient := iaasUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
r.client = apiClient
if r.isExperimental {
alphaApiClient := iaasAlphaUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
r.alphaClient = alphaApiClient
} else {
apiClient := iaasUtils.ConfigureClient(ctx, &r.providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
r.client = apiClient
}
tflog.Info(ctx, "IaaS client configured") tflog.Info(ctx, "IaaS client configured")
} }
// ModifyPlan implements resource.ResourceWithModifyPlan. // ModifyPlan implements resource.ResourceWithModifyPlan.
// Use the modifier to set the effective region in the current plan. // Use the modifier to set the effective region in the current plan.
func (r *networkResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { // nolint:gocritic // function signature required by Terraform func (r *networkResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { // nolint:gocritic // function signature required by Terraform
var configModel model.Model var configModel Model
// skip initial empty configuration to avoid follow-up errors // skip initial empty configuration to avoid follow-up errors
if req.Config.Raw.IsNull() { if req.Config.Raw.IsNull() {
return return
@ -107,7 +118,7 @@ func (r *networkResource) ModifyPlan(ctx context.Context, req resource.ModifyPla
return return
} }
var planModel model.Model var planModel Model
resp.Diagnostics.Append(req.Plan.Get(ctx, &planModel)...) resp.Diagnostics.Append(req.Plan.Get(ctx, &planModel)...)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
@ -118,10 +129,6 @@ func (r *networkResource) ModifyPlan(ctx context.Context, req resource.ModifyPla
addIPv4Warning(&resp.Diagnostics) addIPv4Warning(&resp.Diagnostics)
} }
// If the v1 api is used, it's not required to get the fallback region because it isn't used
if !r.isExperimental {
return
}
utils.AdaptRegion(ctx, configModel.Region, &planModel.Region, r.providerData.GetRegion(), resp) utils.AdaptRegion(ctx, configModel.Region, &planModel.Region, r.providerData.GetRegion(), resp)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
@ -134,7 +141,7 @@ func (r *networkResource) ModifyPlan(ctx context.Context, req resource.ModifyPla
} }
func (r *networkResource) ValidateConfig(ctx context.Context, req resource.ValidateConfigRequest, resp *resource.ValidateConfigResponse) { func (r *networkResource) ValidateConfig(ctx context.Context, req resource.ValidateConfigRequest, resp *resource.ValidateConfigResponse) {
var resourceModel model.Model var resourceModel Model
resp.Diagnostics.Append(req.Config.Get(ctx, &resourceModel)...) resp.Diagnostics.Append(req.Config.Get(ctx, &resourceModel)...)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
@ -143,14 +150,6 @@ func (r *networkResource) ValidateConfig(ctx context.Context, req resource.Valid
if !resourceModel.Nameservers.IsUnknown() && !resourceModel.IPv4Nameservers.IsUnknown() && !resourceModel.Nameservers.IsNull() && !resourceModel.IPv4Nameservers.IsNull() { if !resourceModel.Nameservers.IsUnknown() && !resourceModel.IPv4Nameservers.IsUnknown() && !resourceModel.Nameservers.IsNull() && !resourceModel.IPv4Nameservers.IsNull() {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring network", "You cannot provide both the `nameservers` and `ipv4_nameservers` fields simultaneously. Please remove the deprecated `nameservers` field, and use `ipv4_nameservers` to configure nameservers for IPv4.") core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring network", "You cannot provide both the `nameservers` and `ipv4_nameservers` fields simultaneously. Please remove the deprecated `nameservers` field, and use `ipv4_nameservers` to configure nameservers for IPv4.")
} }
if !r.isExperimental {
if !utils.IsUndefined(resourceModel.Region) {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring network", "Setting the `region` is not supported yet. This can only be configured when the experiments `network` is set.")
}
if !utils.IsUndefined(resourceModel.RoutingTableID) {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring network", "Setting the field `routing_table_id` is not supported yet. This can only be configured when the experiments `network` is set.")
}
}
} }
// ConfigValidators validates the resource configuration // ConfigValidators validates the resource configuration
@ -192,7 +191,7 @@ func (r *networkResource) Schema(_ context.Context, _ resource.SchemaRequest, re
Description: description, Description: description,
Attributes: map[string]schema.Attribute{ Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{ "id": schema.StringAttribute{
Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`network_id`\".", Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`region`,`network_id`\".",
Computed: true, Computed: true,
PlanModifiers: []planmodifier.String{ PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(), stringplanmodifier.UseStateForUnknown(),
@ -359,7 +358,7 @@ func (r *networkResource) Schema(_ context.Context, _ resource.SchemaRequest, re
}, },
}, },
"routing_table_id": schema.StringAttribute{ "routing_table_id": schema.StringAttribute{
Description: "Can only be used when experimental \"network\" is set.\nThe ID of the routing table associated with the network.", Description: "The ID of the routing table associated with the network.",
Optional: true, Optional: true,
Computed: true, Computed: true,
PlanModifiers: []planmodifier.String{ PlanModifiers: []planmodifier.String{
@ -374,7 +373,7 @@ func (r *networkResource) Schema(_ context.Context, _ resource.SchemaRequest, re
Optional: true, Optional: true,
// must be computed to allow for storing the override value from the provider // must be computed to allow for storing the override value from the provider
Computed: true, Computed: true,
Description: "Can only be used when experimental \"network\" is set.\nThe resource region. If not defined, the provider region is used.", Description: "The resource region. If not defined, the provider region is used.",
PlanModifiers: []planmodifier.String{ PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplaceIfConfigured(), stringplanmodifier.RequiresReplaceIfConfigured(),
}, },
@ -386,59 +385,568 @@ func (r *networkResource) Schema(_ context.Context, _ resource.SchemaRequest, re
// Create creates the resource and sets the initial Terraform state. // Create creates the resource and sets the initial Terraform state.
func (r *networkResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform func (r *networkResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
// Retrieve values from plan // Retrieve values from plan
var planModel model.Model var model Model
diags := req.Plan.Get(ctx, &planModel) diags := req.Plan.Get(ctx, &model)
resp.Diagnostics.Append(diags...) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() { if resp.Diagnostics.HasError() {
return return
} }
// When IPv4Nameserver is not set, print warning that the behavior of ipv4_nameservers will change // When IPv4Nameserver is not set, print warning that the behavior of ipv4_nameservers will change
if utils.IsUndefined(planModel.IPv4Nameservers) { if utils.IsUndefined(model.IPv4Nameservers) {
addIPv4Warning(&resp.Diagnostics) addIPv4Warning(&resp.Diagnostics)
} }
if !r.isExperimental { projectId := model.ProjectId.ValueString()
v1network.Create(ctx, req, resp, r.client) region := r.providerData.GetRegionWithOverride(model.Region)
} else { ctx = tflog.SetField(ctx, "project_id", projectId)
v2network.Create(ctx, req, resp, r.alphaClient) ctx = tflog.SetField(ctx, "region", region)
// Generate API request body from model
payload, err := toCreatePayload(ctx, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating network", fmt.Sprintf("Creating API payload: %v", err))
return
} }
// Create new network
network, err := r.client.CreateNetwork(ctx, projectId, region).CreateNetworkPayload(*payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating network", fmt.Sprintf("Calling API: %v", err))
return
}
networkId := *network.Id
ctx = tflog.SetField(ctx, "network_id", networkId)
network, err = wait.CreateNetworkWaitHandler(ctx, r.client, projectId, region, networkId).WaitWithContext(ctx)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating network", fmt.Sprintf("Network creation waiting: %v", err))
return
}
// Map response body to schema
err = mapFields(ctx, network, &model, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating network", fmt.Sprintf("Processing API payload: %v", err))
return
}
// Set state to fully populated data
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Network created")
} }
// Read refreshes the Terraform state with the latest data. // Read refreshes the Terraform state with the latest data.
func (r *networkResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform func (r *networkResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
if !r.isExperimental { var model Model
v1network.Read(ctx, req, resp, r.client) diags := req.State.Get(ctx, &model)
} else { resp.Diagnostics.Append(diags...)
v2network.Read(ctx, req, resp, r.alphaClient, r.providerData) if resp.Diagnostics.HasError() {
return
} }
projectId := model.ProjectId.ValueString()
networkId := model.NetworkId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "network_id", networkId)
ctx = tflog.SetField(ctx, "region", region)
networkResp, err := r.client.GetNetwork(ctx, projectId, region, networkId).Execute()
if err != nil {
oapiErr, ok := err.(*oapierror.GenericOpenAPIError) //nolint:errorlint //complaining that error.As should be used to catch wrapped errors, but this error should not be wrapped
if ok && oapiErr.StatusCode == http.StatusNotFound {
resp.State.RemoveResource(ctx)
return
}
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading network", fmt.Sprintf("Calling API: %v", err))
return
}
// Map response body to schema
err = mapFields(ctx, networkResp, &model, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading network", fmt.Sprintf("Processing API payload: %v", err))
return
}
// Set refreshed state
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Network read")
} }
// Update updates the resource and sets the updated Terraform state on success. // Update updates the resource and sets the updated Terraform state on success.
func (r *networkResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform func (r *networkResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
if !r.isExperimental { // Retrieve values from plan
v1network.Update(ctx, req, resp, r.client) var model Model
} else { diags := req.Plan.Get(ctx, &model)
v2network.Update(ctx, req, resp, r.alphaClient) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
} }
projectId := model.ProjectId.ValueString()
networkId := model.NetworkId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "network_id", networkId)
ctx = tflog.SetField(ctx, "region", region)
// Retrieve values from state
var stateModel Model
diags = req.State.Get(ctx, &stateModel)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// Generate API request body from model
payload, err := toUpdatePayload(ctx, &model, &stateModel)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating network", fmt.Sprintf("Creating API payload: %v", err))
return
}
// Update existing network
err = r.client.PartialUpdateNetwork(ctx, projectId, region, networkId).PartialUpdateNetworkPayload(*payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating network", fmt.Sprintf("Calling API: %v", err))
return
}
waitResp, err := wait.UpdateNetworkWaitHandler(ctx, r.client, projectId, region, networkId).WaitWithContext(ctx)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating network", fmt.Sprintf("Network update waiting: %v", err))
return
}
err = mapFields(ctx, waitResp, &model, region)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating network", fmt.Sprintf("Processing API payload: %v", err))
return
}
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Network updated")
} }
// Delete deletes the resource and removes the Terraform state on success. // Delete deletes the resource and removes the Terraform state on success.
func (r *networkResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform func (r *networkResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
if !r.isExperimental { // Retrieve values from state
v1network.Delete(ctx, req, resp, r.client) var model Model
} else { diags := req.State.Get(ctx, &model)
v2network.Delete(ctx, req, resp, r.alphaClient) resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
} }
projectId := model.ProjectId.ValueString()
networkId := model.NetworkId.ValueString()
region := model.Region.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "network_id", networkId)
ctx = tflog.SetField(ctx, "region", region)
// Delete existing network
err := r.client.DeleteNetwork(ctx, projectId, region, networkId).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting network", fmt.Sprintf("Calling API: %v", err))
return
}
_, err = wait.DeleteNetworkWaitHandler(ctx, r.client, projectId, region, networkId).WaitWithContext(ctx)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting network", fmt.Sprintf("Network deletion waiting: %v", err))
return
}
tflog.Info(ctx, "Network deleted")
} }
// ImportState imports a resource into the Terraform state on success. // ImportState imports a resource into the Terraform state on success.
// The expected format of the resource import identifier is: project_id,network_id // The expected format of the resource import identifier is: project_id,region,network_id
func (r *networkResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { func (r *networkResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
if !r.isExperimental { idParts := strings.Split(req.ID, core.Separator)
v1network.ImportState(ctx, req, resp)
} else { if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
v2network.ImportState(ctx, req, resp) core.LogAndAddError(ctx, &resp.Diagnostics,
"Error importing network",
fmt.Sprintf("Expected import identifier with format: [project_id],[region],[network_id] Got: %q", req.ID),
)
return
} }
projectId := idParts[0]
region := idParts[1]
networkId := idParts[2]
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "network_id", networkId)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), projectId)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("region"), region)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("network_id"), networkId)...)
tflog.Info(ctx, "Network state imported")
}
func mapFields(ctx context.Context, networkResp *iaas.Network, model *Model, region string) error {
if networkResp == nil {
return fmt.Errorf("response input is nil")
}
if model == nil {
return fmt.Errorf("model input is nil")
}
var networkId string
if model.NetworkId.ValueString() != "" {
networkId = model.NetworkId.ValueString()
} else if networkResp.Id != nil {
networkId = *networkResp.Id
} else {
return fmt.Errorf("network id not present")
}
model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), region, networkId)
labels, err := iaasUtils.MapLabels(ctx, networkResp.Labels, model.Labels)
if err != nil {
return err
}
// IPv4
if networkResp.Ipv4 == nil || networkResp.Ipv4.Nameservers == nil {
model.Nameservers = types.ListNull(types.StringType)
model.IPv4Nameservers = types.ListNull(types.StringType)
} else {
respNameservers := *networkResp.Ipv4.Nameservers
modelNameservers, err := utils.ListValuetoStringSlice(model.Nameservers)
modelIPv4Nameservers, errIpv4 := utils.ListValuetoStringSlice(model.IPv4Nameservers)
if err != nil {
return fmt.Errorf("get current network nameservers from model: %w", err)
}
if errIpv4 != nil {
return fmt.Errorf("get current IPv4 network nameservers from model: %w", errIpv4)
}
reconciledNameservers := utils.ReconcileStringSlices(modelNameservers, respNameservers)
reconciledIPv4Nameservers := utils.ReconcileStringSlices(modelIPv4Nameservers, respNameservers)
nameserversTF, diags := types.ListValueFrom(ctx, types.StringType, reconciledNameservers)
ipv4NameserversTF, ipv4Diags := types.ListValueFrom(ctx, types.StringType, reconciledIPv4Nameservers)
if diags.HasError() {
return fmt.Errorf("map network nameservers: %w", core.DiagsToError(diags))
}
if ipv4Diags.HasError() {
return fmt.Errorf("map IPv4 network nameservers: %w", core.DiagsToError(ipv4Diags))
}
model.Nameservers = nameserversTF
model.IPv4Nameservers = ipv4NameserversTF
}
model.IPv4PrefixLength = types.Int64Null()
if networkResp.Ipv4 == nil || networkResp.Ipv4.Prefixes == nil {
model.Prefixes = types.ListNull(types.StringType)
model.IPv4Prefixes = types.ListNull(types.StringType)
} else {
respPrefixes := *networkResp.Ipv4.Prefixes
prefixesTF, diags := types.ListValueFrom(ctx, types.StringType, respPrefixes)
if diags.HasError() {
return fmt.Errorf("map network prefixes: %w", core.DiagsToError(diags))
}
if len(respPrefixes) > 0 {
model.IPv4Prefix = types.StringValue(respPrefixes[0])
_, netmask, err := net.ParseCIDR(respPrefixes[0])
if err != nil {
tflog.Error(ctx, fmt.Sprintf("ipv4_prefix_length: %+v", err))
// silently ignore parsing error for the netmask
model.IPv4PrefixLength = types.Int64Null()
} else {
ones, _ := netmask.Mask.Size()
model.IPv4PrefixLength = types.Int64Value(int64(ones))
}
}
model.Prefixes = prefixesTF
model.IPv4Prefixes = prefixesTF
}
if networkResp.Ipv4 == nil || networkResp.Ipv4.Gateway == nil {
model.IPv4Gateway = types.StringNull()
} else {
model.IPv4Gateway = types.StringPointerValue(networkResp.Ipv4.GetGateway())
}
if networkResp.Ipv4 == nil || networkResp.Ipv4.PublicIp == nil {
model.PublicIP = types.StringNull()
} else {
model.PublicIP = types.StringPointerValue(networkResp.Ipv4.PublicIp)
}
// IPv6
if networkResp.Ipv6 == nil || networkResp.Ipv6.Nameservers == nil {
model.IPv6Nameservers = types.ListNull(types.StringType)
} else {
respIPv6Nameservers := *networkResp.Ipv6.Nameservers
modelIPv6Nameservers, errIpv6 := utils.ListValuetoStringSlice(model.IPv6Nameservers)
if errIpv6 != nil {
return fmt.Errorf("get current IPv6 network nameservers from model: %w", errIpv6)
}
reconciledIPv6Nameservers := utils.ReconcileStringSlices(modelIPv6Nameservers, respIPv6Nameservers)
ipv6NameserversTF, ipv6Diags := types.ListValueFrom(ctx, types.StringType, reconciledIPv6Nameservers)
if ipv6Diags.HasError() {
return fmt.Errorf("map IPv6 network nameservers: %w", core.DiagsToError(ipv6Diags))
}
model.IPv6Nameservers = ipv6NameserversTF
}
model.IPv6PrefixLength = types.Int64Null()
model.IPv6Prefix = types.StringNull()
if networkResp.Ipv6 == nil || networkResp.Ipv6.Prefixes == nil {
model.IPv6Prefixes = types.ListNull(types.StringType)
} else {
respPrefixesV6 := *networkResp.Ipv6.Prefixes
prefixesV6TF, diags := types.ListValueFrom(ctx, types.StringType, respPrefixesV6)
if diags.HasError() {
return fmt.Errorf("map network IPv6 prefixes: %w", core.DiagsToError(diags))
}
if len(respPrefixesV6) > 0 {
model.IPv6Prefix = types.StringValue(respPrefixesV6[0])
_, netmask, err := net.ParseCIDR(respPrefixesV6[0])
if err != nil {
// silently ignore parsing error for the netmask
model.IPv6PrefixLength = types.Int64Null()
} else {
ones, _ := netmask.Mask.Size()
model.IPv6PrefixLength = types.Int64Value(int64(ones))
}
}
model.IPv6Prefixes = prefixesV6TF
}
if networkResp.Ipv6 == nil || networkResp.Ipv6.Gateway == nil {
model.IPv6Gateway = types.StringNull()
} else {
model.IPv6Gateway = types.StringPointerValue(networkResp.Ipv6.GetGateway())
}
model.RoutingTableID = types.StringPointerValue(networkResp.RoutingTableId)
model.NetworkId = types.StringValue(networkId)
model.Name = types.StringPointerValue(networkResp.Name)
model.Labels = labels
model.Routed = types.BoolPointerValue(networkResp.Routed)
model.Region = types.StringValue(region)
return nil
}
func toCreatePayload(ctx context.Context, model *Model) (*iaas.CreateNetworkPayload, error) {
if model == nil {
return nil, fmt.Errorf("nil model")
}
var modelIPv6Nameservers []string
// Is true when IPv6Nameservers is not null or unset
if !utils.IsUndefined(model.IPv6Nameservers) {
// If ipv6Nameservers is empty, modelIPv6Nameservers will be set to an empty slice.
// empty slice != nil slice. Empty slice will result in an empty list in the payload []. Nil slice will result in a payload without the property set
modelIPv6Nameservers = []string{}
for _, ipv6ns := range model.IPv6Nameservers.Elements() {
ipv6NameserverString, ok := ipv6ns.(types.String)
if !ok {
return nil, fmt.Errorf("type assertion failed")
}
modelIPv6Nameservers = append(modelIPv6Nameservers, ipv6NameserverString.ValueString())
}
}
var ipv6Body *iaas.CreateNetworkIPv6
if !utils.IsUndefined(model.IPv6PrefixLength) {
ipv6Body = &iaas.CreateNetworkIPv6{
CreateNetworkIPv6WithPrefixLength: &iaas.CreateNetworkIPv6WithPrefixLength{
PrefixLength: conversion.Int64ValueToPointer(model.IPv6PrefixLength),
},
}
// IPv6 nameservers should only be set, if it contains any value. If the slice is nil, it should NOT be set.
// Setting it to a nil slice would result in a payload, where nameservers is set to null in the json payload,
// but it should actually be unset. Setting it to "null" will result in an error, because it's NOT nullable.
if modelIPv6Nameservers != nil {
ipv6Body.CreateNetworkIPv6WithPrefixLength.Nameservers = &modelIPv6Nameservers
}
} else if !utils.IsUndefined(model.IPv6Prefix) {
var gateway *iaas.NullableString
if model.NoIPv6Gateway.ValueBool() {
gateway = iaas.NewNullableString(nil)
} else if !(model.IPv6Gateway.IsUnknown() || model.IPv6Gateway.IsNull()) {
gateway = iaas.NewNullableString(conversion.StringValueToPointer(model.IPv6Gateway))
}
ipv6Body = &iaas.CreateNetworkIPv6{
CreateNetworkIPv6WithPrefix: &iaas.CreateNetworkIPv6WithPrefix{
Gateway: gateway,
Prefix: conversion.StringValueToPointer(model.IPv6Prefix),
},
}
// IPv6 nameservers should only be set, if it contains any value. If the slice is nil, it should NOT be set.
// Setting it to a nil slice would result in a payload, where nameservers is set to null in the json payload,
// but it should actually be unset. Setting it to "null" will result in an error, because it's NOT nullable.
if modelIPv6Nameservers != nil {
ipv6Body.CreateNetworkIPv6WithPrefix.Nameservers = &modelIPv6Nameservers
}
}
modelIPv4Nameservers := []string{}
var modelIPv4List []attr.Value
if !(model.IPv4Nameservers.IsNull() || model.IPv4Nameservers.IsUnknown()) {
modelIPv4List = model.IPv4Nameservers.Elements()
} else {
modelIPv4List = model.Nameservers.Elements()
}
for _, ipv4ns := range modelIPv4List {
ipv4NameserverString, ok := ipv4ns.(types.String)
if !ok {
return nil, fmt.Errorf("type assertion failed")
}
modelIPv4Nameservers = append(modelIPv4Nameservers, ipv4NameserverString.ValueString())
}
var ipv4Body *iaas.CreateNetworkIPv4
if !utils.IsUndefined(model.IPv4PrefixLength) {
ipv4Body = &iaas.CreateNetworkIPv4{
CreateNetworkIPv4WithPrefixLength: &iaas.CreateNetworkIPv4WithPrefixLength{
Nameservers: &modelIPv4Nameservers,
PrefixLength: conversion.Int64ValueToPointer(model.IPv4PrefixLength),
},
}
} else if !utils.IsUndefined(model.IPv4Prefix) {
var gateway *iaas.NullableString
if model.NoIPv4Gateway.ValueBool() {
gateway = iaas.NewNullableString(nil)
} else if !(model.IPv4Gateway.IsUnknown() || model.IPv4Gateway.IsNull()) {
gateway = iaas.NewNullableString(conversion.StringValueToPointer(model.IPv4Gateway))
}
ipv4Body = &iaas.CreateNetworkIPv4{
CreateNetworkIPv4WithPrefix: &iaas.CreateNetworkIPv4WithPrefix{
Nameservers: &modelIPv4Nameservers,
Prefix: conversion.StringValueToPointer(model.IPv4Prefix),
Gateway: gateway,
},
}
}
labels, err := conversion.ToStringInterfaceMap(ctx, model.Labels)
if err != nil {
return nil, fmt.Errorf("converting to Go map: %w", err)
}
payload := iaas.CreateNetworkPayload{
Name: conversion.StringValueToPointer(model.Name),
Labels: &labels,
Routed: conversion.BoolValueToPointer(model.Routed),
Ipv4: ipv4Body,
Ipv6: ipv6Body,
RoutingTableId: conversion.StringValueToPointer(model.RoutingTableID),
}
return &payload, nil
}
func toUpdatePayload(ctx context.Context, model, stateModel *Model) (*iaas.PartialUpdateNetworkPayload, error) {
if model == nil {
return nil, fmt.Errorf("nil model")
}
var modelIPv6Nameservers []string
// Is true when IPv6Nameservers is not null or unset
if !utils.IsUndefined(model.IPv6Nameservers) {
// If ipv6Nameservers is empty, modelIPv6Nameservers will be set to an empty slice.
// empty slice != nil slice. Empty slice will result in an empty list in the payload []. Nil slice will result in a payload without the property set
modelIPv6Nameservers = []string{}
for _, ipv6ns := range model.IPv6Nameservers.Elements() {
ipv6NameserverString, ok := ipv6ns.(types.String)
if !ok {
return nil, fmt.Errorf("type assertion failed")
}
modelIPv6Nameservers = append(modelIPv6Nameservers, ipv6NameserverString.ValueString())
}
}
var ipv6Body *iaas.UpdateNetworkIPv6Body
if modelIPv6Nameservers != nil || !utils.IsUndefined(model.NoIPv6Gateway) || !utils.IsUndefined(model.IPv6Gateway) {
ipv6Body = &iaas.UpdateNetworkIPv6Body{}
// IPv6 nameservers should only be set, if it contains any value. If the slice is nil, it should NOT be set.
// Setting it to a nil slice would result in a payload, where nameservers is set to null in the json payload,
// but it should actually be unset. Setting it to "null" will result in an error, because it's NOT nullable.
if modelIPv6Nameservers != nil {
ipv6Body.Nameservers = &modelIPv6Nameservers
}
if model.NoIPv6Gateway.ValueBool() {
ipv6Body.Gateway = iaas.NewNullableString(nil)
} else if !(model.IPv6Gateway.IsUnknown() || model.IPv6Gateway.IsNull()) {
ipv6Body.Gateway = iaas.NewNullableString(conversion.StringValueToPointer(model.IPv6Gateway))
}
}
modelIPv4Nameservers := []string{}
var modelIPv4List []attr.Value
if !(model.IPv4Nameservers.IsNull() || model.IPv4Nameservers.IsUnknown()) {
modelIPv4List = model.IPv4Nameservers.Elements()
} else {
modelIPv4List = model.Nameservers.Elements()
}
for _, ipv4ns := range modelIPv4List {
ipv4NameserverString, ok := ipv4ns.(types.String)
if !ok {
return nil, fmt.Errorf("type assertion failed")
}
modelIPv4Nameservers = append(modelIPv4Nameservers, ipv4NameserverString.ValueString())
}
var ipv4Body *iaas.UpdateNetworkIPv4Body
if !model.IPv4Nameservers.IsNull() || !model.Nameservers.IsNull() {
ipv4Body = &iaas.UpdateNetworkIPv4Body{
Nameservers: &modelIPv4Nameservers,
}
if model.NoIPv4Gateway.ValueBool() {
ipv4Body.Gateway = iaas.NewNullableString(nil)
} else if !(model.IPv4Gateway.IsUnknown() || model.IPv4Gateway.IsNull()) {
ipv4Body.Gateway = iaas.NewNullableString(conversion.StringValueToPointer(model.IPv4Gateway))
}
}
currentLabels := stateModel.Labels
labels, err := conversion.ToJSONMapPartialUpdatePayload(ctx, currentLabels, model.Labels)
if err != nil {
return nil, fmt.Errorf("converting to Go map: %w", err)
}
payload := iaas.PartialUpdateNetworkPayload{
Name: conversion.StringValueToPointer(model.Name),
Labels: &labels,
Ipv4: ipv4Body,
Ipv6: ipv6Body,
RoutingTableId: conversion.StringValueToPointer(model.RoutingTableID),
}
return &payload, nil
} }
func addIPv4Warning(diags *diag.Diagnostics) { func addIPv4Warning(diags *diag.Diagnostics) {

View file

@ -1,4 +1,4 @@
package v2network package network
import ( import (
"context" "context"
@ -8,34 +8,33 @@ import (
"github.com/hashicorp/terraform-plugin-framework/attr" "github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/types" "github.com/hashicorp/terraform-plugin-framework/types"
"github.com/stackitcloud/stackit-sdk-go/core/utils" "github.com/stackitcloud/stackit-sdk-go/core/utils"
"github.com/stackitcloud/stackit-sdk-go/services/iaasalpha" "github.com/stackitcloud/stackit-sdk-go/services/iaas"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaas/network/utils/model"
) )
func TestMapFields(t *testing.T) { func TestMapFields(t *testing.T) {
const testRegion = "region" const testRegion = "region"
tests := []struct { tests := []struct {
description string description string
state model.Model state Model
input *iaasalpha.Network input *iaas.Network
region string region string
expected model.Model expected Model
isValid bool isValid bool
}{ }{
{ {
"id_ok", "id_ok",
model.Model{ Model{
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
}, },
&iaasalpha.Network{ &iaas.Network{
Id: utils.Ptr("nid"), Id: utils.Ptr("nid"),
Ipv4: &iaasalpha.NetworkIPv4{ Ipv4: &iaas.NetworkIPv4{
Gateway: iaasalpha.NewNullableString(nil), Gateway: iaas.NewNullableString(nil),
}, },
}, },
testRegion, testRegion,
model.Model{ Model{
Id: types.StringValue("pid,region,nid"), Id: types.StringValue("pid,region,nid"),
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
@ -61,14 +60,14 @@ func TestMapFields(t *testing.T) {
}, },
{ {
"values_ok", "values_ok",
model.Model{ Model{
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
}, },
&iaasalpha.Network{ &iaas.Network{
Id: utils.Ptr("nid"), Id: utils.Ptr("nid"),
Name: utils.Ptr("name"), Name: utils.Ptr("name"),
Ipv4: &iaasalpha.NetworkIPv4{ Ipv4: &iaas.NetworkIPv4{
Nameservers: utils.Ptr([]string{"ns1", "ns2"}), Nameservers: utils.Ptr([]string{"ns1", "ns2"}),
Prefixes: utils.Ptr( Prefixes: utils.Ptr(
[]string{ []string{
@ -77,15 +76,15 @@ func TestMapFields(t *testing.T) {
}, },
), ),
PublicIp: utils.Ptr("publicIp"), PublicIp: utils.Ptr("publicIp"),
Gateway: iaasalpha.NewNullableString(utils.Ptr("gateway")), Gateway: iaas.NewNullableString(utils.Ptr("gateway")),
}, },
Ipv6: &iaasalpha.NetworkIPv6{ Ipv6: &iaas.NetworkIPv6{
Nameservers: utils.Ptr([]string{"ns1", "ns2"}), Nameservers: utils.Ptr([]string{"ns1", "ns2"}),
Prefixes: utils.Ptr([]string{ Prefixes: utils.Ptr([]string{
"fd12:3456:789a:1::/64", "fd12:3456:789a:1::/64",
"fd12:3456:789b:1::/64", "fd12:3456:789b:1::/64",
}), }),
Gateway: iaasalpha.NewNullableString(utils.Ptr("gateway")), Gateway: iaas.NewNullableString(utils.Ptr("gateway")),
}, },
Labels: &map[string]interface{}{ Labels: &map[string]interface{}{
"key": "value", "key": "value",
@ -93,7 +92,7 @@ func TestMapFields(t *testing.T) {
Routed: utils.Ptr(true), Routed: utils.Ptr(true),
}, },
testRegion, testRegion,
model.Model{ Model{
Id: types.StringValue("pid,region,nid"), Id: types.StringValue("pid,region,nid"),
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
@ -139,7 +138,7 @@ func TestMapFields(t *testing.T) {
}, },
{ {
"ipv4_nameservers_changed_outside_tf", "ipv4_nameservers_changed_outside_tf",
model.Model{ Model{
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
Nameservers: types.ListValueMust(types.StringType, []attr.Value{ Nameservers: types.ListValueMust(types.StringType, []attr.Value{
@ -151,9 +150,9 @@ func TestMapFields(t *testing.T) {
types.StringValue("ns2"), types.StringValue("ns2"),
}), }),
}, },
&iaasalpha.Network{ &iaas.Network{
Id: utils.Ptr("nid"), Id: utils.Ptr("nid"),
Ipv4: &iaasalpha.NetworkIPv4{ Ipv4: &iaas.NetworkIPv4{
Nameservers: utils.Ptr([]string{ Nameservers: utils.Ptr([]string{
"ns2", "ns2",
"ns3", "ns3",
@ -161,7 +160,7 @@ func TestMapFields(t *testing.T) {
}, },
}, },
testRegion, testRegion,
model.Model{ Model{
Id: types.StringValue("pid,region,nid"), Id: types.StringValue("pid,region,nid"),
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
@ -185,7 +184,7 @@ func TestMapFields(t *testing.T) {
}, },
{ {
"ipv6_nameservers_changed_outside_tf", "ipv6_nameservers_changed_outside_tf",
model.Model{ Model{
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
IPv6Nameservers: types.ListValueMust(types.StringType, []attr.Value{ IPv6Nameservers: types.ListValueMust(types.StringType, []attr.Value{
@ -193,9 +192,9 @@ func TestMapFields(t *testing.T) {
types.StringValue("ns2"), types.StringValue("ns2"),
}), }),
}, },
&iaasalpha.Network{ &iaas.Network{
Id: utils.Ptr("nid"), Id: utils.Ptr("nid"),
Ipv6: &iaasalpha.NetworkIPv6{ Ipv6: &iaas.NetworkIPv6{
Nameservers: utils.Ptr([]string{ Nameservers: utils.Ptr([]string{
"ns2", "ns2",
"ns3", "ns3",
@ -203,7 +202,7 @@ func TestMapFields(t *testing.T) {
}, },
}, },
testRegion, testRegion,
model.Model{ Model{
Id: types.StringValue("pid,region,nid"), Id: types.StringValue("pid,region,nid"),
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
@ -224,7 +223,7 @@ func TestMapFields(t *testing.T) {
}, },
{ {
"ipv4_prefixes_changed_outside_tf", "ipv4_prefixes_changed_outside_tf",
model.Model{ Model{
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
Prefixes: types.ListValueMust(types.StringType, []attr.Value{ Prefixes: types.ListValueMust(types.StringType, []attr.Value{
@ -232,9 +231,9 @@ func TestMapFields(t *testing.T) {
types.StringValue("10.100.10.0/24"), types.StringValue("10.100.10.0/24"),
}), }),
}, },
&iaasalpha.Network{ &iaas.Network{
Id: utils.Ptr("nid"), Id: utils.Ptr("nid"),
Ipv4: &iaasalpha.NetworkIPv4{ Ipv4: &iaas.NetworkIPv4{
Prefixes: utils.Ptr( Prefixes: utils.Ptr(
[]string{ []string{
"192.168.54.0/24", "192.168.54.0/24",
@ -244,7 +243,7 @@ func TestMapFields(t *testing.T) {
}, },
}, },
testRegion, testRegion,
model.Model{ Model{
Id: types.StringValue("pid,region,nid"), Id: types.StringValue("pid,region,nid"),
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
@ -271,7 +270,7 @@ func TestMapFields(t *testing.T) {
}, },
{ {
"ipv6_prefixes_changed_outside_tf", "ipv6_prefixes_changed_outside_tf",
model.Model{ Model{
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
IPv6Prefixes: types.ListValueMust(types.StringType, []attr.Value{ IPv6Prefixes: types.ListValueMust(types.StringType, []attr.Value{
@ -279,9 +278,9 @@ func TestMapFields(t *testing.T) {
types.StringValue("fd12:3456:789a:2::/64"), types.StringValue("fd12:3456:789a:2::/64"),
}), }),
}, },
&iaasalpha.Network{ &iaas.Network{
Id: utils.Ptr("nid"), Id: utils.Ptr("nid"),
Ipv6: &iaasalpha.NetworkIPv6{ Ipv6: &iaas.NetworkIPv6{
Prefixes: utils.Ptr( Prefixes: utils.Ptr(
[]string{ []string{
"fd12:3456:789a:1::/64", "fd12:3456:789a:1::/64",
@ -291,7 +290,7 @@ func TestMapFields(t *testing.T) {
}, },
}, },
testRegion, testRegion,
model.Model{ Model{
Id: types.StringValue("pid,region,nid"), Id: types.StringValue("pid,region,nid"),
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
@ -315,15 +314,15 @@ func TestMapFields(t *testing.T) {
}, },
{ {
"ipv4_ipv6_gateway_nil", "ipv4_ipv6_gateway_nil",
model.Model{ Model{
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
}, },
&iaasalpha.Network{ &iaas.Network{
Id: utils.Ptr("nid"), Id: utils.Ptr("nid"),
}, },
testRegion, testRegion,
model.Model{ Model{
Id: types.StringValue("pid,region,nid"), Id: types.StringValue("pid,region,nid"),
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
@ -347,20 +346,20 @@ func TestMapFields(t *testing.T) {
}, },
{ {
"response_nil_fail", "response_nil_fail",
model.Model{}, Model{},
nil, nil,
testRegion, testRegion,
model.Model{}, Model{},
false, false,
}, },
{ {
"no_resource_id", "no_resource_id",
model.Model{ Model{
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
}, },
&iaasalpha.Network{}, &iaas.Network{},
testRegion, testRegion,
model.Model{}, Model{},
false, false,
}, },
} }
@ -386,13 +385,13 @@ func TestMapFields(t *testing.T) {
func TestToCreatePayload(t *testing.T) { func TestToCreatePayload(t *testing.T) {
tests := []struct { tests := []struct {
description string description string
input *model.Model input *Model
expected *iaasalpha.CreateNetworkPayload expected *iaas.CreateNetworkPayload
isValid bool isValid bool
}{ }{
{ {
"default_ok", "default_ok",
&model.Model{ &Model{
Name: types.StringValue("name"), Name: types.StringValue("name"),
IPv4Nameservers: types.ListValueMust(types.StringType, []attr.Value{ IPv4Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"), types.StringValue("ns1"),
@ -405,11 +404,11 @@ func TestToCreatePayload(t *testing.T) {
IPv4Gateway: types.StringValue("gateway"), IPv4Gateway: types.StringValue("gateway"),
IPv4Prefix: types.StringValue("prefix"), IPv4Prefix: types.StringValue("prefix"),
}, },
&iaasalpha.CreateNetworkPayload{ &iaas.CreateNetworkPayload{
Name: utils.Ptr("name"), Name: utils.Ptr("name"),
Ipv4: &iaasalpha.CreateNetworkIPv4{ Ipv4: &iaas.CreateNetworkIPv4{
CreateNetworkIPv4WithPrefix: &iaasalpha.CreateNetworkIPv4WithPrefix{ CreateNetworkIPv4WithPrefix: &iaas.CreateNetworkIPv4WithPrefix{
Gateway: iaasalpha.NewNullableString(utils.Ptr("gateway")), Gateway: iaas.NewNullableString(utils.Ptr("gateway")),
Nameservers: utils.Ptr([]string{ Nameservers: utils.Ptr([]string{
"ns1", "ns1",
"ns2", "ns2",
@ -426,7 +425,7 @@ func TestToCreatePayload(t *testing.T) {
}, },
{ {
"ipv4_nameservers_okay", "ipv4_nameservers_okay",
&model.Model{ &Model{
Name: types.StringValue("name"), Name: types.StringValue("name"),
Nameservers: types.ListValueMust(types.StringType, []attr.Value{ Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"), types.StringValue("ns1"),
@ -439,11 +438,11 @@ func TestToCreatePayload(t *testing.T) {
IPv4Gateway: types.StringValue("gateway"), IPv4Gateway: types.StringValue("gateway"),
IPv4Prefix: types.StringValue("prefix"), IPv4Prefix: types.StringValue("prefix"),
}, },
&iaasalpha.CreateNetworkPayload{ &iaas.CreateNetworkPayload{
Name: utils.Ptr("name"), Name: utils.Ptr("name"),
Ipv4: &iaasalpha.CreateNetworkIPv4{ Ipv4: &iaas.CreateNetworkIPv4{
CreateNetworkIPv4WithPrefix: &iaasalpha.CreateNetworkIPv4WithPrefix{ CreateNetworkIPv4WithPrefix: &iaas.CreateNetworkIPv4WithPrefix{
Gateway: iaasalpha.NewNullableString(utils.Ptr("gateway")), Gateway: iaas.NewNullableString(utils.Ptr("gateway")),
Nameservers: utils.Ptr([]string{ Nameservers: utils.Ptr([]string{
"ns1", "ns1",
"ns2", "ns2",
@ -460,7 +459,7 @@ func TestToCreatePayload(t *testing.T) {
}, },
{ {
"ipv6_default_ok", "ipv6_default_ok",
&model.Model{ &Model{
Name: types.StringValue("name"), Name: types.StringValue("name"),
IPv6Nameservers: types.ListValueMust(types.StringType, []attr.Value{ IPv6Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"), types.StringValue("ns1"),
@ -473,11 +472,11 @@ func TestToCreatePayload(t *testing.T) {
IPv6Gateway: types.StringValue("gateway"), IPv6Gateway: types.StringValue("gateway"),
IPv6Prefix: types.StringValue("prefix"), IPv6Prefix: types.StringValue("prefix"),
}, },
&iaasalpha.CreateNetworkPayload{ &iaas.CreateNetworkPayload{
Name: utils.Ptr("name"), Name: utils.Ptr("name"),
Ipv6: &iaasalpha.CreateNetworkIPv6{ Ipv6: &iaas.CreateNetworkIPv6{
CreateNetworkIPv6WithPrefix: &iaasalpha.CreateNetworkIPv6WithPrefix{ CreateNetworkIPv6WithPrefix: &iaas.CreateNetworkIPv6WithPrefix{
Gateway: iaasalpha.NewNullableString(utils.Ptr("gateway")), Gateway: iaas.NewNullableString(utils.Ptr("gateway")),
Nameservers: utils.Ptr([]string{ Nameservers: utils.Ptr([]string{
"ns1", "ns1",
"ns2", "ns2",
@ -494,7 +493,7 @@ func TestToCreatePayload(t *testing.T) {
}, },
{ {
"ipv6_nameserver_null", "ipv6_nameserver_null",
&model.Model{ &Model{
Name: types.StringValue("name"), Name: types.StringValue("name"),
IPv6Nameservers: types.ListNull(types.StringType), IPv6Nameservers: types.ListNull(types.StringType),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{ Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
@ -504,12 +503,12 @@ func TestToCreatePayload(t *testing.T) {
IPv6Gateway: types.StringValue("gateway"), IPv6Gateway: types.StringValue("gateway"),
IPv6Prefix: types.StringValue("prefix"), IPv6Prefix: types.StringValue("prefix"),
}, },
&iaasalpha.CreateNetworkPayload{ &iaas.CreateNetworkPayload{
Name: utils.Ptr("name"), Name: utils.Ptr("name"),
Ipv6: &iaasalpha.CreateNetworkIPv6{ Ipv6: &iaas.CreateNetworkIPv6{
CreateNetworkIPv6WithPrefix: &iaasalpha.CreateNetworkIPv6WithPrefix{ CreateNetworkIPv6WithPrefix: &iaas.CreateNetworkIPv6WithPrefix{
Nameservers: nil, Nameservers: nil,
Gateway: iaasalpha.NewNullableString(utils.Ptr("gateway")), Gateway: iaas.NewNullableString(utils.Ptr("gateway")),
Prefix: utils.Ptr("prefix"), Prefix: utils.Ptr("prefix"),
}, },
}, },
@ -522,7 +521,7 @@ func TestToCreatePayload(t *testing.T) {
}, },
{ {
"ipv6_nameserver_empty_list", "ipv6_nameserver_empty_list",
&model.Model{ &Model{
Name: types.StringValue("name"), Name: types.StringValue("name"),
IPv6Nameservers: types.ListValueMust(types.StringType, []attr.Value{}), IPv6Nameservers: types.ListValueMust(types.StringType, []attr.Value{}),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{ Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
@ -532,12 +531,12 @@ func TestToCreatePayload(t *testing.T) {
IPv6Gateway: types.StringValue("gateway"), IPv6Gateway: types.StringValue("gateway"),
IPv6Prefix: types.StringValue("prefix"), IPv6Prefix: types.StringValue("prefix"),
}, },
&iaasalpha.CreateNetworkPayload{ &iaas.CreateNetworkPayload{
Name: utils.Ptr("name"), Name: utils.Ptr("name"),
Ipv6: &iaasalpha.CreateNetworkIPv6{ Ipv6: &iaas.CreateNetworkIPv6{
CreateNetworkIPv6WithPrefix: &iaasalpha.CreateNetworkIPv6WithPrefix{ CreateNetworkIPv6WithPrefix: &iaas.CreateNetworkIPv6WithPrefix{
Nameservers: utils.Ptr([]string{}), Nameservers: utils.Ptr([]string{}),
Gateway: iaasalpha.NewNullableString(utils.Ptr("gateway")), Gateway: iaas.NewNullableString(utils.Ptr("gateway")),
Prefix: utils.Ptr("prefix"), Prefix: utils.Ptr("prefix"),
}, },
}, },
@ -559,7 +558,7 @@ func TestToCreatePayload(t *testing.T) {
t.Fatalf("Should not have failed: %v", err) t.Fatalf("Should not have failed: %v", err)
} }
if tt.isValid { if tt.isValid {
diff := cmp.Diff(output, tt.expected, cmp.AllowUnexported(iaasalpha.NullableString{})) diff := cmp.Diff(output, tt.expected, cmp.AllowUnexported(iaas.NullableString{}))
if diff != "" { if diff != "" {
t.Fatalf("Data does not match: %s", diff) t.Fatalf("Data does not match: %s", diff)
} }
@ -571,14 +570,14 @@ func TestToCreatePayload(t *testing.T) {
func TestToUpdatePayload(t *testing.T) { func TestToUpdatePayload(t *testing.T) {
tests := []struct { tests := []struct {
description string description string
input *model.Model input *Model
state model.Model state Model
expected *iaasalpha.PartialUpdateNetworkPayload expected *iaas.PartialUpdateNetworkPayload
isValid bool isValid bool
}{ }{
{ {
"default_ok", "default_ok",
&model.Model{ &Model{
Name: types.StringValue("name"), Name: types.StringValue("name"),
IPv4Nameservers: types.ListValueMust(types.StringType, []attr.Value{ IPv4Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"), types.StringValue("ns1"),
@ -590,15 +589,15 @@ func TestToUpdatePayload(t *testing.T) {
Routed: types.BoolValue(true), Routed: types.BoolValue(true),
IPv4Gateway: types.StringValue("gateway"), IPv4Gateway: types.StringValue("gateway"),
}, },
model.Model{ Model{
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
Labels: types.MapNull(types.StringType), Labels: types.MapNull(types.StringType),
}, },
&iaasalpha.PartialUpdateNetworkPayload{ &iaas.PartialUpdateNetworkPayload{
Name: utils.Ptr("name"), Name: utils.Ptr("name"),
Ipv4: &iaasalpha.UpdateNetworkIPv4Body{ Ipv4: &iaas.UpdateNetworkIPv4Body{
Gateway: iaasalpha.NewNullableString(utils.Ptr("gateway")), Gateway: iaas.NewNullableString(utils.Ptr("gateway")),
Nameservers: utils.Ptr([]string{ Nameservers: utils.Ptr([]string{
"ns1", "ns1",
"ns2", "ns2",
@ -612,7 +611,7 @@ func TestToUpdatePayload(t *testing.T) {
}, },
{ {
"ipv4_nameservers_okay", "ipv4_nameservers_okay",
&model.Model{ &Model{
Name: types.StringValue("name"), Name: types.StringValue("name"),
Nameservers: types.ListValueMust(types.StringType, []attr.Value{ Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"), types.StringValue("ns1"),
@ -624,15 +623,15 @@ func TestToUpdatePayload(t *testing.T) {
Routed: types.BoolValue(true), Routed: types.BoolValue(true),
IPv4Gateway: types.StringValue("gateway"), IPv4Gateway: types.StringValue("gateway"),
}, },
model.Model{ Model{
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
Labels: types.MapNull(types.StringType), Labels: types.MapNull(types.StringType),
}, },
&iaasalpha.PartialUpdateNetworkPayload{ &iaas.PartialUpdateNetworkPayload{
Name: utils.Ptr("name"), Name: utils.Ptr("name"),
Ipv4: &iaasalpha.UpdateNetworkIPv4Body{ Ipv4: &iaas.UpdateNetworkIPv4Body{
Gateway: iaasalpha.NewNullableString(utils.Ptr("gateway")), Gateway: iaas.NewNullableString(utils.Ptr("gateway")),
Nameservers: utils.Ptr([]string{ Nameservers: utils.Ptr([]string{
"ns1", "ns1",
"ns2", "ns2",
@ -646,7 +645,7 @@ func TestToUpdatePayload(t *testing.T) {
}, },
{ {
"ipv4_gateway_nil", "ipv4_gateway_nil",
&model.Model{ &Model{
Name: types.StringValue("name"), Name: types.StringValue("name"),
IPv4Nameservers: types.ListValueMust(types.StringType, []attr.Value{ IPv4Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"), types.StringValue("ns1"),
@ -657,14 +656,14 @@ func TestToUpdatePayload(t *testing.T) {
}), }),
Routed: types.BoolValue(true), Routed: types.BoolValue(true),
}, },
model.Model{ Model{
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
Labels: types.MapNull(types.StringType), Labels: types.MapNull(types.StringType),
}, },
&iaasalpha.PartialUpdateNetworkPayload{ &iaas.PartialUpdateNetworkPayload{
Name: utils.Ptr("name"), Name: utils.Ptr("name"),
Ipv4: &iaasalpha.UpdateNetworkIPv4Body{ Ipv4: &iaas.UpdateNetworkIPv4Body{
Nameservers: utils.Ptr([]string{ Nameservers: utils.Ptr([]string{
"ns1", "ns1",
"ns2", "ns2",
@ -678,7 +677,7 @@ func TestToUpdatePayload(t *testing.T) {
}, },
{ {
"ipv6_default_ok", "ipv6_default_ok",
&model.Model{ &Model{
Name: types.StringValue("name"), Name: types.StringValue("name"),
IPv6Nameservers: types.ListValueMust(types.StringType, []attr.Value{ IPv6Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"), types.StringValue("ns1"),
@ -690,15 +689,15 @@ func TestToUpdatePayload(t *testing.T) {
Routed: types.BoolValue(true), Routed: types.BoolValue(true),
IPv6Gateway: types.StringValue("gateway"), IPv6Gateway: types.StringValue("gateway"),
}, },
model.Model{ Model{
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
Labels: types.MapNull(types.StringType), Labels: types.MapNull(types.StringType),
}, },
&iaasalpha.PartialUpdateNetworkPayload{ &iaas.PartialUpdateNetworkPayload{
Name: utils.Ptr("name"), Name: utils.Ptr("name"),
Ipv6: &iaasalpha.UpdateNetworkIPv6Body{ Ipv6: &iaas.UpdateNetworkIPv6Body{
Gateway: iaasalpha.NewNullableString(utils.Ptr("gateway")), Gateway: iaas.NewNullableString(utils.Ptr("gateway")),
Nameservers: utils.Ptr([]string{ Nameservers: utils.Ptr([]string{
"ns1", "ns1",
"ns2", "ns2",
@ -712,7 +711,7 @@ func TestToUpdatePayload(t *testing.T) {
}, },
{ {
"ipv6_gateway_nil", "ipv6_gateway_nil",
&model.Model{ &Model{
Name: types.StringValue("name"), Name: types.StringValue("name"),
IPv6Nameservers: types.ListValueMust(types.StringType, []attr.Value{ IPv6Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"), types.StringValue("ns1"),
@ -723,14 +722,14 @@ func TestToUpdatePayload(t *testing.T) {
}), }),
Routed: types.BoolValue(true), Routed: types.BoolValue(true),
}, },
model.Model{ Model{
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
Labels: types.MapNull(types.StringType), Labels: types.MapNull(types.StringType),
}, },
&iaasalpha.PartialUpdateNetworkPayload{ &iaas.PartialUpdateNetworkPayload{
Name: utils.Ptr("name"), Name: utils.Ptr("name"),
Ipv6: &iaasalpha.UpdateNetworkIPv6Body{ Ipv6: &iaas.UpdateNetworkIPv6Body{
Nameservers: utils.Ptr([]string{ Nameservers: utils.Ptr([]string{
"ns1", "ns1",
"ns2", "ns2",
@ -744,7 +743,7 @@ func TestToUpdatePayload(t *testing.T) {
}, },
{ {
"ipv6_nameserver_null", "ipv6_nameserver_null",
&model.Model{ &Model{
Name: types.StringValue("name"), Name: types.StringValue("name"),
IPv6Nameservers: types.ListNull(types.StringType), IPv6Nameservers: types.ListNull(types.StringType),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{ Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
@ -753,16 +752,16 @@ func TestToUpdatePayload(t *testing.T) {
Routed: types.BoolValue(true), Routed: types.BoolValue(true),
IPv6Gateway: types.StringValue("gateway"), IPv6Gateway: types.StringValue("gateway"),
}, },
model.Model{ Model{
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
Labels: types.MapNull(types.StringType), Labels: types.MapNull(types.StringType),
}, },
&iaasalpha.PartialUpdateNetworkPayload{ &iaas.PartialUpdateNetworkPayload{
Name: utils.Ptr("name"), Name: utils.Ptr("name"),
Ipv6: &iaasalpha.UpdateNetworkIPv6Body{ Ipv6: &iaas.UpdateNetworkIPv6Body{
Nameservers: nil, Nameservers: nil,
Gateway: iaasalpha.NewNullableString(utils.Ptr("gateway")), Gateway: iaas.NewNullableString(utils.Ptr("gateway")),
}, },
Labels: &map[string]interface{}{ Labels: &map[string]interface{}{
"key": "value", "key": "value",
@ -772,7 +771,7 @@ func TestToUpdatePayload(t *testing.T) {
}, },
{ {
"ipv6_nameserver_empty_list", "ipv6_nameserver_empty_list",
&model.Model{ &Model{
Name: types.StringValue("name"), Name: types.StringValue("name"),
IPv6Nameservers: types.ListValueMust(types.StringType, []attr.Value{}), IPv6Nameservers: types.ListValueMust(types.StringType, []attr.Value{}),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{ Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
@ -781,16 +780,16 @@ func TestToUpdatePayload(t *testing.T) {
Routed: types.BoolValue(true), Routed: types.BoolValue(true),
IPv6Gateway: types.StringValue("gateway"), IPv6Gateway: types.StringValue("gateway"),
}, },
model.Model{ Model{
ProjectId: types.StringValue("pid"), ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"), NetworkId: types.StringValue("nid"),
Labels: types.MapNull(types.StringType), Labels: types.MapNull(types.StringType),
}, },
&iaasalpha.PartialUpdateNetworkPayload{ &iaas.PartialUpdateNetworkPayload{
Name: utils.Ptr("name"), Name: utils.Ptr("name"),
Ipv6: &iaasalpha.UpdateNetworkIPv6Body{ Ipv6: &iaas.UpdateNetworkIPv6Body{
Nameservers: utils.Ptr([]string{}), Nameservers: utils.Ptr([]string{}),
Gateway: iaasalpha.NewNullableString(utils.Ptr("gateway")), Gateway: iaas.NewNullableString(utils.Ptr("gateway")),
}, },
Labels: &map[string]interface{}{ Labels: &map[string]interface{}{
"key": "value", "key": "value",
@ -809,7 +808,7 @@ func TestToUpdatePayload(t *testing.T) {
t.Fatalf("Should not have failed: %v", err) t.Fatalf("Should not have failed: %v", err)
} }
if tt.isValid { if tt.isValid {
diff := cmp.Diff(output, tt.expected, cmp.AllowUnexported(iaasalpha.NullableString{})) diff := cmp.Diff(output, tt.expected, cmp.AllowUnexported(iaas.NullableString{}))
if diff != "" { if diff != "" {
t.Fatalf("Data does not match: %s", diff) t.Fatalf("Data does not match: %s", diff)
} }

View file

@ -1,53 +0,0 @@
package model
import "github.com/hashicorp/terraform-plugin-framework/types"
type Model struct {
Id types.String `tfsdk:"id"` // needed by TF
ProjectId types.String `tfsdk:"project_id"`
NetworkId types.String `tfsdk:"network_id"`
Name types.String `tfsdk:"name"`
Nameservers types.List `tfsdk:"nameservers"`
IPv4Gateway types.String `tfsdk:"ipv4_gateway"`
IPv4Nameservers types.List `tfsdk:"ipv4_nameservers"`
IPv4Prefix types.String `tfsdk:"ipv4_prefix"`
IPv4PrefixLength types.Int64 `tfsdk:"ipv4_prefix_length"`
Prefixes types.List `tfsdk:"prefixes"`
IPv4Prefixes types.List `tfsdk:"ipv4_prefixes"`
IPv6Gateway types.String `tfsdk:"ipv6_gateway"`
IPv6Nameservers types.List `tfsdk:"ipv6_nameservers"`
IPv6Prefix types.String `tfsdk:"ipv6_prefix"`
IPv6PrefixLength types.Int64 `tfsdk:"ipv6_prefix_length"`
IPv6Prefixes types.List `tfsdk:"ipv6_prefixes"`
PublicIP types.String `tfsdk:"public_ip"`
Labels types.Map `tfsdk:"labels"`
Routed types.Bool `tfsdk:"routed"`
NoIPv4Gateway types.Bool `tfsdk:"no_ipv4_gateway"`
NoIPv6Gateway types.Bool `tfsdk:"no_ipv6_gateway"`
Region types.String `tfsdk:"region"`
RoutingTableID types.String `tfsdk:"routing_table_id"`
}
type DataSourceModel struct {
Id types.String `tfsdk:"id"` // needed by TF
ProjectId types.String `tfsdk:"project_id"`
NetworkId types.String `tfsdk:"network_id"`
Name types.String `tfsdk:"name"`
Nameservers types.List `tfsdk:"nameservers"`
IPv4Gateway types.String `tfsdk:"ipv4_gateway"`
IPv4Nameservers types.List `tfsdk:"ipv4_nameservers"`
IPv4Prefix types.String `tfsdk:"ipv4_prefix"`
IPv4PrefixLength types.Int64 `tfsdk:"ipv4_prefix_length"`
Prefixes types.List `tfsdk:"prefixes"`
IPv4Prefixes types.List `tfsdk:"ipv4_prefixes"`
IPv6Gateway types.String `tfsdk:"ipv6_gateway"`
IPv6Nameservers types.List `tfsdk:"ipv6_nameservers"`
IPv6Prefix types.String `tfsdk:"ipv6_prefix"`
IPv6PrefixLength types.Int64 `tfsdk:"ipv6_prefix_length"`
IPv6Prefixes types.List `tfsdk:"ipv6_prefixes"`
PublicIP types.String `tfsdk:"public_ip"`
Labels types.Map `tfsdk:"labels"`
Routed types.Bool `tfsdk:"routed"`
Region types.String `tfsdk:"region"`
RoutingTableID types.String `tfsdk:"routing_table_id"`
}

View file

@ -1,208 +0,0 @@
package v1network
import (
"context"
"fmt"
"net"
"net/http"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/stackitcloud/stackit-sdk-go/services/iaas"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
networkModel "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaas/network/utils/model"
iaasUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaas/utils"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils"
)
func DatasourceRead(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse, client *iaas.APIClient) { // nolint:gocritic // function signature required by Terraform
var model networkModel.DataSourceModel
diags := req.Config.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
ctx = core.InitProviderContext(ctx)
projectId := model.ProjectId.ValueString()
networkId := model.NetworkId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "network_id", networkId)
networkResp, err := client.GetNetwork(ctx, projectId, networkId).Execute()
if err != nil {
utils.LogError(
ctx,
&resp.Diagnostics,
err,
"Reading network",
fmt.Sprintf("Network with ID %q does not exist in project %q.", networkId, projectId),
map[int]string{
http.StatusForbidden: fmt.Sprintf("Project with ID %q not found or forbidden access", projectId),
},
)
resp.State.RemoveResource(ctx)
return
}
ctx = core.LogResponse(ctx)
err = mapDataSourceFields(ctx, networkResp, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading network", fmt.Sprintf("Processing API payload: %v", err))
return
}
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Network read")
}
func mapDataSourceFields(ctx context.Context, networkResp *iaas.Network, model *networkModel.DataSourceModel) error {
if networkResp == nil {
return fmt.Errorf("response input is nil")
}
if model == nil {
return fmt.Errorf("model input is nil")
}
var networkId string
if model.NetworkId.ValueString() != "" {
networkId = model.NetworkId.ValueString()
} else if networkResp.NetworkId != nil {
networkId = *networkResp.NetworkId
} else {
return fmt.Errorf("network id not present")
}
model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), networkId)
labels, err := iaasUtils.MapLabels(ctx, networkResp.Labels, model.Labels)
if err != nil {
return err
}
// IPv4
if networkResp.Nameservers == nil {
model.Nameservers = types.ListNull(types.StringType)
model.IPv4Nameservers = types.ListNull(types.StringType)
} else {
respNameservers := *networkResp.Nameservers
modelNameservers, err := utils.ListValuetoStringSlice(model.Nameservers)
modelIPv4Nameservers, errIpv4 := utils.ListValuetoStringSlice(model.IPv4Nameservers)
if err != nil {
return fmt.Errorf("get current network nameservers from model: %w", err)
}
if errIpv4 != nil {
return fmt.Errorf("get current IPv4 network nameservers from model: %w", errIpv4)
}
reconciledNameservers := utils.ReconcileStringSlices(modelNameservers, respNameservers)
reconciledIPv4Nameservers := utils.ReconcileStringSlices(modelIPv4Nameservers, respNameservers)
nameserversTF, diags := types.ListValueFrom(ctx, types.StringType, reconciledNameservers)
ipv4NameserversTF, ipv4Diags := types.ListValueFrom(ctx, types.StringType, reconciledIPv4Nameservers)
if diags.HasError() {
return fmt.Errorf("map network nameservers: %w", core.DiagsToError(diags))
}
if ipv4Diags.HasError() {
return fmt.Errorf("map IPv4 network nameservers: %w", core.DiagsToError(ipv4Diags))
}
model.Nameservers = nameserversTF
model.IPv4Nameservers = ipv4NameserversTF
}
if networkResp.Prefixes == nil {
model.Prefixes = types.ListNull(types.StringType)
model.IPv4Prefixes = types.ListNull(types.StringType)
} else {
respPrefixes := *networkResp.Prefixes
prefixesTF, diags := types.ListValueFrom(ctx, types.StringType, respPrefixes)
if diags.HasError() {
return fmt.Errorf("map network prefixes: %w", core.DiagsToError(diags))
}
if len(respPrefixes) > 0 {
model.IPv4Prefix = types.StringValue(respPrefixes[0])
_, netmask, err := net.ParseCIDR(respPrefixes[0])
if err != nil {
// silently ignore parsing error for the netmask
model.IPv4PrefixLength = types.Int64Null()
} else {
ones, _ := netmask.Mask.Size()
model.IPv4PrefixLength = types.Int64Value(int64(ones))
}
}
model.Prefixes = prefixesTF
model.IPv4Prefixes = prefixesTF
}
model.IPv4Gateway = types.StringNull()
if networkResp.Gateway != nil {
model.IPv4Gateway = types.StringPointerValue(networkResp.GetGateway())
}
// IPv6
if networkResp.NameserversV6 == nil {
model.IPv6Nameservers = types.ListNull(types.StringType)
} else {
respIPv6Nameservers := *networkResp.NameserversV6
modelIPv6Nameservers, errIpv6 := utils.ListValuetoStringSlice(model.IPv6Nameservers)
if errIpv6 != nil {
return fmt.Errorf("get current IPv6 network nameservers from model: %w", errIpv6)
}
reconciledIPv6Nameservers := utils.ReconcileStringSlices(modelIPv6Nameservers, respIPv6Nameservers)
ipv6NameserversTF, ipv6Diags := types.ListValueFrom(ctx, types.StringType, reconciledIPv6Nameservers)
if ipv6Diags.HasError() {
return fmt.Errorf("map IPv6 network nameservers: %w", core.DiagsToError(ipv6Diags))
}
model.IPv6Nameservers = ipv6NameserversTF
}
if networkResp.PrefixesV6 == nil {
model.IPv6Prefixes = types.ListNull(types.StringType)
} else {
respPrefixesV6 := *networkResp.PrefixesV6
prefixesV6TF, diags := types.ListValueFrom(ctx, types.StringType, respPrefixesV6)
if diags.HasError() {
return fmt.Errorf("map network IPv6 prefixes: %w", core.DiagsToError(diags))
}
if len(respPrefixesV6) > 0 {
model.IPv6Prefix = types.StringValue(respPrefixesV6[0])
_, netmask, err := net.ParseCIDR(respPrefixesV6[0])
if err != nil {
// silently ignore parsing error for the netmask
model.IPv6PrefixLength = types.Int64Null()
} else {
ones, _ := netmask.Mask.Size()
model.IPv6PrefixLength = types.Int64Value(int64(ones))
}
}
model.IPv6Prefixes = prefixesV6TF
}
model.IPv6Gateway = types.StringNull()
if networkResp.Gatewayv6 != nil {
model.IPv6Gateway = types.StringPointerValue(networkResp.GetGatewayv6())
}
model.NetworkId = types.StringValue(networkId)
model.Name = types.StringPointerValue(networkResp.Name)
model.PublicIP = types.StringPointerValue(networkResp.PublicIp)
model.Labels = labels
model.Routed = types.BoolPointerValue(networkResp.Routed)
model.RoutingTableID = types.StringNull()
model.Region = types.StringNull()
return nil
}

View file

@ -1,352 +0,0 @@
package v1network
import (
"context"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/stackitcloud/stackit-sdk-go/core/utils"
"github.com/stackitcloud/stackit-sdk-go/services/iaas"
networkModel "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaas/network/utils/model"
)
func TestMapDataSourceFields(t *testing.T) {
tests := []struct {
description string
state networkModel.DataSourceModel
input *iaas.Network
expected networkModel.DataSourceModel
isValid bool
}{
{
"id_ok",
networkModel.DataSourceModel{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
},
&iaas.Network{
NetworkId: utils.Ptr("nid"),
Gateway: iaas.NewNullableString(nil),
},
networkModel.DataSourceModel{
Id: types.StringValue("pid,nid"),
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
Name: types.StringNull(),
Nameservers: types.ListNull(types.StringType),
IPv4Nameservers: types.ListNull(types.StringType),
IPv4PrefixLength: types.Int64Null(),
IPv4Gateway: types.StringNull(),
IPv4Prefix: types.StringNull(),
Prefixes: types.ListNull(types.StringType),
IPv4Prefixes: types.ListNull(types.StringType),
IPv6Nameservers: types.ListNull(types.StringType),
IPv6PrefixLength: types.Int64Null(),
IPv6Gateway: types.StringNull(),
IPv6Prefix: types.StringNull(),
IPv6Prefixes: types.ListNull(types.StringType),
PublicIP: types.StringNull(),
Labels: types.MapNull(types.StringType),
Routed: types.BoolNull(),
},
true,
},
{
"values_ok",
networkModel.DataSourceModel{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
},
&iaas.Network{
NetworkId: utils.Ptr("nid"),
Name: utils.Ptr("name"),
Nameservers: &[]string{
"ns1",
"ns2",
},
Prefixes: &[]string{
"192.168.42.0/24",
"10.100.10.0/16",
},
NameserversV6: &[]string{
"ns1",
"ns2",
},
PrefixesV6: &[]string{
"fd12:3456:789a:1::/64",
"fd12:3456:789a:2::/64",
},
PublicIp: utils.Ptr("publicIp"),
Labels: &map[string]interface{}{
"key": "value",
},
Routed: utils.Ptr(true),
Gateway: iaas.NewNullableString(utils.Ptr("gateway")),
Gatewayv6: iaas.NewNullableString(utils.Ptr("gateway")),
},
networkModel.DataSourceModel{
Id: types.StringValue("pid,nid"),
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
Name: types.StringValue("name"),
Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"),
types.StringValue("ns2"),
}),
IPv4Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"),
types.StringValue("ns2"),
}),
IPv4PrefixLength: types.Int64Value(24),
Prefixes: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("192.168.42.0/24"),
types.StringValue("10.100.10.0/16"),
}),
IPv4Prefix: types.StringValue("192.168.42.0/24"),
IPv4Prefixes: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("192.168.42.0/24"),
types.StringValue("10.100.10.0/16"),
}),
IPv6Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"),
types.StringValue("ns2"),
}),
IPv6PrefixLength: types.Int64Value(64),
IPv6Prefix: types.StringValue("fd12:3456:789a:1::/64"),
IPv6Prefixes: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("fd12:3456:789a:1::/64"),
types.StringValue("fd12:3456:789a:2::/64"),
}),
PublicIP: types.StringValue("publicIp"),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
"key": types.StringValue("value"),
}),
Routed: types.BoolValue(true),
IPv4Gateway: types.StringValue("gateway"),
IPv6Gateway: types.StringValue("gateway"),
},
true,
},
{
"ipv4_nameservers_changed_outside_tf",
networkModel.DataSourceModel{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"),
types.StringValue("ns2"),
}),
IPv4Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"),
types.StringValue("ns2"),
}),
},
&iaas.Network{
NetworkId: utils.Ptr("nid"),
Nameservers: &[]string{
"ns2",
"ns3",
},
},
networkModel.DataSourceModel{
Id: types.StringValue("pid,nid"),
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
Name: types.StringNull(),
IPv6Prefixes: types.ListNull(types.StringType),
IPv6Nameservers: types.ListNull(types.StringType),
Prefixes: types.ListNull(types.StringType),
IPv4Prefixes: types.ListNull(types.StringType),
Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns2"),
types.StringValue("ns3"),
}),
IPv4Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns2"),
types.StringValue("ns3"),
}),
Labels: types.MapNull(types.StringType),
},
true,
},
{
"ipv6_nameservers_changed_outside_tf",
networkModel.DataSourceModel{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
IPv6Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"),
types.StringValue("ns2"),
}),
},
&iaas.Network{
NetworkId: utils.Ptr("nid"),
NameserversV6: &[]string{
"ns2",
"ns3",
},
},
networkModel.DataSourceModel{
Id: types.StringValue("pid,nid"),
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
Name: types.StringNull(),
IPv6Prefixes: types.ListNull(types.StringType),
IPv4Nameservers: types.ListNull(types.StringType),
Prefixes: types.ListNull(types.StringType),
IPv4Prefixes: types.ListNull(types.StringType),
Nameservers: types.ListNull(types.StringType),
IPv6Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns2"),
types.StringValue("ns3"),
}),
Labels: types.MapNull(types.StringType),
},
true,
},
{
"ipv4_prefixes_changed_outside_tf",
networkModel.DataSourceModel{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
Prefixes: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("192.168.42.0/24"),
types.StringValue("10.100.10.0/16"),
}),
},
&iaas.Network{
NetworkId: utils.Ptr("nid"),
Prefixes: &[]string{
"10.100.20.0/16",
"10.100.10.0/16",
},
},
networkModel.DataSourceModel{
Id: types.StringValue("pid,nid"),
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
Name: types.StringNull(),
IPv6Nameservers: types.ListNull(types.StringType),
IPv6PrefixLength: types.Int64Null(),
IPv6Prefixes: types.ListNull(types.StringType),
Labels: types.MapNull(types.StringType),
Nameservers: types.ListNull(types.StringType),
IPv4Nameservers: types.ListNull(types.StringType),
IPv4PrefixLength: types.Int64Value(16),
IPv4Prefix: types.StringValue("10.100.20.0/16"),
Prefixes: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("10.100.20.0/16"),
types.StringValue("10.100.10.0/16"),
}),
IPv4Prefixes: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("10.100.20.0/16"),
types.StringValue("10.100.10.0/16"),
}),
},
true,
},
{
"ipv6_prefixes_changed_outside_tf",
networkModel.DataSourceModel{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
IPv6Prefixes: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("fd12:3456:789a:1::/64"),
types.StringValue("fd12:3456:789a:2::/64"),
}),
},
&iaas.Network{
NetworkId: utils.Ptr("nid"),
PrefixesV6: &[]string{
"fd12:3456:789a:3::/64",
"fd12:3456:789a:4::/64",
},
},
networkModel.DataSourceModel{
Id: types.StringValue("pid,nid"),
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
Name: types.StringNull(),
IPv4Nameservers: types.ListNull(types.StringType),
IPv4PrefixLength: types.Int64Null(),
Prefixes: types.ListNull(types.StringType),
IPv4Prefixes: types.ListNull(types.StringType),
Labels: types.MapNull(types.StringType),
Nameservers: types.ListNull(types.StringType),
IPv6Nameservers: types.ListNull(types.StringType),
IPv6PrefixLength: types.Int64Value(64),
IPv6Prefix: types.StringValue("fd12:3456:789a:3::/64"),
IPv6Prefixes: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("fd12:3456:789a:3::/64"),
types.StringValue("fd12:3456:789a:4::/64"),
}),
},
true,
},
{
"ipv4_ipv6_gateway_nil",
networkModel.DataSourceModel{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
},
&iaas.Network{
NetworkId: utils.Ptr("nid"),
},
networkModel.DataSourceModel{
Id: types.StringValue("pid,nid"),
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
Name: types.StringNull(),
Nameservers: types.ListNull(types.StringType),
IPv4Nameservers: types.ListNull(types.StringType),
IPv4PrefixLength: types.Int64Null(),
IPv4Gateway: types.StringNull(),
Prefixes: types.ListNull(types.StringType),
IPv4Prefixes: types.ListNull(types.StringType),
IPv6Nameservers: types.ListNull(types.StringType),
IPv6PrefixLength: types.Int64Null(),
IPv6Gateway: types.StringNull(),
IPv6Prefixes: types.ListNull(types.StringType),
PublicIP: types.StringNull(),
Labels: types.MapNull(types.StringType),
Routed: types.BoolNull(),
},
true,
},
{
"response_nil_fail",
networkModel.DataSourceModel{},
nil,
networkModel.DataSourceModel{},
false,
},
{
"no_resource_id",
networkModel.DataSourceModel{
ProjectId: types.StringValue("pid"),
},
&iaas.Network{},
networkModel.DataSourceModel{},
false,
},
}
for _, tt := range tests {
t.Run(tt.description, func(t *testing.T) {
err := mapDataSourceFields(context.Background(), tt.input, &tt.state)
if !tt.isValid && err == nil {
t.Fatalf("Should have failed")
}
if tt.isValid && err != nil {
t.Fatalf("Should not have failed: %v", err)
}
if tt.isValid {
diff := cmp.Diff(tt.state, tt.expected)
if diff != "" {
t.Fatalf("Data does not match: %s", diff)
}
}
})
}
}

View file

@ -1,558 +0,0 @@
package v1network
import (
"context"
"fmt"
"net"
"net/http"
"strings"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/stackitcloud/stackit-sdk-go/core/oapierror"
"github.com/stackitcloud/stackit-sdk-go/services/iaas"
"github.com/stackitcloud/stackit-sdk-go/services/iaas/wait"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
networkModel "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaas/network/utils/model"
iaasUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaas/utils"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils"
)
func Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse, client *iaas.APIClient) { // nolint:gocritic // function signature required by Terraform
// Retrieve values from plan
var model networkModel.Model
diags := req.Plan.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
projectId := model.ProjectId.ValueString()
ctx = core.InitProviderContext(ctx)
ctx = tflog.SetField(ctx, "project_id", projectId)
// Generate API request body from model
payload, err := toCreatePayload(ctx, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating network", fmt.Sprintf("Creating API payload: %v", err))
return
}
// Create new network
network, err := client.CreateNetwork(ctx, projectId).CreateNetworkPayload(*payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating network", fmt.Sprintf("Calling API: %v", err))
return
}
ctx = core.LogResponse(ctx)
networkId := *network.NetworkId
network, err = wait.CreateNetworkWaitHandler(ctx, client, projectId, networkId).WaitWithContext(ctx)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating network", fmt.Sprintf("Network creation waiting: %v", err))
return
}
ctx = tflog.SetField(ctx, "network_id", networkId)
// Map response body to schema
err = mapFields(ctx, network, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating network", fmt.Sprintf("Processing API payload: %v", err))
return
}
// Set state to fully populated data
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Network created")
}
func Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse, client *iaas.APIClient) { // nolint:gocritic // function signature required by Terraform
var model networkModel.Model
diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
projectId := model.ProjectId.ValueString()
networkId := model.NetworkId.ValueString()
ctx = core.InitProviderContext(ctx)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "network_id", networkId)
networkResp, err := client.GetNetwork(ctx, projectId, networkId).Execute()
if err != nil {
oapiErr, ok := err.(*oapierror.GenericOpenAPIError) //nolint:errorlint //complaining that error.As should be used to catch wrapped errors, but this error should not be wrapped
if ok && oapiErr.StatusCode == http.StatusNotFound {
resp.State.RemoveResource(ctx)
return
}
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading network", fmt.Sprintf("Calling API: %v", err))
return
}
ctx = core.LogResponse(ctx)
// Map response body to schema
err = mapFields(ctx, networkResp, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading network", fmt.Sprintf("Processing API payload: %v", err))
return
}
// Set refreshed state
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Network read")
}
func Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse, client *iaas.APIClient) { // nolint:gocritic // function signature required by Terraform
// Retrieve values from plan
var model networkModel.Model
diags := req.Plan.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
projectId := model.ProjectId.ValueString()
networkId := model.NetworkId.ValueString()
ctx = core.InitProviderContext(ctx)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "network_id", networkId)
// Retrieve values from state
var stateModel networkModel.Model
diags = req.State.Get(ctx, &stateModel)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// Generate API request body from model
payload, err := toUpdatePayload(ctx, &model, &stateModel)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating network", fmt.Sprintf("Creating API payload: %v", err))
return
}
// Update existing network
err = client.PartialUpdateNetwork(ctx, projectId, networkId).PartialUpdateNetworkPayload(*payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating network", fmt.Sprintf("Calling API: %v", err))
return
}
ctx = core.LogResponse(ctx)
waitResp, err := wait.UpdateNetworkWaitHandler(ctx, client, projectId, networkId).WaitWithContext(ctx)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating network", fmt.Sprintf("Network update waiting: %v", err))
return
}
err = mapFields(ctx, waitResp, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating network", fmt.Sprintf("Processing API payload: %v", err))
return
}
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Network updated")
}
func Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse, client *iaas.APIClient) { // nolint:gocritic // function signature required by Terraform
// Retrieve values from state
var model networkModel.Model
diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
projectId := model.ProjectId.ValueString()
networkId := model.NetworkId.ValueString()
ctx = core.InitProviderContext(ctx)
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "network_id", networkId)
// Delete existing network
err := client.DeleteNetwork(ctx, projectId, networkId).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting network", fmt.Sprintf("Calling API: %v", err))
return
}
ctx = core.LogResponse(ctx)
_, err = wait.DeleteNetworkWaitHandler(ctx, client, projectId, networkId).WaitWithContext(ctx)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting network", fmt.Sprintf("Network deletion waiting: %v", err))
return
}
tflog.Info(ctx, "Network deleted")
}
// ImportState imports a resource into the Terraform state on success.
// The expected format of the resource import identifier is: project_id,network_id
func ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" {
core.LogAndAddError(ctx, &resp.Diagnostics,
"Error importing network",
fmt.Sprintf("Expected import identifier with format: [project_id],[network_id] Got: %q", req.ID),
)
return
}
projectId := idParts[0]
networkId := idParts[1]
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "network_id", networkId)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), projectId)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("network_id"), networkId)...)
tflog.Info(ctx, "Network state imported")
}
func mapFields(ctx context.Context, networkResp *iaas.Network, model *networkModel.Model) error {
if networkResp == nil {
return fmt.Errorf("response input is nil")
}
if model == nil {
return fmt.Errorf("model input is nil")
}
var networkId string
if model.NetworkId.ValueString() != "" {
networkId = model.NetworkId.ValueString()
} else if networkResp.NetworkId != nil {
networkId = *networkResp.NetworkId
} else {
return fmt.Errorf("network id not present")
}
model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), networkId)
labels, err := iaasUtils.MapLabels(ctx, networkResp.Labels, model.Labels)
if err != nil {
return err
}
// IPv4
if networkResp.Nameservers == nil {
model.Nameservers = types.ListNull(types.StringType)
model.IPv4Nameservers = types.ListNull(types.StringType)
} else {
respNameservers := *networkResp.Nameservers
modelNameservers, err := utils.ListValuetoStringSlice(model.Nameservers)
modelIPv4Nameservers, errIpv4 := utils.ListValuetoStringSlice(model.IPv4Nameservers)
if err != nil {
return fmt.Errorf("get current network nameservers from model: %w", err)
}
if errIpv4 != nil {
return fmt.Errorf("get current IPv4 network nameservers from model: %w", errIpv4)
}
reconciledNameservers := utils.ReconcileStringSlices(modelNameservers, respNameservers)
reconciledIPv4Nameservers := utils.ReconcileStringSlices(modelIPv4Nameservers, respNameservers)
nameserversTF, diags := types.ListValueFrom(ctx, types.StringType, reconciledNameservers)
ipv4NameserversTF, ipv4Diags := types.ListValueFrom(ctx, types.StringType, reconciledIPv4Nameservers)
if diags.HasError() {
return fmt.Errorf("map network nameservers: %w", core.DiagsToError(diags))
}
if ipv4Diags.HasError() {
return fmt.Errorf("map IPv4 network nameservers: %w", core.DiagsToError(ipv4Diags))
}
model.Nameservers = nameserversTF
model.IPv4Nameservers = ipv4NameserversTF
}
if networkResp.Prefixes == nil {
model.Prefixes = types.ListNull(types.StringType)
model.IPv4Prefixes = types.ListNull(types.StringType)
} else {
respPrefixes := *networkResp.Prefixes
prefixesTF, diags := types.ListValueFrom(ctx, types.StringType, respPrefixes)
if diags.HasError() {
return fmt.Errorf("map network prefixes: %w", core.DiagsToError(diags))
}
if len(respPrefixes) > 0 {
model.IPv4Prefix = types.StringValue(respPrefixes[0])
_, netmask, err := net.ParseCIDR(respPrefixes[0])
if err != nil {
// silently ignore parsing error for the netmask
model.IPv4PrefixLength = types.Int64Null()
} else {
ones, _ := netmask.Mask.Size()
model.IPv4PrefixLength = types.Int64Value(int64(ones))
}
}
model.Prefixes = prefixesTF
model.IPv4Prefixes = prefixesTF
}
if networkResp.Gateway != nil {
model.IPv4Gateway = types.StringPointerValue(networkResp.GetGateway())
} else {
model.IPv4Gateway = types.StringNull()
}
// IPv6
if networkResp.NameserversV6 == nil {
model.IPv6Nameservers = types.ListNull(types.StringType)
} else {
respIPv6Nameservers := *networkResp.NameserversV6
modelIPv6Nameservers, errIpv6 := utils.ListValuetoStringSlice(model.IPv6Nameservers)
if errIpv6 != nil {
return fmt.Errorf("get current IPv6 network nameservers from model: %w", errIpv6)
}
reconciledIPv6Nameservers := utils.ReconcileStringSlices(modelIPv6Nameservers, respIPv6Nameservers)
ipv6NameserversTF, ipv6Diags := types.ListValueFrom(ctx, types.StringType, reconciledIPv6Nameservers)
if ipv6Diags.HasError() {
return fmt.Errorf("map IPv6 network nameservers: %w", core.DiagsToError(ipv6Diags))
}
model.IPv6Nameservers = ipv6NameserversTF
}
if networkResp.PrefixesV6 == nil || len(*networkResp.PrefixesV6) == 0 {
model.IPv6Prefixes = types.ListNull(types.StringType)
model.IPv6Prefix = types.StringNull()
model.IPv6PrefixLength = types.Int64Null()
} else {
respPrefixesV6 := *networkResp.PrefixesV6
prefixesV6TF, diags := types.ListValueFrom(ctx, types.StringType, respPrefixesV6)
if diags.HasError() {
return fmt.Errorf("map network IPv6 prefixes: %w", core.DiagsToError(diags))
}
if len(respPrefixesV6) > 0 {
model.IPv6Prefix = types.StringValue(respPrefixesV6[0])
_, netmask, err := net.ParseCIDR(respPrefixesV6[0])
if err != nil {
// silently ignore parsing error for the netmask
model.IPv6PrefixLength = types.Int64Null()
} else {
ones, _ := netmask.Mask.Size()
model.IPv6PrefixLength = types.Int64Value(int64(ones))
}
}
model.IPv6Prefixes = prefixesV6TF
}
if networkResp.Gatewayv6 != nil {
model.IPv6Gateway = types.StringPointerValue(networkResp.GetGatewayv6())
} else {
model.IPv6Gateway = types.StringNull()
}
model.NetworkId = types.StringValue(networkId)
model.Name = types.StringPointerValue(networkResp.Name)
model.PublicIP = types.StringPointerValue(networkResp.PublicIp)
model.Labels = labels
model.Routed = types.BoolPointerValue(networkResp.Routed)
model.Region = types.StringNull()
model.RoutingTableID = types.StringNull()
return nil
}
func toCreatePayload(ctx context.Context, model *networkModel.Model) (*iaas.CreateNetworkPayload, error) {
if model == nil {
return nil, fmt.Errorf("nil model")
}
addressFamily := &iaas.CreateNetworkAddressFamily{}
var modelIPv6Nameservers []string
// Is true when IPv6Nameservers is not null or unset
if !utils.IsUndefined(model.IPv6Nameservers) {
// If ipv6Nameservers is empty, modelIPv6Nameservers will be set to an empty slice.
// empty slice != nil slice. Empty slice will result in an empty list in the payload []. Nil slice will result in a payload without the property set
modelIPv6Nameservers = []string{}
for _, ipv6ns := range model.IPv6Nameservers.Elements() {
ipv6NameserverString, ok := ipv6ns.(types.String)
if !ok {
return nil, fmt.Errorf("type assertion failed")
}
modelIPv6Nameservers = append(modelIPv6Nameservers, ipv6NameserverString.ValueString())
}
}
if !utils.IsUndefined(model.IPv6Prefix) || !utils.IsUndefined(model.IPv6PrefixLength) || (modelIPv6Nameservers != nil) {
addressFamily.Ipv6 = &iaas.CreateNetworkIPv6Body{
Prefix: conversion.StringValueToPointer(model.IPv6Prefix),
PrefixLength: conversion.Int64ValueToPointer(model.IPv6PrefixLength),
}
// IPv6 nameservers should only be set, if it contains any value. If the slice is nil, it should NOT be set.
// Setting it to a nil slice would result in a payload, where nameservers is set to null in the json payload,
// but it should actually be unset. Setting it to "null" will result in an error, because it's NOT nullable.
if modelIPv6Nameservers != nil {
addressFamily.Ipv6.Nameservers = &modelIPv6Nameservers
}
if model.NoIPv6Gateway.ValueBool() {
addressFamily.Ipv6.Gateway = iaas.NewNullableString(nil)
} else if !(model.IPv6Gateway.IsUnknown() || model.IPv6Gateway.IsNull()) {
addressFamily.Ipv6.Gateway = iaas.NewNullableString(conversion.StringValueToPointer(model.IPv6Gateway))
}
}
modelIPv4Nameservers := []string{}
var modelIPv4List []attr.Value
if !(model.IPv4Nameservers.IsNull() || model.IPv4Nameservers.IsUnknown()) {
modelIPv4List = model.IPv4Nameservers.Elements()
} else {
modelIPv4List = model.Nameservers.Elements()
}
for _, ipv4ns := range modelIPv4List {
ipv4NameserverString, ok := ipv4ns.(types.String)
if !ok {
return nil, fmt.Errorf("type assertion failed")
}
modelIPv4Nameservers = append(modelIPv4Nameservers, ipv4NameserverString.ValueString())
}
if !model.IPv4Prefix.IsNull() || !model.IPv4PrefixLength.IsNull() || !model.IPv4Nameservers.IsNull() || !model.Nameservers.IsNull() {
addressFamily.Ipv4 = &iaas.CreateNetworkIPv4Body{
Nameservers: &modelIPv4Nameservers,
Prefix: conversion.StringValueToPointer(model.IPv4Prefix),
PrefixLength: conversion.Int64ValueToPointer(model.IPv4PrefixLength),
}
if model.NoIPv4Gateway.ValueBool() {
addressFamily.Ipv4.Gateway = iaas.NewNullableString(nil)
} else if !(model.IPv4Gateway.IsUnknown() || model.IPv4Gateway.IsNull()) {
addressFamily.Ipv4.Gateway = iaas.NewNullableString(conversion.StringValueToPointer(model.IPv4Gateway))
}
}
labels, err := conversion.ToStringInterfaceMap(ctx, model.Labels)
if err != nil {
return nil, fmt.Errorf("converting to Go map: %w", err)
}
payload := iaas.CreateNetworkPayload{
Name: conversion.StringValueToPointer(model.Name),
Labels: &labels,
Routed: conversion.BoolValueToPointer(model.Routed),
}
if addressFamily.Ipv6 != nil || addressFamily.Ipv4 != nil {
payload.AddressFamily = addressFamily
}
return &payload, nil
}
func toUpdatePayload(ctx context.Context, model, stateModel *networkModel.Model) (*iaas.PartialUpdateNetworkPayload, error) {
if model == nil {
return nil, fmt.Errorf("nil model")
}
addressFamily := &iaas.UpdateNetworkAddressFamily{}
var modelIPv6Nameservers []string
// Is true when IPv6Nameservers is not null or unset
if !utils.IsUndefined(model.IPv6Nameservers) {
// If ipv6Nameservers is empty, modelIPv6Nameservers will be set to an empty slice.
// empty slice != nil slice. Empty slice will result in an empty list in the payload []. Nil slice will result in a payload without the property set
modelIPv6Nameservers = []string{}
for _, ipv6ns := range model.IPv6Nameservers.Elements() {
ipv6NameserverString, ok := ipv6ns.(types.String)
if !ok {
return nil, fmt.Errorf("type assertion failed")
}
modelIPv6Nameservers = append(modelIPv6Nameservers, ipv6NameserverString.ValueString())
}
}
if !utils.IsUndefined(model.NoIPv6Gateway) || !utils.IsUndefined(model.IPv6Gateway) || modelIPv6Nameservers != nil {
addressFamily.Ipv6 = &iaas.UpdateNetworkIPv6Body{}
// IPv6 nameservers should only be set, if it contains any value. If the slice is nil, it should NOT be set.
// Setting it to a nil slice would result in a payload, where nameservers is set to null in the json payload,
// but it should actually be unset. Setting it to "null" will result in an error, because it's NOT nullable.
if modelIPv6Nameservers != nil {
addressFamily.Ipv6.Nameservers = &modelIPv6Nameservers
}
if model.NoIPv6Gateway.ValueBool() {
addressFamily.Ipv6.Gateway = iaas.NewNullableString(nil)
} else if !utils.IsUndefined(model.IPv6Gateway) {
addressFamily.Ipv6.Gateway = iaas.NewNullableString(conversion.StringValueToPointer(model.IPv6Gateway))
}
}
modelIPv4Nameservers := []string{}
var modelIPv4List []attr.Value
if !(model.IPv4Nameservers.IsNull() || model.IPv4Nameservers.IsUnknown()) {
modelIPv4List = model.IPv4Nameservers.Elements()
} else {
modelIPv4List = model.Nameservers.Elements()
}
for _, ipv4ns := range modelIPv4List {
ipv4NameserverString, ok := ipv4ns.(types.String)
if !ok {
return nil, fmt.Errorf("type assertion failed")
}
modelIPv4Nameservers = append(modelIPv4Nameservers, ipv4NameserverString.ValueString())
}
if !model.IPv4Nameservers.IsNull() || !model.Nameservers.IsNull() {
addressFamily.Ipv4 = &iaas.UpdateNetworkIPv4Body{
Nameservers: &modelIPv4Nameservers,
}
if model.NoIPv4Gateway.ValueBool() {
addressFamily.Ipv4.Gateway = iaas.NewNullableString(nil)
} else if !(model.IPv4Gateway.IsUnknown() || model.IPv4Gateway.IsNull()) {
addressFamily.Ipv4.Gateway = iaas.NewNullableString(conversion.StringValueToPointer(model.IPv4Gateway))
}
}
currentLabels := stateModel.Labels
labels, err := conversion.ToJSONMapPartialUpdatePayload(ctx, currentLabels, model.Labels)
if err != nil {
return nil, fmt.Errorf("converting to Go map: %w", err)
}
payload := iaas.PartialUpdateNetworkPayload{
Name: conversion.StringValueToPointer(model.Name),
Labels: &labels,
}
if addressFamily.Ipv6 != nil || addressFamily.Ipv4 != nil {
payload.AddressFamily = addressFamily
}
return &payload, nil
}

View file

@ -1,811 +0,0 @@
package v1network
import (
"context"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/stackitcloud/stackit-sdk-go/core/utils"
"github.com/stackitcloud/stackit-sdk-go/services/iaas"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/iaas/network/utils/model"
)
func TestMapFields(t *testing.T) {
tests := []struct {
description string
state model.Model
input *iaas.Network
expected model.Model
isValid bool
}{
{
"id_ok",
model.Model{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
},
&iaas.Network{
NetworkId: utils.Ptr("nid"),
Gateway: iaas.NewNullableString(nil),
},
model.Model{
Id: types.StringValue("pid,nid"),
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
Name: types.StringNull(),
Nameservers: types.ListNull(types.StringType),
IPv4Nameservers: types.ListNull(types.StringType),
IPv4PrefixLength: types.Int64Null(),
IPv4Gateway: types.StringNull(),
IPv4Prefix: types.StringNull(),
Prefixes: types.ListNull(types.StringType),
IPv4Prefixes: types.ListNull(types.StringType),
IPv6Nameservers: types.ListNull(types.StringType),
IPv6PrefixLength: types.Int64Null(),
IPv6Gateway: types.StringNull(),
IPv6Prefix: types.StringNull(),
IPv6Prefixes: types.ListNull(types.StringType),
PublicIP: types.StringNull(),
Labels: types.MapNull(types.StringType),
Routed: types.BoolNull(),
},
true,
},
{
"values_ok",
model.Model{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
},
&iaas.Network{
NetworkId: utils.Ptr("nid"),
Name: utils.Ptr("name"),
Nameservers: &[]string{
"ns1",
"ns2",
},
Prefixes: &[]string{
"192.168.42.0/24",
"10.100.10.0/16",
},
NameserversV6: &[]string{
"ns1",
"ns2",
},
PrefixesV6: &[]string{
"fd12:3456:789a:1::/64",
"fd12:3456:789b:1::/64",
},
PublicIp: utils.Ptr("publicIp"),
Labels: &map[string]interface{}{
"key": "value",
},
Routed: utils.Ptr(true),
Gateway: iaas.NewNullableString(utils.Ptr("gateway")),
Gatewayv6: iaas.NewNullableString(utils.Ptr("gateway")),
},
model.Model{
Id: types.StringValue("pid,nid"),
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
Name: types.StringValue("name"),
Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"),
types.StringValue("ns2"),
}),
IPv4Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"),
types.StringValue("ns2"),
}),
IPv4PrefixLength: types.Int64Value(24),
Prefixes: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("192.168.42.0/24"),
types.StringValue("10.100.10.0/16"),
}),
IPv4Prefixes: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("192.168.42.0/24"),
types.StringValue("10.100.10.0/16"),
}),
IPv4Prefix: types.StringValue("192.168.42.0/24"),
IPv6Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"),
types.StringValue("ns2"),
}),
IPv6PrefixLength: types.Int64Value(64),
IPv6Prefixes: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("fd12:3456:789a:1::/64"),
types.StringValue("fd12:3456:789b:1::/64"),
}),
IPv6Prefix: types.StringValue("fd12:3456:789a:1::/64"),
PublicIP: types.StringValue("publicIp"),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
"key": types.StringValue("value"),
}),
Routed: types.BoolValue(true),
IPv4Gateway: types.StringValue("gateway"),
IPv6Gateway: types.StringValue("gateway"),
},
true,
},
{
"ipv4_nameservers_changed_outside_tf",
model.Model{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"),
types.StringValue("ns2"),
}),
IPv4Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"),
types.StringValue("ns2"),
}),
},
&iaas.Network{
NetworkId: utils.Ptr("nid"),
Nameservers: &[]string{
"ns2",
"ns3",
},
},
model.Model{
Id: types.StringValue("pid,nid"),
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
Name: types.StringNull(),
IPv6Prefixes: types.ListNull(types.StringType),
IPv6Nameservers: types.ListNull(types.StringType),
Prefixes: types.ListNull(types.StringType),
IPv4Prefixes: types.ListNull(types.StringType),
Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns2"),
types.StringValue("ns3"),
}),
IPv4Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns2"),
types.StringValue("ns3"),
}),
Labels: types.MapNull(types.StringType),
},
true,
},
{
"ipv6_nameservers_changed_outside_tf",
model.Model{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
IPv6Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"),
types.StringValue("ns2"),
}),
},
&iaas.Network{
NetworkId: utils.Ptr("nid"),
NameserversV6: &[]string{
"ns2",
"ns3",
},
},
model.Model{
Id: types.StringValue("pid,nid"),
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
Name: types.StringNull(),
IPv6Prefixes: types.ListNull(types.StringType),
IPv4Nameservers: types.ListNull(types.StringType),
Prefixes: types.ListNull(types.StringType),
IPv4Prefixes: types.ListNull(types.StringType),
Nameservers: types.ListNull(types.StringType),
IPv6Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns2"),
types.StringValue("ns3"),
}),
Labels: types.MapNull(types.StringType),
},
true,
},
{
"ipv4_prefixes_changed_outside_tf",
model.Model{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
Prefixes: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("192.168.42.0/24"),
types.StringValue("10.100.10.0/24"),
}),
},
&iaas.Network{
NetworkId: utils.Ptr("nid"),
Prefixes: &[]string{
"192.168.54.0/24",
"192.168.55.0/24",
},
},
model.Model{
Id: types.StringValue("pid,nid"),
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
Name: types.StringNull(),
IPv6Nameservers: types.ListNull(types.StringType),
IPv6PrefixLength: types.Int64Null(),
IPv6Prefixes: types.ListNull(types.StringType),
Labels: types.MapNull(types.StringType),
Nameservers: types.ListNull(types.StringType),
IPv4Nameservers: types.ListNull(types.StringType),
IPv4PrefixLength: types.Int64Value(24),
IPv4Prefix: types.StringValue("192.168.54.0/24"),
Prefixes: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("192.168.54.0/24"),
types.StringValue("192.168.55.0/24"),
}),
IPv4Prefixes: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("192.168.54.0/24"),
types.StringValue("192.168.55.0/24"),
}),
},
true,
},
{
"ipv6_prefixes_changed_outside_tf",
model.Model{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
IPv6Prefixes: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("fd12:3456:789a:1::/64"),
types.StringValue("fd12:3456:789a:2::/64"),
}),
},
&iaas.Network{
NetworkId: utils.Ptr("nid"),
PrefixesV6: &[]string{
"fd12:3456:789a:1::/64",
"fd12:3456:789a:2::/64",
},
},
model.Model{
Id: types.StringValue("pid,nid"),
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
Name: types.StringNull(),
IPv4Nameservers: types.ListNull(types.StringType),
IPv4PrefixLength: types.Int64Null(),
Prefixes: types.ListNull(types.StringType),
IPv4Prefixes: types.ListNull(types.StringType),
Labels: types.MapNull(types.StringType),
Nameservers: types.ListNull(types.StringType),
IPv6Nameservers: types.ListNull(types.StringType),
IPv6PrefixLength: types.Int64Value(64),
IPv6Prefixes: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("fd12:3456:789a:1::/64"),
types.StringValue("fd12:3456:789a:2::/64"),
}),
IPv6Prefix: types.StringValue("fd12:3456:789a:1::/64"),
},
true,
},
{
"ipv4_ipv6_gateway_nil",
model.Model{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
},
&iaas.Network{
NetworkId: utils.Ptr("nid"),
},
model.Model{
Id: types.StringValue("pid,nid"),
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
Name: types.StringNull(),
Nameservers: types.ListNull(types.StringType),
IPv4Nameservers: types.ListNull(types.StringType),
IPv4PrefixLength: types.Int64Null(),
IPv4Gateway: types.StringNull(),
Prefixes: types.ListNull(types.StringType),
IPv4Prefixes: types.ListNull(types.StringType),
IPv6Nameservers: types.ListNull(types.StringType),
IPv6PrefixLength: types.Int64Null(),
IPv6Gateway: types.StringNull(),
IPv6Prefixes: types.ListNull(types.StringType),
PublicIP: types.StringNull(),
Labels: types.MapNull(types.StringType),
Routed: types.BoolNull(),
},
true,
},
{
"response_nil_fail",
model.Model{},
nil,
model.Model{},
false,
},
{
"no_resource_id",
model.Model{
ProjectId: types.StringValue("pid"),
},
&iaas.Network{},
model.Model{},
false,
},
}
for _, tt := range tests {
t.Run(tt.description, func(t *testing.T) {
err := mapFields(context.Background(), tt.input, &tt.state)
if !tt.isValid && err == nil {
t.Fatalf("Should have failed")
}
if tt.isValid && err != nil {
t.Fatalf("Should not have failed: %v", err)
}
if tt.isValid {
diff := cmp.Diff(tt.state, tt.expected)
if diff != "" {
t.Fatalf("Data does not match: %s", diff)
}
}
})
}
}
func TestToCreatePayload(t *testing.T) {
tests := []struct {
description string
input *model.Model
expected *iaas.CreateNetworkPayload
isValid bool
}{
{
"default_ok",
&model.Model{
Name: types.StringValue("name"),
IPv4Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"),
types.StringValue("ns2"),
}),
IPv4PrefixLength: types.Int64Value(24),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
"key": types.StringValue("value"),
}),
Routed: types.BoolValue(false),
IPv4Gateway: types.StringValue("gateway"),
IPv4Prefix: types.StringValue("prefix"),
},
&iaas.CreateNetworkPayload{
Name: utils.Ptr("name"),
AddressFamily: &iaas.CreateNetworkAddressFamily{
Ipv4: &iaas.CreateNetworkIPv4Body{
Nameservers: &[]string{
"ns1",
"ns2",
},
PrefixLength: utils.Ptr(int64(24)),
Gateway: iaas.NewNullableString(utils.Ptr("gateway")),
Prefix: utils.Ptr("prefix"),
},
},
Labels: &map[string]interface{}{
"key": "value",
},
Routed: utils.Ptr(false),
},
true,
},
{
"ipv4_nameservers_okay",
&model.Model{
Name: types.StringValue("name"),
Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"),
types.StringValue("ns2"),
}),
IPv4PrefixLength: types.Int64Value(24),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
"key": types.StringValue("value"),
}),
Routed: types.BoolValue(false),
IPv4Gateway: types.StringValue("gateway"),
IPv4Prefix: types.StringValue("prefix"),
},
&iaas.CreateNetworkPayload{
Name: utils.Ptr("name"),
AddressFamily: &iaas.CreateNetworkAddressFamily{
Ipv4: &iaas.CreateNetworkIPv4Body{
Nameservers: &[]string{
"ns1",
"ns2",
},
PrefixLength: utils.Ptr(int64(24)),
Gateway: iaas.NewNullableString(utils.Ptr("gateway")),
Prefix: utils.Ptr("prefix"),
},
},
Labels: &map[string]interface{}{
"key": "value",
},
Routed: utils.Ptr(false),
},
true,
},
{
"ipv6_default_ok",
&model.Model{
Name: types.StringValue("name"),
IPv6Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"),
types.StringValue("ns2"),
}),
IPv6PrefixLength: types.Int64Value(24),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
"key": types.StringValue("value"),
}),
Routed: types.BoolValue(false),
IPv6Gateway: types.StringValue("gateway"),
IPv6Prefix: types.StringValue("prefix"),
},
&iaas.CreateNetworkPayload{
Name: utils.Ptr("name"),
AddressFamily: &iaas.CreateNetworkAddressFamily{
Ipv6: &iaas.CreateNetworkIPv6Body{
Nameservers: &[]string{
"ns1",
"ns2",
},
PrefixLength: utils.Ptr(int64(24)),
Gateway: iaas.NewNullableString(utils.Ptr("gateway")),
Prefix: utils.Ptr("prefix"),
},
},
Labels: &map[string]interface{}{
"key": "value",
},
Routed: utils.Ptr(false),
},
true,
},
{
"ipv6_nameserver_null",
&model.Model{
Name: types.StringValue("name"),
IPv6Nameservers: types.ListNull(types.StringType),
IPv6PrefixLength: types.Int64Value(24),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
"key": types.StringValue("value"),
}),
Routed: types.BoolValue(false),
IPv6Gateway: types.StringValue("gateway"),
IPv6Prefix: types.StringValue("prefix"),
},
&iaas.CreateNetworkPayload{
Name: utils.Ptr("name"),
AddressFamily: &iaas.CreateNetworkAddressFamily{
Ipv6: &iaas.CreateNetworkIPv6Body{
Nameservers: nil,
PrefixLength: utils.Ptr(int64(24)),
Gateway: iaas.NewNullableString(utils.Ptr("gateway")),
Prefix: utils.Ptr("prefix"),
},
},
Labels: &map[string]interface{}{
"key": "value",
},
Routed: utils.Ptr(false),
},
true,
},
{
"ipv6_nameserver_empty_list",
&model.Model{
Name: types.StringValue("name"),
IPv6Nameservers: types.ListValueMust(types.StringType, []attr.Value{}),
IPv6PrefixLength: types.Int64Value(24),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
"key": types.StringValue("value"),
}),
Routed: types.BoolValue(false),
IPv6Gateway: types.StringValue("gateway"),
IPv6Prefix: types.StringValue("prefix"),
},
&iaas.CreateNetworkPayload{
Name: utils.Ptr("name"),
AddressFamily: &iaas.CreateNetworkAddressFamily{
Ipv6: &iaas.CreateNetworkIPv6Body{
Nameservers: utils.Ptr([]string{}),
PrefixLength: utils.Ptr(int64(24)),
Gateway: iaas.NewNullableString(utils.Ptr("gateway")),
Prefix: utils.Ptr("prefix"),
},
},
Labels: &map[string]interface{}{
"key": "value",
},
Routed: utils.Ptr(false),
},
true,
},
}
for _, tt := range tests {
t.Run(tt.description, func(t *testing.T) {
output, err := toCreatePayload(context.Background(), tt.input)
if !tt.isValid && err == nil {
t.Fatalf("Should have failed")
}
if tt.isValid && err != nil {
t.Fatalf("Should not have failed: %v", err)
}
if tt.isValid {
diff := cmp.Diff(output, tt.expected, cmp.AllowUnexported(iaas.NullableString{}))
if diff != "" {
t.Fatalf("Data does not match: %s", diff)
}
}
})
}
}
func TestToUpdatePayload(t *testing.T) {
tests := []struct {
description string
input *model.Model
state model.Model
expected *iaas.PartialUpdateNetworkPayload
isValid bool
}{
{
"default_ok",
&model.Model{
Name: types.StringValue("name"),
IPv4Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"),
types.StringValue("ns2"),
}),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
"key": types.StringValue("value"),
}),
Routed: types.BoolValue(true),
IPv4Gateway: types.StringValue("gateway"),
},
model.Model{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
Labels: types.MapNull(types.StringType),
},
&iaas.PartialUpdateNetworkPayload{
Name: utils.Ptr("name"),
AddressFamily: &iaas.UpdateNetworkAddressFamily{
Ipv4: &iaas.UpdateNetworkIPv4Body{
Nameservers: &[]string{
"ns1",
"ns2",
},
Gateway: iaas.NewNullableString(utils.Ptr("gateway")),
},
},
Labels: &map[string]interface{}{
"key": "value",
},
},
true,
},
{
"ipv4_nameservers_okay",
&model.Model{
Name: types.StringValue("name"),
Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"),
types.StringValue("ns2"),
}),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
"key": types.StringValue("value"),
}),
Routed: types.BoolValue(true),
IPv4Gateway: types.StringValue("gateway"),
},
model.Model{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
Labels: types.MapNull(types.StringType),
},
&iaas.PartialUpdateNetworkPayload{
Name: utils.Ptr("name"),
AddressFamily: &iaas.UpdateNetworkAddressFamily{
Ipv4: &iaas.UpdateNetworkIPv4Body{
Nameservers: &[]string{
"ns1",
"ns2",
},
Gateway: iaas.NewNullableString(utils.Ptr("gateway")),
},
},
Labels: &map[string]interface{}{
"key": "value",
},
},
true,
},
{
"ipv4_gateway_nil",
&model.Model{
Name: types.StringValue("name"),
IPv4Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"),
types.StringValue("ns2"),
}),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
"key": types.StringValue("value"),
}),
Routed: types.BoolValue(true),
},
model.Model{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
Labels: types.MapNull(types.StringType),
},
&iaas.PartialUpdateNetworkPayload{
Name: utils.Ptr("name"),
AddressFamily: &iaas.UpdateNetworkAddressFamily{
Ipv4: &iaas.UpdateNetworkIPv4Body{
Nameservers: &[]string{
"ns1",
"ns2",
},
},
},
Labels: &map[string]interface{}{
"key": "value",
},
},
true,
},
{
"ipv6_default_ok",
&model.Model{
Name: types.StringValue("name"),
IPv6Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"),
types.StringValue("ns2"),
}),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
"key": types.StringValue("value"),
}),
Routed: types.BoolValue(true),
IPv6Gateway: types.StringValue("gateway"),
},
model.Model{
ProjectId: types.StringValue("pid"),
NetworkId: types.StringValue("nid"),
Labels: types.MapNull(types.StringType),
},
&iaas.PartialUpdateNetworkPayload{
Name: utils.Ptr("name"),
AddressFamily: &iaas.UpdateNetworkAddressFamily{
Ipv6: &iaas.UpdateNetworkIPv6Body{
Nameservers: &[]string{
"ns1",
"ns2",
},
Gateway: iaas.NewNullableString(utils.Ptr("gateway")),
},
},
Labels: &map[string]interface{}{
"key": "value",
},
},
true,
},
{
"ipv6_gateway_nil",
&model.Model{
Name: types.StringValue("name"),
IPv6Nameservers: types.ListValueMust(types.StringType, []attr.Value{
types.StringValue("ns1"),
types.StringValue("ns2"),
}),
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{