diff --git a/.secrets.baseline b/.secrets.baseline index 1332509cd9..5eb22bef30 100644 --- a/.secrets.baseline +++ b/.secrets.baseline @@ -3,7 +3,7 @@ "files": "go.mod|go.sum|.*.map|^.secrets.baseline$", "lines": null }, - "generated_at": "2024-09-10T13:43:43Z", + "generated_at": "2024-09-12T14:29:18Z", "plugins_used": [ { "name": "AWSKeyDetector" @@ -444,15 +444,15 @@ "hashed_secret": "dc61ac50e6f36d09340d8ca062da1f0d4215004f", "is_secret": false, "is_verified": false, - "line_number": 62, + "line_number": 170, "type": "Secret Keyword", "verified_result": null }, { - "hashed_secret": "f4adb76dda1dc36da0e225b8477887a30e7346c9", + "hashed_secret": "470851178a9e3a16c35bc88232c21d04c555e5ca", "is_secret": false, "is_verified": false, - "line_number": 131, + "line_number": 242, "type": "Secret Keyword", "verified_result": null } @@ -1789,6 +1789,16 @@ "verified_result": null } ], + "ibm/service/codeengine/data_source_ibm_code_engine_function.go": [ + { + "hashed_secret": "b732fb611fd46a38e8667f9972e0cde777fbe37f", + "is_secret": false, + "is_verified": false, + "line_number": 229, + "type": "Secret Keyword", + "verified_result": null + } + ], "ibm/service/codeengine/data_source_ibm_code_engine_job.go": [ { "hashed_secret": "b732fb611fd46a38e8667f9972e0cde777fbe37f", @@ -1871,6 +1881,32 @@ "verified_result": null } ], + "ibm/service/codeengine/resource_ibm_code_engine_function.go": [ + { + "hashed_secret": "b732fb611fd46a38e8667f9972e0cde777fbe37f", + "is_secret": false, + "is_verified": false, + "line_number": 503, + "type": "Secret Keyword", + "verified_result": null + }, + { + "hashed_secret": "a99bf28e18370eb20e9cc79a1e7f8c379075f69c", + "is_secret": false, + "is_verified": false, + "line_number": 658, + "type": "Secret Keyword", + "verified_result": null + }, + { + "hashed_secret": "b5366a2d2ac98dae978423083f8b09e5cddc705d", + "is_secret": false, + "is_verified": false, + "line_number": 726, + "type": "Secret Keyword", + "verified_result": null + } + ], "ibm/service/codeengine/resource_ibm_code_engine_job.go": [ { "hashed_secret": "b732fb611fd46a38e8667f9972e0cde777fbe37f", diff --git a/CHANGELOG.md b/CHANGELOG.md index 8940c863d2..9d9744e0d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,42 @@ +# 1.70.0-beta0(Sep 22, 2024) + +Breaking Changes +* update(cloud-databases): Make Service Endpoints as Required argument([5615](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5615)) + +Features +* Support IAM Access tag + - **Resources** + - ibm_iam_access_tag +* Support VPC + - **Resources** + - ibm_is_subnet_reserved_ip_patch +* Support code Engine + - **Resources** + - ibm_code_engine_function + +Enhancements +* add service_to_service_enabled field to atracker event streams endpoint ([5605](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5605)) +* Deprecated ibm_resource_access_tag and replaced it with ibm_iam_access_tag ([5567](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5567)) +* SM New error formatting + crypto_key label name changes ([5562](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5562)) +* Deprecating alias and bindings APIs and schema items ([5612](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5612)) +* update(cloud-databases): Make Service Endpoints Required and send warning when public endpoints are in use ([5402](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5402)) +* discourage use of ibm_container_bind_service ([5588](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5588)) +* updated resources, data source and documentation for Slack Direct destination support ([5615](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5615)) +* IAM Policy Assignment: S2S Policy Assignments ET and AG ([5624](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5624)) +* fix for context and history parameter of template assignment ([5640](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5640)) +* Updating to latest schematics sdk and updating sch_agent resource to enable force deletion by default ([5660](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5660)) +* add support for 4th zone ([5644](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5644)) + +BugFixes +* The ibm_resource_tag do not detach if tag_type is access or service ([5566](https://github.com/IBM-Cloud/terraform-provider-ibm/issues/5566)) +* fix(is_share): added empty check and moved source_share_crn outside ([5632](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5632)) +* Add test bucket endpoints ([5636](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5636)) +* The ibm_resource_tag does not check the response on api tags calls ([5641](https://github.com/IBM-Cloud/terraform-provider-ibm/issues/5641)) + +# 1.69.2(Sep 13, 2024) +* Add region parameter to logs-routing resources and data sources ([5634](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5634)) +* fix(is_share): added empty check and moved source_share_crn outside ([5632](https://github.com/IBM-Cloud/terraform-provider-ibm/pull/5632)) + # 1.69.1(Sep 10, 2024) BugFixes * BUG: 1.69.0 panic when attempting to update ibm_resource_instance ([5618](https://github.com/IBM-Cloud/terraform-provider-ibm/issues/5618)) diff --git a/examples/ibm-code-engine/README.md b/examples/ibm-code-engine/README.md index 33ac34cd9b..931a6b8fff 100644 --- a/examples/ibm-code-engine/README.md +++ b/examples/ibm-code-engine/README.md @@ -1,17 +1,28 @@ -# Example for CodeEngineV2 - -This example illustrates how to use the CodeEngineV2 - -The following types of resources are supported: - -* code_engine_app -* code_engine_binding -* code_engine_build -* code_engine_config_map -* code_engine_domain_mapping -* code_engine_job -* code_engine_project -* code_engine_secret +# Examples for Code Engine + +These examples illustrate how to use the resources and data sources associated with Code Engine. + +The following resources are supported: +* ibm_code_engine_app +* ibm_code_engine_binding +* ibm_code_engine_build +* ibm_code_engine_config_map +* ibm_code_engine_domain_mapping +* ibm_code_engine_function +* ibm_code_engine_job +* ibm_code_engine_project +* ibm_code_engine_secret + +The following data sources are supported: +* ibm_code_engine_app +* ibm_code_engine_binding +* ibm_code_engine_build +* ibm_code_engine_config_map +* ibm_code_engine_domain_mapping +* ibm_code_engine_function +* ibm_code_engine_job +* ibm_code_engine_project +* ibm_code_engine_secret ## Usage @@ -25,19 +36,37 @@ $ terraform apply Run `terraform destroy` when you don't need these resources. +## Code Engine resources -## CodeEngineV2 resources - -code_engine_project resource: +### Resource: ibm_code_engine_project ```hcl -resource "code_engine_project" "code_engine_project_instance" { +resource "ibm_code_engine_project" "code_engine_project_instance" { name = var.code_engine_project_name resource_group_id = var.code_engine_project_resource_group_id } ``` -code_engine_app resource: +#### Inputs + +| Name | Description | Type | Required | +|------|-------------|------|---------| +| name | The name of the project. | `string` | true | +| resource_group_id | The ID of the resource group. | `string` | false | + +#### Outputs + +| Name | Description | +|------|-------------| +| account_id | An alphanumeric value identifying the account ID. | +| created_at | The timestamp when the project was created. | +| crn | The CRN of the project. | +| href | When you provision a new resource, a URL is created identifying the location of the instance. | +| region | The region for your project deployment. Possible values: `au-syd`, `br-sao`, `ca-tor`, `eu-de`, `eu-es`, `eu-gb`, `jp-osa`, `jp-tok`, `us-east`, `us-south`. | +| resource_type | The type of the project. | +| status | The current state of the project. For example, when the project is created and is ready for use, the status of the project is `active`. | + +### Resource: ibm_code_engine_app ```hcl resource "ibm_code_engine_app" "code_engine_app_instance" { @@ -52,7 +81,86 @@ resource "ibm_code_engine_app" "code_engine_app_instance" { } ``` -code_engine_build resource: +#### Inputs + +| Name | Description | Type | Required | +|------|-------------|------|---------| +| project_id | The ID of the project. | `string` | true | +| image_port | Optional port the app listens on. While the app will always be exposed via port `443` for end users, this port is used to connect to the port that is exposed by the container image. | `number` | false | +| image_reference | The name of the image that is used for this app. The format is `REGISTRY/NAMESPACE/REPOSITORY:TAG` where `REGISTRY` and `TAG` are optional. If `REGISTRY` is not specified, the default is `docker.io`. If `TAG` is not specified, the default is `latest`. If the image reference points to a registry that requires authentication, make sure to also specify the property `image_secret`. | `string` | true | +| image_secret | Optional name of the image registry access secret. The image registry access secret is used to authenticate with a private registry when you download the container image. If the image reference points to a registry that requires authentication, the app will be created but cannot reach the ready status, until this property is provided, too. | `string` | false | +| managed_domain_mappings | Optional value controlling which of the system managed domain mappings will be setup for the application. Valid values are 'local_public', 'local_private' and 'local'. Visibility can only be 'local_private' if the project supports application private visibility. | `string` | false | +| name | The name of the app. | `string` | true | +| probe_liveness | Response model for probes. | `` | false | +| probe_readiness | Response model for probes. | `` | false | +| run_arguments | Optional arguments for the app that are passed to start the container. If not specified an empty string array will be applied and the arguments specified by the container image, will be used to start the container. | `list(string)` | false | +| run_as_user | Optional user ID (UID) to run the app. | `number` | false | +| run_commands | Optional commands for the app that are passed to start the container. If not specified an empty string array will be applied and the command specified by the container image, will be used to start the container. | `list(string)` | false | +| run_env_variables | References to config maps, secrets or literal values, which are exposed as environment variables in the application. | `list()` | false | +| run_service_account | Optional name of the service account. For built-in service accounts, you can use the shortened names `manager` , `none`, `reader`, and `writer`. | `string` | false | +| run_volume_mounts | Mounts of config maps or secrets. | `list()` | false | +| scale_concurrency | Optional maximum number of requests that can be processed concurrently per instance. | `number` | false | +| scale_concurrency_target | Optional threshold of concurrent requests per instance at which one or more additional instances are created. Use this value to scale up instances based on concurrent number of requests. This option defaults to the value of the `scale_concurrency` option, if not specified. | `number` | false | +| scale_cpu_limit | Optional number of CPU set for the instance of the app. For valid values see [Supported memory and CPU combinations](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo). | `string` | false | +| scale_down_delay | Optional amount of time in seconds that delays the scale-down behavior for an app instance. | `number` | false | +| scale_ephemeral_storage_limit | Optional amount of ephemeral storage to set for the instance of the app. The amount specified as ephemeral storage, must not exceed the amount of `scale_memory_limit`. The units for specifying ephemeral storage are Megabyte (M) or Gigabyte (G), whereas G and M are the shorthand expressions for GB and MB. For more information see [Units of measurement](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo#unit-measurements). | `string` | false | +| scale_initial_instances | Optional initial number of instances that are created upon app creation or app update. | `number` | false | +| scale_max_instances | Optional maximum number of instances for this app. If you set this value to `0`, this property does not set a upper scaling limit. However, the app scaling is still limited by the project quota for instances. See [Limits and quotas for Code Engine](https://cloud.ibm.com/docs/codeengine?topic=codeengine-limits). | `number` | false | +| scale_memory_limit | Optional amount of memory set for the instance of the app. For valid values see [Supported memory and CPU combinations](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo). The units for specifying memory are Megabyte (M) or Gigabyte (G), whereas G and M are the shorthand expressions for GB and MB. For more information see [Units of measurement](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo#unit-measurements). | `string` | false | +| scale_min_instances | Optional minimum number of instances for this app. If you set this value to `0`, the app will scale down to zero, if not hit by any request for some time. | `number` | false | +| scale_request_timeout | Optional amount of time in seconds that is allowed for a running app to respond to a request. | `number` | false | + +#### Outputs + +| Name | Description | +|------|-------------| +| build | Reference to a build that is associated with the application. | +| build_run | Reference to a build run that is associated with the application. | +| created_at | The timestamp when the resource was created. | +| endpoint | Optional URL to invoke the app. Depending on visibility, this is accessible publicly or in the private network only. Empty in case 'managed_domain_mappings' is set to 'local'. | +| endpoint_internal | The URL to the app that is only visible within the project. | +| entity_tag | The version of the app instance, which is used to achieve optimistic locking. | +| href | When you provision a new app, a URL is created identifying the location of the instance. | +| app_id | The identifier of the resource. | +| region | The region of the project the resource is located in. Possible values: 'au-syd', 'br-sao', 'ca-tor', 'eu-de', 'eu-gb', 'jp-osa', 'jp-tok', 'us-east', 'us-south'. | +| resource_type | The type of the app. | +| status | The current status of the app. | +| status_details | The detailed status of the application. | + +### Resource: ibm_code_engine_binding + +```hcl +resource "ibm_code_engine_binding" "code_engine_binding_instance" { + project_id = var.code_engine_project_id + prefix = var.code_engine_binding_prefix + secret_name = "my-service-access-secret" + component { + name = var.code_engine_binding_component_name + resource_type = var.code_engine_binding_component_resource_type + } +} + +``` + +#### Inputs + +| Name | Description | Type | Required | +|------|-------------|------|---------| +| project_id | The ID of the project. | `string` | true | +| component | A reference to another component. | `` | true | +| prefix | The value that is set as a prefix in the component that is bound. | `string` | true | +| secret_name | The service access secret that is bound to a component. | `string` | true | + +#### Outputs + +| Name | Description | +|------|-------------| +| href | When you provision a new binding, a URL is created identifying the location of the instance. | +| resource_type | The type of the binding. | +| status | The current status of the binding. | +| code_engine_binding_id | The ID of the binding. | + +### Resource: ibm_code_engine_build ```hcl resource "ibm_code_engine_build" "code_engine_build_instance" { @@ -65,34 +173,201 @@ resource "ibm_code_engine_build" "code_engine_build_instance" { } ``` -code_engine_config_map resource: +#### Inputs + +| Name | Description | Type | Required | +|------|-------------|------|---------| +| project_id | The ID of the project. | `string` | true | +| name | The name of the build. | `string` | true | +| output_image | The name of the image. | `string` | true | +| output_secret | The secret that is required to access the image registry. Make sure that the secret is granted with push permissions towards the specified container registry namespace. | `string` | true | +| source_context_dir | Optional directory in the repository that contains the buildpacks file or the Dockerfile. | `string` | false | +| source_revision | Commit, tag, or branch in the source repository to pull. This field is optional if the `source_type` is `git` and uses the HEAD of default branch if not specified. If the `source_type` value is `local`, this field must be omitted. | `string` | false | +| source_secret | Name of the secret that is used access the repository source. This field is optional if the `source_type` is `git`. Additionally, if the `source_url` points to a repository that requires authentication, the build will be created but cannot access any source code, until this property is provided, too. If the `source_type` value is `local`, this field must be omitted. | `string` | false | +| source_type | Specifies the type of source to determine if your build source is in a repository or based on local source code.* local - For builds from local source code.* git - For builds from git version controlled source code. | `string` | false | +| source_url | The URL of the code repository. This field is required if the `source_type` is `git`. If the `source_type` value is `local`, this field must be omitted. If the repository is publicly available you can provide a 'https' URL like `https://github.com/IBM/CodeEngine`. If the repository requires authentication, you need to provide a 'ssh' URL like `git@github.com:IBM/CodeEngine.git` along with a `source_secret` that points to a secret of format `ssh_auth`. | `string` | false | +| strategy_size | Optional size for the build, which determines the amount of resources used. Build sizes are `small`, `medium`, `large`, `xlarge`, `xxlarge`. | `string` | false | +| strategy_spec_file | Optional path to the specification file that is used for build strategies for building an image. | `string` | false | +| strategy_type | The strategy to use for building the image. | `string` | true | +| timeout | The maximum amount of time, in seconds, that can pass before the build must succeed or fail. | `number` | false | + +#### Outputs + +| Name | Description | +|------|-------------| +| created_at | The timestamp when the resource was created. | +| entity_tag | The version of the build instance, which is used to achieve optimistic locking. | +| href | When you provision a new build, a URL is created identifying the location of the instance. | +| build_id | The identifier of the resource. | +| region | The region of the project the resource is located in. Possible values: 'au-syd', 'br-sao', 'ca-tor', 'eu-de', 'eu-gb', 'jp-osa', 'jp-tok', 'us-east', 'us-south'. | +| resource_type | The type of the build. | +| status | The current status of the build. | +| status_details | The detailed status of the build. | + +### Resource: ibm_code_engine_config_map ```hcl -resource "code_engine_config_map" "code_engine_config_map_instance" { +resource "ibm_code_engine_config_map" "code_engine_config_map_instance" { project_id = var.code_engine_project_id name = var.code_engine_config_map_name data = var.code_engine_config_map_data } ``` -code_engine_job resource: +#### Inputs + +| Name | Description | Type | Required | +|------|-------------|------|---------| +| project_id | The ID of the project. | `string` | true | +| data | The key-value pair for the config map. Values must be specified in `KEY=VALUE` format. | `map(string)` | false | +| name | The name of the config map. | `string` | true | + +#### Outputs + +| Name | Description | +|------|-------------| +| created_at | The timestamp when the resource was created. | +| entity_tag | The version of the config map instance, which is used to achieve optimistic locking. | +| href | When you provision a new config map, a URL is created identifying the location of the instance. | +| config_map_id | The identifier of the resource. | +| region | The region of the project the resource is located in. Possible values: 'au-syd', 'br-sao', 'ca-tor', 'eu-de', 'eu-gb', 'jp-osa', 'jp-tok', 'us-east', 'us-south'. | +| resource_type | The type of the config map. | + +### Resource: ibm_code_engine_domain_mapping + +```hcl +resource "ibm_code_engine_domain_mapping" "code_engine_domain_mapping_instance" { + project_id = var.code_engine_domain_mapping_project_id + name = var.code_engine_domain_mapping_name + tls_secret = var.code_engine_domain_mapping_tls_secret + component { + name = var.code_engine_domain_mapping_component_name + resource_type = var.code_engine_domain_mapping_component_resource_type + } +} +``` + +#### Inputs + +| Name | Description | Type | Required | +|------|-------------|------|---------| +| project_id | The ID of the project. | `string` | true | +| component | A reference to another component. | `` | true | +| name | The name of the domain mapping. | `string` | true | +| tls_secret | The name of the TLS secret that includes the certificate and private key of this domain mapping. | `string` | true | + +#### Outputs + +| Name | Description | +|------|-------------| +| cname_target | The value of the CNAME record that must be configured in the DNS settings of the domain, to route traffic properly to the target Code Engine region. | +| created_at | The timestamp when the resource was created. | +| entity_tag | The version of the domain mapping instance, which is used to achieve optimistic locking. | +| href | When you provision a new domain mapping, a URL is created identifying the location of the instance. | +| domain_mapping_id | The identifier of the resource. | +| region | The region of the project the resource is located in. Possible values: 'au-syd', 'br-sao', 'ca-tor', 'eu-de', 'eu-gb', 'jp-osa', 'jp-tok', 'us-east', 'us-south'. | +| resource_type | The type of the Code Engine resource. | +| status | The current status of the domain mapping. | +| status_details | The detailed status of the domain mapping. | +| user_managed | Specifies whether the domain mapping is managed by the user or by Code Engine. | +| visibility | Specifies whether the domain mapping is reachable through the public internet, or private IBM network, or only through other components within the same Code Engine project. | + +### Resource: ibm_code_engine_function + +```hcl +resource "ibm_code_engine_function" "code_engine_function_instance" { + project_id = var.code_engine_function_project_id + name = var.code_engine_function_name + runtime = var.code_engine_function_runtime + code_reference = var.code_engine_function_code_reference +} +``` + +#### Inputs + +| Name | Description | Type | Required | +|------|-------------|------|---------| +| project_id | The ID of the project. | `string` | true | +| code_binary | Specifies whether the code is binary or not. Defaults to false when `code_reference` is set to a data URL. When `code_reference` is set to a code bundle URL, this field is always true. | `bool` | false | +| code_main | Specifies the name of the function that should be invoked. | `string` | false | +| code_reference | Specifies either a reference to a code bundle or the source code itself. To specify the source code, use the data URL scheme and include the source code as base64 encoded. The data URL scheme is defined in [RFC 2397](https://tools.ietf.org/html/rfc2397). | `string` | true | +| code_secret | The name of the secret that is used to access the specified `code_reference`. The secret is used to authenticate with a non-public endpoint that is specified as`code_reference`. | `string` | false | +| managed_domain_mappings | Optional value controlling which of the system managed domain mappings will be setup for the function. Valid values are 'local_public', 'local_private' and 'local'. Visibility can only be 'local_private' if the project supports function private visibility. | `string` | false | +| name | The name of the function. | `string` | true | +| run_env_variables | References to config maps, secrets or literal values, which are defined by the function owner and are exposed as environment variables in the function. | `list()` | false | +| runtime | The managed runtime used to execute the injected code. | `string` | true | +| scale_concurrency | Number of parallel requests handled by a single instance, supported only by Node.js, default is `1`. | `number` | false | +| scale_cpu_limit | Optional amount of CPU set for the instance of the function. For valid values see [Supported memory and CPU combinations](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo). | `string` | false | +| scale_down_delay | Optional amount of time in seconds that delays the scale down behavior for a function. | `number` | false | +| scale_max_execution_time | Timeout in secs after which the function is terminated. | `number` | false | +| scale_memory_limit | Optional amount of memory set for the instance of the function. For valid values see [Supported memory and CPU combinations](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo). The units for specifying memory are Megabyte (M) or Gigabyte (G), whereas G and M are the shorthand expressions for GB and MB. For more information see [Units of measurement](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo#unit-measurements). | `string` | false | + +#### Outputs + +| Name | Description | +|------|-------------| +| created_at | The timestamp when the resource was created. | +| endpoint | URL to invoke the function. | +| endpoint_internal | URL to function that is only visible within the project. | +| entity_tag | The version of the function instance, which is used to achieve optimistic locking. | +| href | When you provision a new function, a relative URL path is created identifying the location of the instance. | +| function_id | The identifier of the resource. | +| region | The region of the project the resource is located in. Possible values: 'au-syd', 'br-sao', 'ca-tor', 'eu-de', 'eu-gb', 'jp-osa', 'jp-tok', 'us-east', 'us-south'. | +| resource_type | The type of the function. | +| status | The current status of the function. | +| status_details | The detailed status of the function. | + +### Resource: ibm_code_engine_job ```hcl resource "ibm_code_engine_job" "code_engine_job_instance" { project_id = var.code_engine_project_id image_reference = var.code_engine_job_image_reference name = var.code_engine_job_name - run_env_variables { type = "literal" name = "name" value = "value" } } - ``` -code_engine_secret resource: +#### Inputs + +| Name | Description | Type | Required | +|------|-------------|------|---------| +| project_id | The ID of the project. | `string` | true | +| image_reference | The name of the image that is used for this job. The format is `REGISTRY/NAMESPACE/REPOSITORY:TAG` where `REGISTRY` and `TAG` are optional. If `REGISTRY` is not specified, the default is `docker.io`. If `TAG` is not specified, the default is `latest`. If the image reference points to a registry that requires authentication, make sure to also specify the property `image_secret`. | `string` | true | +| image_secret | The name of the image registry access secret. The image registry access secret is used to authenticate with a private registry when you download the container image. If the image reference points to a registry that requires authentication, the job / job runs will be created but submitted job runs will fail, until this property is provided, too. This property must not be set on a job run, which references a job template. | `string` | false | +| name | The name of the job. | `string` | true | +| run_arguments | Set arguments for the job that are passed to start job run containers. If not specified an empty string array will be applied and the arguments specified by the container image, will be used to start the container. | `list(string)` | false | +| run_as_user | The user ID (UID) to run the job. | `number` | false | +| run_commands | Set commands for the job that are passed to start job run containers. If not specified an empty string array will be applied and the command specified by the container image, will be used to start the container. | `list(string)` | false | +| run_env_variables | References to config maps, secrets or literal values, which are exposed as environment variables in the job run. | `list()` | false | +| run_mode | The mode for runs of the job. Valid values are `task` and `daemon`. In `task` mode, the `max_execution_time` and `retry_limit` properties apply. In `daemon` mode, since there is no timeout and failed instances are restarted indefinitely, the `max_execution_time` and `retry_limit` properties are not allowed. | `string` | false | +| run_service_account | The name of the service account. For built-in service accounts, you can use the shortened names `manager`, `none`, `reader`, and `writer`. This property must not be set on a job run, which references a job template. | `string` | false | +| run_volume_mounts | Optional mounts of config maps or secrets. | `list()` | false | +| scale_array_spec | Define a custom set of array indices as a comma-separated list containing single values and hyphen-separated ranges, such as 5,12-14,23,27. Each instance gets its array index value from the environment variable JOB_INDEX. The number of unique array indices that you specify with this parameter determines the number of job instances to run. | `string` | false | +| scale_cpu_limit | Optional amount of CPU set for the instance of the job. For valid values see [Supported memory and CPU combinations](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo). | `string` | false | +| scale_ephemeral_storage_limit | Optional amount of ephemeral storage to set for the instance of the job. The amount specified as ephemeral storage, must not exceed the amount of `scale_memory_limit`. The units for specifying ephemeral storage are Megabyte (M) or Gigabyte (G), whereas G and M are the shorthand expressions for GB and MB. For more information see [Units of measurement](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo#unit-measurements). | `string` | false | +| scale_max_execution_time | The maximum execution time in seconds for runs of the job. This property can only be specified if `run_mode` is `task`. | `number` | false | +| scale_memory_limit | Optional amount of memory set for the instance of the job. For valid values see [Supported memory and CPU combinations](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo). The units for specifying memory are Megabyte (M) or Gigabyte (G), whereas G and M are the shorthand expressions for GB and MB. For more information see [Units of measurement](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo#unit-measurements). | `string` | false | +| scale_retry_limit | The number of times to rerun an instance of the job before the job is marked as failed. This property can only be specified if `run_mode` is `task`. | `number` | false | + +#### Outputs + +| Name | Description | +|------|-------------| +| build | Reference to a build that is associated with the job. | +| build_run | Reference to a build run that is associated with the job. | +| created_at | The timestamp when the resource was created. | +| entity_tag | The version of the job instance, which is used to achieve optimistic locking. | +| href | When you provision a new job, a URL is created identifying the location of the instance. | +| job_id | The identifier of the resource. | +| region | The region of the project the resource is located in. Possible values: 'au-syd', 'br-sao', 'ca-tor', 'eu-de', 'eu-gb', 'jp-osa', 'jp-tok', 'us-east', 'us-south'. | +| resource_type | The type of the job. | + +### Resource: ibm_code_engine_secret ```hcl resource "ibm_code_engine_secret" "code_engine_secret_instance" { @@ -103,172 +378,349 @@ resource "ibm_code_engine_secret" "code_engine_secret_instance" { } ``` -code_engine_binding resource: +#### Inputs -```hcl -resource "ibm_code_engine_binding" "code_engine_secret_instance" { - project_id = var.code_engine_project_id - component { - name = var.code_engine_binding_component_name - resource_type = var.code_engine_binding_component_resource_type - } +| Name | Description | Type | Required | +|------|-------------|------|---------| +| project_id | The ID of the project. | `string` | true | +| data | Data container that allows to specify config parameters and their values as a key-value map. Each key field must consist of alphanumeric characters, `-`, `_` or `.` and must not exceed a max length of 253 characters. Each value field can consists of any character and must not exceed a max length of 1048576 characters. | `map(string)` | false | +| format | Specify the format of the secret. | `string` | true | +| name | The name of the secret. | `string` | true | +| service_access | Properties for Service Access Secrets. | `` | false | +| service_operator | Properties for the IBM Cloud Operator Secret. | `` | false | - prefix = var.code_engine_binding_prefix - secret_name = var.code_engine_binding_secret_name -} -``` +#### Outputs -code_engine_domain_mapping resource: +| Name | Description | +|------|-------------| +| created_at | The timestamp when the resource was created. | +| entity_tag | The version of the secret instance, which is used to achieve optimistic locking. | +| href | When you provision a new secret, a URL is created identifying the location of the instance. | +| secret_id | The identifier of the resource. | +| region | The region of the project the resource is located in. Possible values: 'au-syd', 'br-sao', 'ca-tor', 'eu-de', 'eu-gb', 'jp-osa', 'jp-tok', 'us-east', 'us-south'. | +| resource_type | The type of the secret. | + +## Code Engine data sources + +### Data source: ibm_code_engine_project ```hcl -resource "ibm_code_engine_domain_mapping" "code_engine_domain_mapping_instance" { - project_id = var.code_engine_project_id - name = var.code_engine_domain_mapping_name - component { - name = var.code_engine_domain_mapping_component_name - resource_type = var.code_engine_domain_mapping_component_resource_type - } - tls_secret = var.code_engine_binding_secret_name +data "ibm_code_engine_project" "code_engine_project_instance" { + project_id = var.data_code_engine_project_code_engine_project_id } ``` -## CodeEngineV2 Data sources +#### Inputs + +| Name | Description | Type | Required | +|------|-------------|------|---------| +| project_id | The ID of the project. | `string` | true | -code_engine_project data source: +#### Outputs + +| Name | Description | +|------|-------------| +| account_id | An alphanumeric value identifying the account ID. | +| created_at | The timestamp when the project was created. | +| crn | The CRN of the project. | +| href | When you provision a new resource, a URL is created identifying the location of the instance. | +| name | The name of the project. | +| region | The region for your project deployment. Possible values: 'au-syd', 'br-sao', 'ca-tor', 'eu-de', 'eu-gb', 'jp-osa', 'jp-tok', 'us-east', 'us-south'. | +| resource_group_id | The ID of the resource group. | +| resource_type | The type of the project. | +| status | The current state of the project. For example, when the project is created and is ready for use, the status of the project is active. | + +### Data source: ibm_code_engine_app ```hcl -data "code_engine_project" "code_engine_project_instance" { - project_id = var.code_engine_project_id +data "ibm_code_engine_app" "code_engine_app_instance" { + project_id = var.data_code_engine_app_project_id + name = var.data_code_engine_app_name } ``` -code_engine_app data source: +#### Inputs + +| Name | Description | Type | Required | +|------|-------------|------|---------| +| project_id | The ID of the project. | `string` | true | +| name | The name of your application. | `string` | true | + +#### Outputs + +| Name | Description | +|------|-------------| +| build | Reference to a build that is associated with the application. | +| build_run | Reference to a build run that is associated with the application. | +| created_at | The timestamp when the resource was created. | +| endpoint | Optional URL to invoke the app. Depending on visibility, this is accessible publicly or in the private network only. Empty in case 'managed_domain_mappings' is set to 'local'. | +| endpoint_internal | The URL to the app that is only visible within the project. | +| entity_tag | The version of the app instance, which is used to achieve optimistic locking. | +| href | When you provision a new app, a URL is created identifying the location of the instance. | +| image_port | Optional port the app listens on. While the app will always be exposed via port `443` for end users, this port is used to connect to the port that is exposed by the container image. | +| image_reference | The name of the image that is used for this app. The format is `REGISTRY/NAMESPACE/REPOSITORY:TAG` where `REGISTRY` and `TAG` are optional. If `REGISTRY` is not specified, the default is `docker.io`. If `TAG` is not specified, the default is `latest`. If the image reference points to a registry that requires authentication, make sure to also specify the property `image_secret`. | +| image_secret | Optional name of the image registry access secret. The image registry access secret is used to authenticate with a private registry when you download the container image. If the image reference points to a registry that requires authentication, the app will be created but cannot reach the ready status, until this property is provided, too. | +| managed_domain_mappings | Optional value controlling which of the system managed domain mappings will be setup for the application. Valid values are 'local_public', 'local_private' and 'local'. Visibility can only be 'local_private' if the project supports application private visibility. | +| probe_liveness | Response model for probes. | +| probe_readiness | Response model for probes. | +| region | The region of the project the resource is located in. Possible values: 'au-syd', 'br-sao', 'ca-tor', 'eu-de', 'eu-gb', 'jp-osa', 'jp-tok', 'us-east', 'us-south'. | +| resource_type | The type of the app. | +| run_arguments | Optional arguments for the app that are passed to start the container. If not specified an empty string array will be applied and the arguments specified by the container image, will be used to start the container. | +| run_as_user | Optional user ID (UID) to run the app. | +| run_commands | Optional commands for the app that are passed to start the container. If not specified an empty string array will be applied and the command specified by the container image, will be used to start the container. | +| run_env_variables | References to config maps, secrets or literal values, which are exposed as environment variables in the application. | +| run_service_account | Optional name of the service account. For built-in service accounts, you can use the shortened names `manager` , `none`, `reader`, and `writer`. | +| run_volume_mounts | Mounts of config maps or secrets. | +| scale_concurrency | Optional maximum number of requests that can be processed concurrently per instance. | +| scale_concurrency_target | Optional threshold of concurrent requests per instance at which one or more additional instances are created. Use this value to scale up instances based on concurrent number of requests. This option defaults to the value of the `scale_concurrency` option, if not specified. | +| scale_cpu_limit | Optional number of CPU set for the instance of the app. For valid values see [Supported memory and CPU combinations](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo). | +| scale_down_delay | Optional amount of time in seconds that delays the scale-down behavior for an app instance. | +| scale_ephemeral_storage_limit | Optional amount of ephemeral storage to set for the instance of the app. The amount specified as ephemeral storage, must not exceed the amount of `scale_memory_limit`. The units for specifying ephemeral storage are Megabyte (M) or Gigabyte (G), whereas G and M are the shorthand expressions for GB and MB. For more information see [Units of measurement](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo#unit-measurements). | +| scale_initial_instances | Optional initial number of instances that are created upon app creation or app update. | +| scale_max_instances | Optional maximum number of instances for this app. If you set this value to `0`, this property does not set a upper scaling limit. However, the app scaling is still limited by the project quota for instances. See [Limits and quotas for Code Engine](https://cloud.ibm.com/docs/codeengine?topic=codeengine-limits). | +| scale_memory_limit | Optional amount of memory set for the instance of the app. For valid values see [Supported memory and CPU combinations](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo). The units for specifying memory are Megabyte (M) or Gigabyte (G), whereas G and M are the shorthand expressions for GB and MB. For more information see [Units of measurement](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo#unit-measurements). | +| scale_min_instances | Optional minimum number of instances for this app. If you set this value to `0`, the app will scale down to zero, if not hit by any request for some time. | +| scale_request_timeout | Optional amount of time in seconds that is allowed for a running app to respond to a request. | +| status | The current status of the app. | +| status_details | The detailed status of the application. | + +### Data source: ibm_code_engine_binding ```hcl -data "ibm_code_engine_app" "code_engine_app_instance" { - project_id = var.code_engine_project_id - name = var.code_engine_app_name +data "ibm_code_engine_binding" "code_engine_binding_instance" { + project_id = var.data_code_engine_binding_project_id + code_engine_binding_id = var.data_code_engine_binding_code_engine_binding_id } ``` -code_engine_build data source: +#### Inputs + +| Name | Description | Type | Required | +|------|-------------|------|---------| +| project_id | The ID of the project. | `string` | true | +| code_engine_binding_id | The id of your binding. | `string` | true | + +#### Outputs + +| Name | Description | +|------|-------------| +| component | A reference to another component. | +| href | When you provision a new binding, a URL is created identifying the location of the instance. | +| prefix | The value that is set as a prefix in the component that is bound. | +| resource_type | The type of the binding. | +| secret_name | The service access secret that is bound to a component. | +| status | The current status of the binding. | + +### Data source: ibm_code_engine_build ```hcl data "ibm_code_engine_build" "code_engine_build_instance" { - project_id = var.code_engine_project_id - name = var.code_engine_build_name + project_id = var.data_code_engine_build_project_id + name = var.data_code_engine_build_name } ``` -code_engine_config_map data source: +#### Inputs + +| Name | Description | Type | Required | +|------|-------------|------|---------| +| project_id | The ID of the project. | `string` | true | +| name | The name of your build. | `string` | true | + +#### Outputs + +| Name | Description | +|------|-------------| +| created_at | The timestamp when the resource was created. | +| entity_tag | The version of the build instance, which is used to achieve optimistic locking. | +| href | When you provision a new build, a URL is created identifying the location of the instance. | +| output_image | The name of the image. | +| output_secret | The secret that is required to access the image registry. Make sure that the secret is granted with push permissions towards the specified container registry namespace. | +| region | The region of the project the resource is located in. Possible values: 'au-syd', 'br-sao', 'ca-tor', 'eu-de', 'eu-gb', 'jp-osa', 'jp-tok', 'us-east', 'us-south'. | +| resource_type | The type of the build. | +| source_context_dir | Optional directory in the repository that contains the buildpacks file or the Dockerfile. | +| source_revision | Commit, tag, or branch in the source repository to pull. This field is optional if the `source_type` is `git` and uses the HEAD of default branch if not specified. If the `source_type` value is `local`, this field must be omitted. | +| source_secret | Name of the secret that is used access the repository source. This field is optional if the `source_type` is `git`. Additionally, if the `source_url` points to a repository that requires authentication, the build will be created but cannot access any source code, until this property is provided, too. If the `source_type` value is `local`, this field must be omitted. | +| source_type | Specifies the type of source to determine if your build source is in a repository or based on local source code.* local - For builds from local source code.* git - For builds from git version controlled source code. | +| source_url | The URL of the code repository. This field is required if the `source_type` is `git`. If the `source_type` value is `local`, this field must be omitted. If the repository is publicly available you can provide a 'https' URL like `https://github.com/IBM/CodeEngine`. If the repository requires authentication, you need to provide a 'ssh' URL like `git@github.com:IBM/CodeEngine.git` along with a `source_secret` that points to a secret of format `ssh_auth`. | +| status | The current status of the build. | +| status_details | The detailed status of the build. | +| strategy_size | Optional size for the build, which determines the amount of resources used. Build sizes are `small`, `medium`, `large`, `xlarge`, `xxlarge`. | +| strategy_spec_file | Optional path to the specification file that is used for build strategies for building an image. | +| strategy_type | The strategy to use for building the image. | +| timeout | The maximum amount of time, in seconds, that can pass before the build must succeed or fail. | + +### Data source: ibm_code_engine_config_map ```hcl -data "code_engine_config_map" "code_engine_config_map_instance" { - project_id = var.code_engine_project_id - name = var.code_engine_config_map_name +data "ibm_code_engine_config_map" "code_engine_config_map_instance" { + project_id = var.data_code_engine_config_map_project_id + name = var.data_code_engine_config_map_name } ``` -code_engine_job data source: +#### Inputs + +| Name | Description | Type | Required | +|------|-------------|------|---------| +| project_id | The ID of the project. | `string` | true | +| name | The name of your configmap. | `string` | true | + +#### Outputs + +| Name | Description | +|------|-------------| +| created_at | The timestamp when the resource was created. | +| data | The key-value pair for the config map. Values must be specified in `KEY=VALUE` format. | +| entity_tag | The version of the config map instance, which is used to achieve optimistic locking. | +| href | When you provision a new config map, a URL is created identifying the location of the instance. | +| region | The region of the project the resource is located in. Possible values: 'au-syd', 'br-sao', 'ca-tor', 'eu-de', 'eu-gb', 'jp-osa', 'jp-tok', 'us-east', 'us-south'. | +| resource_type | The type of the config map. | + +### Data source: ibm_code_engine_domain_mapping ```hcl -data "ibm_code_engine_job" "code_engine_job_instance" { - project_id = var.code_engine_project_id - name = var.code_engine_job_name +data "ibm_code_engine_domain_mapping" "code_engine_domain_mapping_instance" { + project_id = var.data_code_engine_domain_mapping_project_id + name = var.data_code_engine_domain_mapping_name } - ``` -code_engine_secret data source: +#### Inputs + +| Name | Description | Type | Required | +|------|-------------|------|---------| +| project_id | The ID of the project. | `string` | true | +| name | The name of your domain mapping. | `string` | true | + +#### Outputs + +| Name | Description | +|------|-------------| +| cname_target | The value of the CNAME record that must be configured in the DNS settings of the domain, to route traffic properly to the target Code Engine region. | +| component | A reference to another component. | +| created_at | The timestamp when the resource was created. | +| entity_tag | The version of the domain mapping instance, which is used to achieve optimistic locking. | +| href | When you provision a new domain mapping, a URL is created identifying the location of the instance. | +| region | The region of the project the resource is located in. Possible values: 'au-syd', 'br-sao', 'ca-tor', 'eu-de', 'eu-gb', 'jp-osa', 'jp-tok', 'us-east', 'us-south'. | +| resource_type | The type of the Code Engine resource. | +| status | The current status of the domain mapping. | +| status_details | The detailed status of the domain mapping. | +| tls_secret | The name of the TLS secret that includes the certificate and private key of this domain mapping. | +| user_managed | Specifies whether the domain mapping is managed by the user or by Code Engine. | +| visibility | Specifies whether the domain mapping is reachable through the public internet, or private IBM network, or only through other components within the same Code Engine project. | + +### Data source: ibm_code_engine_function ```hcl -data "ibm_code_engine_secret" "code_engine_secret_instance" { - project_id = var.code_engine_project_id - name = var.code_engine_secret_name +data "ibm_code_engine_function" "code_engine_function_instance" { + project_id = var.data_code_engine_function_project_id + name = var.data_code_engine_function_name } ``` -code_engine_binding data source: +#### Inputs + +| Name | Description | Type | Required | +|------|-------------|------|---------| +| project_id | The ID of the project. | `string` | true | +| name | The name of your function. | `string` | true | + +#### Outputs + +| Name | Description | +|------|-------------| +| code_binary | Specifies whether the code is binary or not. Defaults to false when `code_reference` is set to a data URL. When `code_reference` is set to a code bundle URL, this field is always true. | +| code_main | Specifies the name of the function that should be invoked. | +| code_reference | Specifies either a reference to a code bundle or the source code itself. To specify the source code, use the data URL scheme and include the source code as base64 encoded. The data URL scheme is defined in [RFC 2397](https://tools.ietf.org/html/rfc2397). | +| code_secret | The name of the secret that is used to access the specified `code_reference`. The secret is used to authenticate with a non-public endpoint that is specified as`code_reference`. | +| created_at | The timestamp when the resource was created. | +| endpoint | URL to invoke the function. | +| endpoint_internal | URL to function that is only visible within the project. | +| entity_tag | The version of the function instance, which is used to achieve optimistic locking. | +| href | When you provision a new function, a relative URL path is created identifying the location of the instance. | +| managed_domain_mappings | Optional value controlling which of the system managed domain mappings will be setup for the function. Valid values are 'local_public', 'local_private' and 'local'. Visibility can only be 'local_private' if the project supports function private visibility. | +| region | The region of the project the resource is located in. Possible values: 'au-syd', 'br-sao', 'ca-tor', 'eu-de', 'eu-gb', 'jp-osa', 'jp-tok', 'us-east', 'us-south'. | +| resource_type | The type of the function. | +| run_env_variables | References to config maps, secrets or literal values, which are defined by the function owner and are exposed as environment variables in the function. | +| runtime | The managed runtime used to execute the injected code. | +| scale_concurrency | Number of parallel requests handled by a single instance, supported only by Node.js, default is `1`. | +| scale_cpu_limit | Optional amount of CPU set for the instance of the function. For valid values see [Supported memory and CPU combinations](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo). | +| scale_down_delay | Optional amount of time in seconds that delays the scale down behavior for a function. | +| scale_max_execution_time | Timeout in secs after which the function is terminated. | +| scale_memory_limit | Optional amount of memory set for the instance of the function. For valid values see [Supported memory and CPU combinations](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo). The units for specifying memory are Megabyte (M) or Gigabyte (G), whereas G and M are the shorthand expressions for GB and MB. For more information see [Units of measurement](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo#unit-measurements). | +| status | The current status of the function. | +| status_details | The detailed status of the function. | + +### Data source: ibm_code_engine_job ```hcl -data "ibm_code_engine_binding" "code_engine_binding_instance" { - project_id = var.code_engine_project_id - binding_id = var.code_engine_binding_id +data "ibm_code_engine_job" "code_engine_job_instance" { + project_id = var.data_code_engine_job_project_id + name = var.data_code_engine_job_name } ``` -code_engine_domain_mapping data source: +#### Inputs + +| Name | Description | Type | Required | +|------|-------------|------|---------| +| project_id | The ID of the project. | `string` | true | +| name | The name of your job. | `string` | true | + +#### Outputs + +| Name | Description | +|------|-------------| +| build | Reference to a build that is associated with the job. | +| build_run | Reference to a build run that is associated with the job. | +| created_at | The timestamp when the resource was created. | +| entity_tag | The version of the job instance, which is used to achieve optimistic locking. | +| href | When you provision a new job, a URL is created identifying the location of the instance. | +| image_reference | The name of the image that is used for this job. The format is `REGISTRY/NAMESPACE/REPOSITORY:TAG` where `REGISTRY` and `TAG` are optional. If `REGISTRY` is not specified, the default is `docker.io`. If `TAG` is not specified, the default is `latest`. If the image reference points to a registry that requires authentication, make sure to also specify the property `image_secret`. | +| image_secret | The name of the image registry access secret. The image registry access secret is used to authenticate with a private registry when you download the container image. If the image reference points to a registry that requires authentication, the job / job runs will be created but submitted job runs will fail, until this property is provided, too. This property must not be set on a job run, which references a job template. | +| region | The region of the project the resource is located in. Possible values: 'au-syd', 'br-sao', 'ca-tor', 'eu-de', 'eu-gb', 'jp-osa', 'jp-tok', 'us-east', 'us-south'. | +| resource_type | The type of the job. | +| run_arguments | Set arguments for the job that are passed to start job run containers. If not specified an empty string array will be applied and the arguments specified by the container image, will be used to start the container. | +| run_as_user | The user ID (UID) to run the job. | +| run_commands | Set commands for the job that are passed to start job run containers. If not specified an empty string array will be applied and the command specified by the container image, will be used to start the container. | +| run_env_variables | References to config maps, secrets or literal values, which are exposed as environment variables in the job run. | +| run_mode | The mode for runs of the job. Valid values are `task` and `daemon`. In `task` mode, the `max_execution_time` and `retry_limit` properties apply. In `daemon` mode, since there is no timeout and failed instances are restarted indefinitely, the `max_execution_time` and `retry_limit` properties are not allowed. | +| run_service_account | The name of the service account. For built-in service accounts, you can use the shortened names `manager`, `none`, `reader`, and `writer`. This property must not be set on a job run, which references a job template. | +| run_volume_mounts | Optional mounts of config maps or secrets. | +| scale_array_spec | Define a custom set of array indices as a comma-separated list containing single values and hyphen-separated ranges, such as 5,12-14,23,27. Each instance gets its array index value from the environment variable JOB_INDEX. The number of unique array indices that you specify with this parameter determines the number of job instances to run. | +| scale_cpu_limit | Optional amount of CPU set for the instance of the job. For valid values see [Supported memory and CPU combinations](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo). | +| scale_ephemeral_storage_limit | Optional amount of ephemeral storage to set for the instance of the job. The amount specified as ephemeral storage, must not exceed the amount of `scale_memory_limit`. The units for specifying ephemeral storage are Megabyte (M) or Gigabyte (G), whereas G and M are the shorthand expressions for GB and MB. For more information see [Units of measurement](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo#unit-measurements). | +| scale_max_execution_time | The maximum execution time in seconds for runs of the job. This property can only be specified if `run_mode` is `task`. | +| scale_memory_limit | Optional amount of memory set for the instance of the job. For valid values see [Supported memory and CPU combinations](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo). The units for specifying memory are Megabyte (M) or Gigabyte (G), whereas G and M are the shorthand expressions for GB and MB. For more information see [Units of measurement](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo#unit-measurements). | +| scale_retry_limit | The number of times to rerun an instance of the job before the job is marked as failed. This property can only be specified if `run_mode` is `task`. | + +### Data source: ibm_code_engine_secret ```hcl -data "ibm_code_engine_domain_mapping" "code_engine_domain_mapping_instance" { - project_id = var.code_engine_project_id - name = var.code_engine_domain_mapping_name +data "ibm_code_engine_secret" "code_engine_secret_instance" { + project_id = var.data_code_engine_secret_project_id + name = var.data_code_engine_secret_name } ``` -## Inputs +#### Inputs | Name | Description | Type | Required | |------|-------------|------|---------| -| ibmcloud\_api\_key | IBM Cloud API key | `string` | true | | project_id | The ID of the project. | `string` | true | -| image_reference | The name of the image that is used for this app or job. The format is `REGISTRY/NAMESPACE/REPOSITORY:TAG` where `REGISTRY` and `TAG` are optional. If `REGISTRY` is not specified, the default is `docker.io`. If `TAG` is not specified, the default is `latest`. If the image reference points to a registry that requires authentication, make sure to also specify the property `image_secret`. | `string` | true | -| name | The name of the resource. | `string` | true | -| image_port | Optional port the app listens on. While the app will always be exposed via port `443` for end users, this port is used to connect to the port that is exposed by the container image. | `number` | false | -| image_secret | Optional name of the image registry access secret. The image registry access secret is used to authenticate with a private registry when you download the container image. If the image reference points to a registry that requires authentication, the app will be created but cannot reach the ready status, until this property is provided, too. | `string` | false | -| managed_domain_mappings | Optional value controlling which of the system managed domain mappings will be setup for the application. Valid values are 'local_public', 'local_private' and 'local'. Visibility can only be 'local_private' if the project supports application private visibility. | `string` | false | -| run_arguments | Optional arguments for the app that are passed to start the container. If not specified an empty string array will be applied and the arguments specified by the container image, will be used to start the container. | `list(string)` | false | -| run_as_user | Optional user ID (UID) to run the app/job (e.g., `1001`). | `number` | false | -| run_commands | Optional commands for the app/job that are passed to start the container. If not specified an empty string array will be applied and the command specified by the container image, will be used to start the container. | `list(string)` | false | -| run_env_variables | Optional references to config maps, secrets or literal values that are exposed as environment variables within the running application. | `list()` | false | -| run_service_account | Optional name of the service account. For built-in service accounts, you can use the shortened names `manager` , `none`, `reader`, and `writer`. | `string` | false | -| run_volume_mounts | Optional mounts of config maps or a secrets. | `list()` | false | -| scale_concurrency | Optional maximum number of requests that can be processed concurrently per instance. | `number` | false | -| scale_concurrency_target | Optional threshold of concurrent requests per instance at which one or more additional instances are created. Use this value to scale up instances based on concurrent number of requests. This option defaults to the value of the `scale_concurrency` option, if not specified. | `number` | false | -| scale_cpu_limit | Optional number of CPU set for the instance of the app/job. For valid values see [Supported memory and CPU combinations](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo). | `string` | false | -| scale_down_delay | Optional amount of time in seconds that delays the scale down behavior for an app instance. | `number` | false | -| scale_ephemeral_storage_limit | Optional amount of ephemeral storage to set for the instance of the app. The amount specified as ephemeral storage, must not exceed the amount of `scale_memory_limit`. The units for specifying ephemeral storage are Megabyte (M) or Gigabyte (G), whereas G and M are the shorthand expressions for GB and MB. For more information see [Units of measurement](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo#unit-measurements). | `string` | false | -| scale_initial_instances | Optional initial number of instances that are created upon app creation or app update. | `number` | false | -| scale_max_instances | Optional maximum number of instances for this app. If you set this value to `0`, this property does not set a upper scaling limit. However, the app scaling is still limited by the project quota for instances. See [Limits and quotas for Code Engine](https://cloud.ibm.com/docs/codeengine?topic=codeengine-limits). | `number` | false | -| scale_memory_limit | Optional amount of memory set for the instance of the app. For valid values see [Supported memory and CPU combinations](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo). The units for specifying memory are Megabyte (M) or Gigabyte (G), whereas G and M are the shorthand expressions for GB and MB. For more information see [Units of measurement](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo#unit-measurements). | `string` | false | -| scale_min_instances | Optional minimum number of instances for this app. If you set this value to `0`, the app will scale down to zero, if not hit by any request for some time. | `number` | false | -| scale_request_timeout | Optional amount of time in seconds that is allowed for a running app to respond to a request. | `number` | false | -| component | A reference to another component. | `` | true | -| prefix | Optional value that is set as prefix in the component that is bound. Will be generated if not provided. | `string` | true | -| secret_name | The service access secret that is binding to a component. | `string` | true | -| output_image | The name of the image. | `string` | true | -| output_secret | The secret that is required to access the image registry. Make sure that the secret is granted with push permissions towards the specified container registry namespace. | `string` | true | -| strategy_type | The strategy to use for building the image. | `string` | true | -| source_context_dir | Option directory in the repository that contains the buildpacks file or the Dockerfile. | `string` | false | -| source_revision | Commit, tag, or branch in the source repository to pull. This field is optional if the `source_type` is `git` and uses the HEAD of default branch if not specified. If the `source_type` value is `local`, this field must be omitted. | `string` | false | -| source_secret | Name of the secret that is used access the repository source. This field is optional if the `source_type` is `git`. Additionally, if the `source_url` points to a repository that requires authentication, the build will be created but cannot access any source code, until this property is provided, too. If the `source_type` value is `local`, this field must be omitted. | `string` | false | -| source_type | Specifies the type of source to determine if your build source is in a repository or based on local source code.* local - For builds from local source code.* git - For builds from git version controlled source code. | `string` | false | -| source_url | The URL of the code repository. This field is required if the `source_type` is `git`. If the `source_type` value is `local`, this field must be omitted. If the repository is publicly available you can provide a 'https' URL like `https://github.com/IBM/CodeEngine`. If the repository requires authentication, you need to provide a 'ssh' URL like `git@github.com:IBM/CodeEngine.git` along with a `source_secret` that points to a secret of format `ssh_auth`. | `string` | false | -| strategy_size | Optional size for the build, which determines the amount of resources used. Build sizes are `small`, `medium`, `large`, `xlarge`. | `string` | false | -| strategy_spec_file | Optional path to the specification file that is used for build strategies for building an image. | `string` | false | -| timeout | The maximum amount of time, in seconds, that can pass before the build must succeed or fail. | `number` | false | -| data | The key-value pair for the config map. Values must be specified in `KEY=VALUE` format. Each `KEY` field must consist of alphanumeric characters, `-`, `_` or `.` and must not be exceed a max length of 253 characters. Each `VALUE` field can consists of any character and must not be exceed a max length of 1048576 characters. | `map(string)` | false | -| image_reference | The name of the image that is used for this job. The format is `REGISTRY/NAMESPACE/REPOSITORY:TAG` where `REGISTRY` and `TAG` are optional. If `REGISTRY` is not specified, the default is `docker.io`. If `TAG` is not specified, the default is `latest`. If the image reference points to a registry that requires authentication, make sure to also specify the property `image_secret`. | `string` | true | -| image_secret | The name of the image registry access secret. The image registry access secret is used to authenticate with a private registry when you download the container image. If the image reference points to a registry that requires authentication, the job / job runs will be created but submitted job runs will fail, until this property is provided, too. This property must not be set on a job run, which references a job template. | `string` | false | -| run_mode | The mode for runs of the job. Valid values are `task` and `daemon`. In `task` mode, the `scale_max_execution_time` and `scale_retry_limit` properties apply. In `daemon` mode, since there is no timeout and failed instances are restarted indefinitely, the `scale_max_execution_time` and `scale_retry_limit` properties are not allowed. | `string` | false | -| scale_array_spec | Define a custom set of array indices as comma-separated list containing single values and hyphen-separated ranges like `5,12-14,23,27`. Each instance can pick up its array index via environment variable `JOB_INDEX`. The number of unique array indices specified here determines the number of job instances to run. | `string` | false | -| scale_max_execution_time | The maximum execution time in seconds for runs of the job. This property can only be specified if `run_mode` is `task`. | `number` | false | -| scale_memory_limit | Optional amount of memory set for the instance of the job. For valid values see [Supported memory and CPU combinations](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo). The units for specifying memory are Megabyte (M) or Gigabyte (G), whereas G and M are the shorthand expressions for GB and MB. For more information see [Units of measurement](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo#unit-measurements). | `string` | false | -| scale_retry_limit | The number of times to rerun an instance of the job before the job is marked as failed. This property can only be specified if `run_mode` is `task`. | `number` | false | -| resource_group_id | Optional ID of the resource group for your project deployment. If this field is not defined, the default resource group of the account will be used. | `string` | false | -| format | Specify the format of the secret. | `string` | true | -| service_access | Properties for Service Access Secret Prototypes. | `` | false | -| tls_secret | The name of the TLS secret that holds the certificate and private key of the domain mapping. | `string` | true | +| name | The name of your secret. | `string` | true | -## Outputs +#### Outputs | Name | Description | |------|-------------| -| code_engine_project | code_engine_project object | -| code_engine_app | code_engine_app object | -| code_engine_binding | code_engine_binding object | -| code_engine_build | code_engine_build object | -| code_engine_config_map | code_engine_config_map object | -| code_engine_domain_mapping | code_engine_domain_mapping object | -| code_engine_job | code_engine_job object | -| code_engine_secret | code_engine_secret object | +| created_at | The timestamp when the resource was created. | +| data | Data container that allows to specify config parameters and their values as a key-value map. Each key field must consist of alphanumeric characters, `-`, `_` or `.` and must not exceed a max length of 253 characters. Each value field can consists of any character and must not exceed a max length of 1048576 characters. | +| entity_tag | The version of the secret instance, which is used to achieve optimistic locking. | +| format | Specify the format of the secret. | +| href | When you provision a new secret, a URL is created identifying the location of the instance. | +| region | The region of the project the resource is located in. Possible values: 'au-syd', 'br-sao', 'ca-tor', 'eu-de', 'eu-gb', 'jp-osa', 'jp-tok', 'us-east', 'us-south'. | +| resource_type | The type of the secret. | +| service_access | Properties for Service Access Secrets. | +| service_operator | Properties for the IBM Cloud Operator Secret. | diff --git a/examples/ibm-code-engine/main.tf b/examples/ibm-code-engine/main.tf index e196dbfd81..bbb3ecb3e2 100644 --- a/examples/ibm-code-engine/main.tf +++ b/examples/ibm-code-engine/main.tf @@ -28,7 +28,7 @@ resource "ibm_code_engine_config_map" "code_engine_config_map_instance" { } // Provision code_engine_secret resource instance -resource "ibm_code_engine_secret" "code_engine_secret_generic" { +resource "ibm_code_engine_secret" "code_engine_secret_instance" { project_id = ibm_code_engine_project.code_engine_project_instance.project_id name = var.code_engine_secret_name format = var.code_engine_secret_format @@ -83,6 +83,14 @@ resource "ibm_code_engine_secret" "code_engine_secret_service_access" { } } +// Provision code_engine_secret resource instance for format tls +resource "ibm_code_engine_secret" "code_engine_secret_tls_instance" { + project_id = ibm_code_engine_project.code_engine_project_instance.project_id + name = var.code_engine_secret_tls_name + format = "tls" + data = local.tls_secret_data +} + // Provision code_engine_binding resource instance resource "ibm_code_engine_binding" "code_engine_binding_instance" { project_id = ibm_code_engine_project.code_engine_project_instance.project_id @@ -102,7 +110,19 @@ resource "ibm_code_engine_domain_mapping" "code_engine_domain_mapping_instance" name = ibm_code_engine_app.code_engine_app_instance.name resource_type = ibm_code_engine_app.code_engine_app_instance.resource_type } - tls_secret = ibm_code_engine_secret.code_engine_secret_instance.name + tls_secret = ibm_code_engine_secret.code_engine_secret_tls_instance.name + + depends_on = [ + ibm_code_engine_app.code_engine_app_instance, + ] +} + +// Provision code_engine_function resource instance +resource "ibm_code_engine_function" "code_engine_function_instance" { + project_id = ibm_code_engine_project.code_engine_project_instance.project_id + name = var.code_engine_function_name + runtime = var.code_engine_function_runtime + code_reference = local.function_code_reference } ////////////////// @@ -154,3 +174,19 @@ data "ibm_code_engine_domain_mapping" "code_engine_domain_mapping_data" { project_id = data.ibm_code_engine_project.code_engine_project_data.project_id name = var.code_engine_domain_mapping_name } + +// Create code_engine_function data source +data "ibm_code_engine_function" "code_engine_function_data" { + project_id = data.ibm_code_engine_project.code_engine_project_data.project_id + name = var.code_engine_function_name +} + +////////////////// +// Locals +locals { + tls_secret_data = { + tls_key = file(var.code_engine_secret_tls_key_file_path) + tls_cert = file(var.code_engine_secret_tls_crt_file_path) + } + function_code_reference = format("data:text/plain;base64,%s", filebase64(var.code_engine_function_code_reference_file_path)) +} diff --git a/examples/ibm-code-engine/outputs.tf b/examples/ibm-code-engine/outputs.tf index 7126482655..ebc5c0e180 100644 --- a/examples/ibm-code-engine/outputs.tf +++ b/examples/ibm-code-engine/outputs.tf @@ -48,3 +48,9 @@ output "ibm_code_engine_domain_mapping" { value = ibm_code_engine_domain_mapping.code_engine_domain_mapping_instance description = "code_engine_domain_mapping resource instance" } +// This allows code_engine_function data to be referenced by other resources and the terraform CLI +// Modify this if only certain data should be exposed +output "ibm_code_engine_function" { + value = ibm_code_engine_function.code_engine_function_instance + description = "code_engine_function resource instance" +} diff --git a/examples/ibm-code-engine/variables.tf b/examples/ibm-code-engine/variables.tf index 86f1b0a770..0c7734109b 100644 --- a/examples/ibm-code-engine/variables.tf +++ b/examples/ibm-code-engine/variables.tf @@ -17,7 +17,7 @@ variable "code_engine_project_name" { // Resource arguments for code_engine_app variable "code_engine_app_image_reference" { - description = "The name of the image that is used for this job. The format is `REGISTRY/NAMESPACE/REPOSITORY:TAG` where `REGISTRY` and `TAG` are optional. If `REGISTRY` is not specified, the default is `docker.io`. If `TAG` is not specified, the default is `latest`. If the image reference points to a registry that requires authentication, make sure to also specify the property `image_secret`." + description = "The name of the image that is used for this app. The format is `REGISTRY/NAMESPACE/REPOSITORY:TAG` where `REGISTRY` and `TAG` are optional. If `REGISTRY` is not specified, the default is `docker.io`. If `TAG` is not specified, the default is `latest`. If the image reference points to a registry that requires authentication, make sure to also specify the property `image_secret`." type = string default = "icr.io/codeengine/helloworld" } @@ -125,6 +125,37 @@ variable "code_engine_domain_mapping_name" { type = string } +// Resource arguments for code_engine_function +variable "code_engine_function_name" { + description = "The name of the function." + type = string + default = "my-function" +} +variable "code_engine_function_runtime" { + description = "The runtime of the function." + type = string + default = "nodejs-20" +} +variable "code_engine_function_code_reference_file_path" { + description = "The path to a file containing the source code." + type = string +} + +// Resource arguments for code_engine_secret with format tls +variable "code_engine_secret_tls_name" { + description = "The name of the tls secret." + type = string + default = "my-tls-secret" +} +variable "code_engine_secret_tls_key_file_path" { + description = "The path to the .key file containing the private key of the TLS certificate." + type = string +} +variable "code_engine_secret_tls_crt_file_path" { + description = "The path to the .crt file containing the signed TLS certificate." + type = string +} + // Data source arguments for code_engine_project variable "code_engine_project_id" { description = "The ID of the project." diff --git a/examples/ibm-configuration-aggregator/README.md b/examples/ibm-configuration-aggregator/README.md new file mode 100644 index 0000000000..83b88ab517 --- /dev/null +++ b/examples/ibm-configuration-aggregator/README.md @@ -0,0 +1,123 @@ +# Examples for Configuration Aggregator + +These examples illustrate how to use the resources and data sources associated with Configuration Aggregator. + +The following resources are supported: +* ibm_config_aggregator_settings + +The following data sources are supported: +* ibm_config_aggregator_configurations +* ibm_config_aggregator_settings +* ibm_config_aggregator_resource_collection_status + +## Usage + +To run this example, execute the following commands: + +```bash +$ terraform init +$ terraform plan +$ terraform apply +``` + +Run `terraform destroy` when you don't need these resources. + +## Configuration Aggregator resources + +### Resource: ibm_config_aggregator_settings + +```hcl +resource "ibm_config_aggregator_settings" "config_aggregator_settings_instance" { + resource_collection_enabled = var.config_aggregator_settings_resource_collection_enabled + trusted_profile_id = var.config_aggregator_settings_trusted_profile_id + regions = var.config_aggregator_settings_regions + additional_scope = var.config_aggregator_settings_additional_scope +} +``` + +#### Inputs + +| Name | Description | Type | Required | +|------|-------------|------|---------| +| ibmcloud\_api\_key | IBM Cloud API key | `string` | true | +| resource_collection_enabled | The field denoting if the resource collection is enabled. | `bool` | false | +| trusted_profile_id | The trusted profile id that provides Reader access to the App Configuration instance to collect resource metadata. | `string` | false | +| regions | The list of regions across which the resource collection is enabled. | `list(string)` | false | +| additional_scope | The additional scope that enables resource collection for Enterprise acccounts. | `list()` | false | + +## Configuration Aggregator data sources + +### Data source: ibm_config_aggregator_configurations + +```hcl +data "ibm_config_aggregator_configurations" "config_aggregator_configurations_instance" { + config_type = var.config_aggregator_configurations_config_type + service_name = var.config_aggregator_configurations_service_name + resource_group_id = var.config_aggregator_configurations_resource_group_id + location = var.config_aggregator_configurations_location + resource_crn = var.config_aggregator_configurations_resource_crn +} +``` + +#### Inputs + +| Name | Description | Type | Required | +|------|-------------|------|---------| +| config_type | The type of resource configuration that are to be retrieved. | `string` | false | +| service_name | The name of the IBM Cloud service for which resources are to be retrieved. | `string` | false | +| resource_group_id | The resource group id of the resources. | `string` | false | +| location | The location or region in which the resources are created. | `string` | false | +| resource_crn | The crn of the resource. | `string` | false | + +#### Outputs + +| Name | Description | +|------|-------------| +| prev | The reference to the previous page of entries. | +| configs | Array of resource configurations. | + +### Data source: ibm_config_aggregator_settings + +```hcl +data "ibm_config_aggregator_settings" "config_aggregator_settings_instance" { +} +``` + +#### Outputs + +| Name | Description | +|------|-------------| +| resource_collection_enabled | The field to check if the resource collection is enabled. | +| trusted_profile_id | The trusted profile ID that provides access to App Configuration instance to retrieve resource metadata. | +| last_updated | The last time the settings was last updated. | +| regions | Regions for which the resource collection is enabled. | +| additional_scope | The additional scope that enables resource collection for Enterprise acccounts. | + +### Data source: ibm_config_aggregator_resource_collection_status + +```hcl +data "ibm_config_aggregator_resource_collection_status" "config_aggregator_resource_collection_status_instance" { +} +``` + +#### Outputs + +| Name | Description | +|------|-------------| +| last_config_refresh_time | The timestamp at which the configuration was last refreshed. | +| status | Status of the resource collection. | + +## Assumptions + +1. TODO + +## Notes + +1. TODO + +## Requirements + +| Name | Version | +|------|---------| +| terraform | ~> 1.9.6 | + diff --git a/examples/ibm-configuration-aggregator/main.tf b/examples/ibm-configuration-aggregator/main.tf new file mode 100644 index 0000000000..ce47ce52c7 --- /dev/null +++ b/examples/ibm-configuration-aggregator/main.tf @@ -0,0 +1,41 @@ + +provider "ibm" { + ibmcloud_api_key = var.ibmcloud_api_key +} + +// Provision config_aggregator_settings resource instance +resource "ibm_config_aggregator_settings" "config_aggregator_settings_instance" { + resource_collection_enabled = var.config_aggregator_settings_resource_collection_enabled + trusted_profile_id = var.config_aggregator_settings_trusted_profile_id + regions = var.config_aggregator_settings_regions +} + + +// Data source is not linked to a resource instance +// Uncomment if an existing data source instance exists +/* +// Create config_aggregator_configurations data source +data "ibm_config_aggregator_configurations" "config_aggregator_configurations_instance" { + config_type = var.config_aggregator_configurations_config_type + service_name = var.config_aggregator_configurations_service_name + resource_group_id = var.config_aggregator_configurations_resource_group_id + location = var.config_aggregator_configurations_location + resource_crn = var.config_aggregator_configurations_resource_crn +} +*/ + +// Data source is not linked to a resource instance +// Uncomment if an existing data source instance exists +/* +// Create config_aggregator_settings data source +data "ibm_config_aggregator_settings" "config_aggregator_settings_instance" { +} +*/ + +// Data source is not linked to a resource instance +// Uncomment if an existing data source instance exists +/* +// Create config_aggregator_resource_collection_status data source +data "ibm_config_aggregator_resource_collection_status" "config_aggregator_resource_collection_status_instance" { +} +*/ diff --git a/examples/ibm-configuration-aggregator/outputs.tf b/examples/ibm-configuration-aggregator/outputs.tf new file mode 100644 index 0000000000..cb38ff8b1e --- /dev/null +++ b/examples/ibm-configuration-aggregator/outputs.tf @@ -0,0 +1,10 @@ +// This output allows config_aggregator_settings data to be referenced by other resources and the terraform CLI +// Modify this output if only certain data should be exposed +output "config_aggregator_settings" { + value = { + additional_scope = [] + regions = ["all"] + resource_collection_enabled = ibm_config_aggregator_settings.config_aggregator_settings_instance.resource_collection_enabled + trusted_profile_id = ibm_config_aggregator_settings.config_aggregator_settings_instance.trusted_profile_id + } +} \ No newline at end of file diff --git a/examples/ibm-configuration-aggregator/variables.tf b/examples/ibm-configuration-aggregator/variables.tf new file mode 100644 index 0000000000..0c2a2ecf2f --- /dev/null +++ b/examples/ibm-configuration-aggregator/variables.tf @@ -0,0 +1,50 @@ +variable "ibmcloud_api_key" { + description = "IBM Cloud API key" + type = string +} + +// Resource arguments for config_aggregator_settings +variable "config_aggregator_settings_resource_collection_enabled" { + description = "The field denoting if the resource collection is enabled." + type = bool + default = true +} +variable "config_aggregator_settings_trusted_profile_id" { + description = "The trusted profile id that provides Reader access to the App Configuration instance to collect resource metadata." + type = string + default = "Profile-7d935dbb-7ee5-44e1-9e85-38e65d722398" +} +variable "config_aggregator_settings_regions" { + description = "The list of regions across which the resource collection is enabled." + type = list(string) + default = ["all"] +} + +// Data source arguments for config_aggregator_configurations +variable "config_aggregator_configurations_config_type" { + description = "The type of resource configuration that are to be retrieved." + type = string + default = "placeholder" +} +variable "config_aggregator_configurations_service_name" { + description = "The name of the IBM Cloud service for which resources are to be retrieved." + type = string + default = "placeholder" +} +variable "config_aggregator_configurations_resource_group_id" { + description = "The resource group id of the resources." + type = string + default = "placeholder" +} +variable "config_aggregator_configurations_location" { + description = "The location or region in which the resources are created." + type = string + default = "placeholder" +} +variable "config_aggregator_configurations_resource_crn" { + description = "The crn of the resource." + type = string + default = "placeholder" +} + + diff --git a/examples/ibm-configuration-aggregator/versions.tf b/examples/ibm-configuration-aggregator/versions.tf new file mode 100644 index 0000000000..0b29488aaf --- /dev/null +++ b/examples/ibm-configuration-aggregator/versions.tf @@ -0,0 +1,7 @@ +terraform { + required_providers { + ibm = { + source = "IBM-Cloud/ibm" + } + } +} \ No newline at end of file diff --git a/examples/ibm-cos-bucket/README.md b/examples/ibm-cos-bucket/README.md index 91d220a059..694b279549 100644 --- a/examples/ibm-cos-bucket/README.md +++ b/examples/ibm-cos-bucket/README.md @@ -510,6 +510,36 @@ resource ibm_cos_bucket_website_configuration "website_configuration" { } } ``` +## ibm_cos_bucket_lifecycle_configuration + +Provides an independent resource to manage the lifecycle configuration for a bucket.For more information please refer to [`ibm_cos_bucket_lifecycle_configuration`](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs/resources/ibm_cos_bucket_lifecycle_configuration) + +## Example usage + +```terraform +resource "ibm_cos_bucket" "cos_bucket" { + bucket_name = var.bucket_name + resource_instance_id = ibm_resource_instance.cos_instance.id + region_location = var.regional_loc + storage_class = var.standard_storage_class + +} +resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.cos_bucket.crn + bucket_location = ibm_cos_bucket.cos_bucket.region_location + lifecycle_rule { + expiration{ + days = 1 + } + filter { + prefix = "foo" + } + rule_id = "id" + status = "enable" + + } +} +``` ## Requirements @@ -582,4 +612,15 @@ resource ibm_cos_bucket_website_configuration "website_configuration" { | http_redirect_code | HTTP redirect code to use on the response. | `string` | No | replace_key_with | Specific object key to use in the redirect request. | `string` | No | replace_key_prefix_with | Object key prefix to use in the redirect request. | `string` | No +| days | Days after which the lifecycle rule expiration will be applied on the object. | `int` | No +| date | Date after which the lifecycle rule expiration will be applied on the object. | `int` | No +| expire_object_delete_marker | Indicates whether ibm will remove a delete marker with no noncurrent versions. | `bool` | No +| days | Days after which the lifecycle rule transition will be applied on the object. | `int` | No +| date | Date after which the lifecycle rule transition will be applied on the object. | `int` | No +| storage_class | Class of storage used to store the object. | `string` | No +| noncurrent_days | Number of days an object is noncurrent before lifecycle action is performed. | `int` | No +| days_after_initiatiob | Number of days after which incomplete multipart uploads are aborted. | `int` | No +| id | Unique identifier for lifecycle rule. | `int` | Yes +| status | Whether the rule is currently being applied. | `int` | Yes + {: caption="inputs"} diff --git a/examples/ibm-cos-bucket/main.tf b/examples/ibm-cos-bucket/main.tf index 8e83a6f669..0e97cbe65e 100644 --- a/examples/ibm-cos-bucket/main.tf +++ b/examples/ibm-cos-bucket/main.tf @@ -297,7 +297,7 @@ resource "ibm_kms_key" "key" { force_delete = true } -resource "ibm_cos_bucket" "hpcs-enabled" { +resource "ibm_cos_bucket" "hpcs-enable" { depends_on = [ibm_iam_authorization_policy.policy2] bucket_name = var.bucket_name resource_instance_id = ibm_resource_instance.cos_instance.id @@ -307,7 +307,7 @@ resource "ibm_cos_bucket" "hpcs-enabled" { } //HPCS - UKO plan -resource "ibm_cos_bucket" "hpcs-uko-enabled" { +resource "ibm_cos_bucket" "hpcs-uko-enable" { depends_on = [ibm_iam_authorization_policy.policy2] bucket_name = var.bucket_name resource_instance_id = ibm_resource_instance.cos_instance.id @@ -386,7 +386,7 @@ resource ibm_cos_bucket_object_lock_configuration "objectlock" { bucket_crn = ibm_cos_bucket.bucket.crn bucket_location = var.regional_loc object_lock_configuration{ - object_lock_enabled = "Enabled" + object_lock_enable = "Enabled" object_lock_rule{ default_retention{ mode = "COMPLIANCE" @@ -500,3 +500,146 @@ resource ibm_cos_bucket_website_configuration "website_configuration" { EOF } } + + +#COS Lifecycle Configuration + +# Adding lifecycle configuration with expiration and prefix filter. + +resource "ibm_cos_bucket" "cos_bucket_lifecycle_expiration" { + bucket_name = var.bucket_name + resource_instance_id = ibm_resource_instance.cos_instance.id + region_location = var.regional_loc + storage_class = var.standard_storage_class + +} +resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.cos_bucket.crn + bucket_location = ibm_cos_bucket.cos_bucket.region_location + lifecycle_rule { + expiration{ + days = 1 + } + filter { + prefix = "foo" + } + rule_id = "id" + status = "enable" + + } +} + + + +# Adding lifecycle configuration with transition. + +resource "ibm_cos_bucket" "cos_bucket_transition" { + bucket_name = var.bucket_name + resource_instance_id = ibm_resource_instance.cos_instance.id + region_location = var.regional_loc + storage_class = var.standard_storage_class + +} +resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle_transition" { + bucket_crn = ibm_cos_bucket.cos_bucket.crn + bucket_location = ibm_cos_bucket.cos_bucket.region_location + lifecycle_rule { + transition{ + days = 1 + storage_class = "GLACIER" + } + filter { + prefix = "" + } + rule_id = "id" + status = "enable" + + } +} + + +# Adding lifecycle configuration with abort incomplete multipart upload. + +resource "ibm_cos_bucket" "cos_bucket_abort_incomplete" { + bucket_name = var.bucket_name + resource_instance_id = ibm_resource_instance.cos_instance.id + region_location = var.regional_loc + storage_class = var.standard_storage_class + +} +resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle_abort_incomplete" { + bucket_crn = ibm_cos_bucket.cos_bucket.crn + bucket_location = ibm_cos_bucket.cos_bucket.region_location + lifecycle_rule { + abort_incomplete_multipart_upload{ + days_after_initiation = 1 + } + filter { + prefix = "" + } + rule_id = "id" + status = "enable" + + } +} + + +# Adding lifecycle configuration with non current version expiration. + +resource "ibm_cos_bucket" "cos_bucket_lifecycle_version_expiration" { + bucket_name = var.bucket_name + resource_instance_id = ibm_resource_instance.cos_instance.id + region_location = var.regional_loc + storage_class = var.standard_storage_class + +} +resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle_new" { + bucket_crn = ibm_cos_bucket.cos_bucket.crn + bucket_location = ibm_cos_bucket.cos_bucket.region_location + lifecycle_rule { + noncurrent_version_expiration{ + noncurrent_days = "1" + } + filter { + prefix = "" + } + rule_id = "id" + status = "enable" + + } +} + +# Adding lifecycle configuration with multiple rules + +resource "ibm_cos_bucket" "cos_bucket_lifecycle" { + bucket_name = var.bucket_name + resource_instance_id = ibm_resource_instance.cos_instance.id + region_location = var.regional_loc + storage_class = var.standard_storage_class +} + +resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle_config" { + bucket_crn = ibm_cos_bucket.cos_bucket.crn + bucket_location = ibm_cos_bucket.cos_bucket.region_location + lifecycle_rule { + expiration{ + days = 1 + } + filter { + prefix = "foo" + } + rule_id = "id" + status = "enable" + } + lifecycle_rule { + expiration{ + days = 2 + } + filter { + prefix = "bar" + } + rule_id = "id2" + status = "enable" + } +} + diff --git a/examples/ibm-logs-routing/README.md b/examples/ibm-logs-routing/README.md index 8528d61348..afa5203bfe 100644 --- a/examples/ibm-logs-routing/README.md +++ b/examples/ibm-logs-routing/README.md @@ -28,12 +28,13 @@ Run `terraform destroy` when you don't need these resources. ```hcl resource "ibm_logs_router_tenant" "logs_router_tenant_instance" { name = var.logs_router_tenant_name + region = "us-east" targets { log_sink_crn = "crn:v1:bluemix:public:logdna:eu-de:a/7246b8fa0a174a71899f5affa4f18d78:3517d2ed-9429-af34-ad52-34278391cbc8::" name = "my-log-sink" parameters { host = "www.example.com" - port = 1 + port = 443 access_credential = "new-credential" } } @@ -46,6 +47,7 @@ resource "ibm_logs_router_tenant" "logs_router_tenant_instance" { |------|-------------|------|---------| | ibmcloud\_api\_key | IBM Cloud API key | `string` | true | | name | The name for this tenant. The name is regionally unique across all tenants in the account. | `string` | true | +| region | The region to onboard this tenant. | `string` | true | | targets | List of targets. | `list()` | true | | targets.log_sink_crn | CRN of the Mezmo or Cloud Logs instance to sends logs to | `string` | true | | targets.name | The name for this target. The name is regionally unique for this tenant. | `string` | true | @@ -70,6 +72,7 @@ resource "ibm_logs_router_tenant" "logs_router_tenant_instance" { ```hcl data "ibm_logs_router_tenants" "logs_router_tenants_instance" { name = var.logs_router_tenants_name + region = "us-east" } ``` @@ -77,7 +80,8 @@ data "ibm_logs_router_tenants" "logs_router_tenants_instance" { | Name | Description | Type | Required | |------|-------------|------|---------| -| name | Optional: The name of a tenant. | `string` | true | +| name | The name of a tenant. | `string` | true | +| region | The region to query the tenant. | `string` | true | #### Outputs @@ -90,7 +94,7 @@ data "ibm_logs_router_tenants" "logs_router_tenants_instance" { ```hcl data "ibm_logs_router_targets" "logs_router_targets_instance" { tenant_id = var.logs_router_targets_tenant_id - name = var.logs_router_targets_name + region = "us-east" } ``` @@ -99,6 +103,7 @@ data "ibm_logs_router_targets" "logs_router_targets_instance" { | Name | Description | Type | Required | |------|-------------|------|---------| | tenant_id | The instance ID of the tenant. | `` | true | +| region | The region where the tenant for this target exists, | `string` | true | | name | Optional: Name of the tenant target. | `string` | false | #### Outputs diff --git a/examples/ibm-logs-routing/main.tf b/examples/ibm-logs-routing/main.tf index fce3673817..410a7f40fa 100644 --- a/examples/ibm-logs-routing/main.tf +++ b/examples/ibm-logs-routing/main.tf @@ -6,31 +6,48 @@ provider "ibm" { // Provision logs_router_tenant resource instance resource "ibm_logs_router_tenant" "logs_router_tenant_instance" { name = var.logs_router_tenant_name + region = "us-east" targets { - log_sink_crn = "crn:v1:bluemix:public:logdna:eu-de:a/7246b8fa0a174a71899f5affa4f18d78:3517d2ed-9429-af34-ad52-34278391cbc8::" + log_sink_crn = "crn:v1:bluemix:public:logdna:us-east:a/7246b8fa0a174a71899f5affa4f18d78:3517d2ed-9429-af34-ad52-34278391cbc8::" name = "my-logdna-target" parameters { host = "www.example-1.com" - port = 80 + port = 443 access_credential = "new-cred" } } targets { - log_sink_crn = "crn:v1:bluemix:public:logs:eu-de:a/7246b8fa0a174a71899f5affa4f18d78:3517d2ed-9429-af34-ad52-34278391cbc8::" + log_sink_crn = "crn:v1:bluemix:public:logs:us-east:a/7246b8fa0a174a71899f5affa4f18d78:3517d2ed-9429-af34-ad52-34278391cbc8::" name = "my-cloud-logs-target" parameters { host = "www.example-2.com" - port = 80 + port = 443 + } + } +} + +resource "ibm_logs_router_tenant" "logs_router_tenant_instance_eu_de" { + name = "eu-de-tenant" + region = "eu-de" + targets { + log_sink_crn = "crn:v1:bluemix:public:logdna:eu-de:a/7246b8fa0a174a71899f5affa4f18d78:3517d2ed-9429-af34-ad52-34278391cbc8::" + name = "my-logdna-target" + parameters { + host = "www.example-1.com" + port = 443 + access_credential = "new-cred" } } } // Create logs_router_tenants data source data "ibm_logs_router_tenants" "logs_router_tenants_instance" { - name = ibm_logs_router_tenant.logs_router_tenant_instance_both.name + name = ibm_logs_router_tenant.logs_router_tenant_instance.name + region = ibm_logs_router_tenant.logs_router_tenant_instance.region } // Create logs_router_targets data source data "ibm_logs_router_targets" "logs_router_targets_instance" { - tenant_id = ibm_logs_router_tenant.logs_router_tenant_instance_both.id + tenant_id = ibm_logs_router_tenant.logs_router_tenant_instance.id + region = ibm_logs_router_tenant.logs_router_tenant_instance.region } \ No newline at end of file diff --git a/go.mod b/go.mod index b82d447ccc..c1b757f96f 100644 --- a/go.mod +++ b/go.mod @@ -14,9 +14,10 @@ require ( github.com/IBM/cloud-databases-go-sdk v0.7.0 github.com/IBM/cloudant-go-sdk v0.8.0 github.com/IBM/code-engine-go-sdk v0.0.0-20240126185534-a6e054aa01ed + github.com/IBM/configuration-aggregator-go-sdk v0.0.1 github.com/IBM/container-registry-go-sdk v1.1.0 github.com/IBM/continuous-delivery-go-sdk v1.6.0 - github.com/IBM/event-notifications-go-admin-sdk v0.8.0 + github.com/IBM/event-notifications-go-admin-sdk v0.9.0 github.com/IBM/eventstreams-go-sdk v1.4.0 github.com/IBM/go-sdk-core v1.1.0 github.com/IBM/go-sdk-core/v3 v3.2.4 @@ -27,7 +28,7 @@ require ( github.com/IBM/ibm-hpcs-uko-sdk v0.0.20-beta github.com/IBM/keyprotect-go-client v0.15.1 github.com/IBM/logs-go-sdk v0.3.0 - github.com/IBM/logs-router-go-sdk v1.0.3 + github.com/IBM/logs-router-go-sdk v1.0.5 github.com/IBM/mqcloud-go-sdk v0.1.0 github.com/IBM/networking-go-sdk v0.49.0 github.com/IBM/platform-services-go-sdk v0.68.1 @@ -35,11 +36,11 @@ require ( github.com/IBM/push-notifications-go-sdk v0.0.0-20210310100607-5790b96c47f5 github.com/IBM/sarama v1.41.2 github.com/IBM/scc-go-sdk/v5 v5.4.1 - github.com/IBM/schematics-go-sdk v0.2.3 - github.com/IBM/secrets-manager-go-sdk/v2 v2.0.5 + github.com/IBM/schematics-go-sdk v0.3.0 + github.com/IBM/secrets-manager-go-sdk/v2 v2.0.6 github.com/IBM/vmware-go-sdk v0.1.2 github.com/IBM/vpc-beta-go-sdk v0.6.0 - github.com/IBM/vpc-go-sdk v0.57.0 + github.com/IBM/vpc-go-sdk v0.58.0 github.com/ScaleFT/sshkeys v0.0.0-20200327173127-6142f742bca5 github.com/akamai/AkamaiOPEN-edgegrid-golang v1.2.2 github.com/akamai/AkamaiOPEN-edgegrid-golang/v5 v5.0.0 @@ -51,7 +52,7 @@ require ( github.com/google/go-cmp v0.6.0 github.com/google/uuid v1.6.0 github.com/hashicorp/go-uuid v1.0.3 - github.com/hashicorp/go-version v1.6.0 + github.com/hashicorp/go-version v1.7.0 github.com/hashicorp/terraform-plugin-sdk/v2 v2.29.0 github.com/jinzhu/copier v0.3.2 github.com/minsikl/netscaler-nitro-go v0.0.0-20170827154432-5b14ce3643e3 @@ -104,7 +105,7 @@ require ( github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/gabriel-vasile/mimetype v1.4.3 // indirect github.com/go-jose/go-jose/v3 v3.0.3 // indirect - github.com/go-logr/logr v1.3.0 // indirect + github.com/go-logr/logr v1.4.1 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-openapi/analysis v0.21.5 // indirect github.com/go-openapi/errors v0.22.0 // indirect @@ -176,6 +177,8 @@ require ( github.com/mitchellh/copystructure v1.2.0 // indirect github.com/mitchellh/go-testing-interface v1.14.1 // indirect github.com/mitchellh/go-wordwrap v1.0.0 // indirect + github.com/mitchellh/gox v1.0.1 // indirect + github.com/mitchellh/iochan v1.0.0 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/mitchellh/reflectwalk v1.0.2 // indirect github.com/moby/spdystream v0.2.0 // indirect diff --git a/go.sum b/go.sum index 1a10242539..001abecd86 100644 --- a/go.sum +++ b/go.sum @@ -132,14 +132,14 @@ github.com/IBM/cloud-databases-go-sdk v0.7.0 h1:prvLebKD1kcIk81D6yRhOr/TWp1VQJGL github.com/IBM/cloud-databases-go-sdk v0.7.0/go.mod h1:JYucI1PdwqbAd8XGdDAchxzxRP7bxOh1zUnseovHKsc= github.com/IBM/cloudant-go-sdk v0.8.0 h1:XzaqZFy5fm1Q9+iK52X5zRW39SHaahT9pf5SRgVTsTY= github.com/IBM/cloudant-go-sdk v0.8.0/go.mod h1:zDGBs8ideVtn9MehXbIQNI3852B68BsMtKJvq3iPn/Q= -github.com/IBM/code-engine-go-sdk v0.0.0-20240126185534-a6e054aa01ed h1:X0VrZW5ulbqxbOmy5JoZcH0A+tw80k0/ZmRZz1NqogM= -github.com/IBM/code-engine-go-sdk v0.0.0-20240126185534-a6e054aa01ed/go.mod h1:m4pD/58c6NVzlAFkN3XCYXpmDFmUyTG31ivLy/loyHQ= +github.com/IBM/code-engine-go-sdk v0.0.0-20240808131715-b9d168602dac h1:9Y5TB9Ar2SM6JPr2kM6c9pHSdSuHMDCIcbvTa/hNTj4= +github.com/IBM/code-engine-go-sdk v0.0.0-20240808131715-b9d168602dac/go.mod h1:sy4CocPPaCiS+T1znqVdw83dkoyxSMUFxkksqahUhbY= github.com/IBM/container-registry-go-sdk v1.1.0 h1:sYyknIod8R4RJZQqAheiduP6wbSTphE9Ag8ho28yXjc= github.com/IBM/container-registry-go-sdk v1.1.0/go.mod h1:4TwsCnQtVfZ4Vkapy/KPvQBKFc3VOyUZYkwRU4FTPrs= github.com/IBM/continuous-delivery-go-sdk v1.6.0 h1:eAL/jIWHrDFlWDF+Qd9Y5UN99Pr5Mjd/H/bvTbXUbz4= github.com/IBM/continuous-delivery-go-sdk v1.6.0/go.mod h1:nZdKUnubXNLo+zo28R4Rd+TGDqiJ/xoE8WO/A3kLw1E= -github.com/IBM/event-notifications-go-admin-sdk v0.8.0 h1:xk2CYTayQtKi6LSgGGFRxFJfWUxyM5SY8Rs64ducAhw= -github.com/IBM/event-notifications-go-admin-sdk v0.8.0/go.mod h1:OByvqfrNVxs7G6ggv8pwQCEVw10/TBJCLh7NM3z707w= +github.com/IBM/event-notifications-go-admin-sdk v0.9.0 h1:eaCd+GkxhNyot+8rA9WkAQdlVYrRD20LYiXjEytFO6M= +github.com/IBM/event-notifications-go-admin-sdk v0.9.0/go.mod h1:OByvqfrNVxs7G6ggv8pwQCEVw10/TBJCLh7NM3z707w= github.com/IBM/eventstreams-go-sdk v1.4.0 h1:yS/Ns29sBOe8W2tynQmz9HTKqQZ0ckse4Py5Oy/F2rM= github.com/IBM/eventstreams-go-sdk v1.4.0/go.mod h1:2tuAxaYLctfqfr5jvyqSrxxEQGMwYPm3yJGWSj85YVQ= github.com/IBM/go-sdk-core v1.1.0 h1:pV73lZqr9r1xKb3h08c1uNG3AphwoV5KzUzhS+pfEqY= @@ -167,8 +167,8 @@ github.com/IBM/keyprotect-go-client v0.15.1 h1:m4qzqF5zOumRxKZ8s7vtK7A/UV/D278L8 github.com/IBM/keyprotect-go-client v0.15.1/go.mod h1:asXtHwL/4uCHA221Vd/7SkXEi2pcRHDzPyyksc1DthE= github.com/IBM/logs-go-sdk v0.3.0 h1:FHzTCCMyp9DvQGXgkppzcOPywC4ggt7x8xu0MR5h8xI= github.com/IBM/logs-go-sdk v0.3.0/go.mod h1:yv/GCXC4/p+MZEeXl4xjZAOMvDAVRwu61WyHZFKFXQM= -github.com/IBM/logs-router-go-sdk v1.0.3 h1:VO64OpANNouxS/0kvUeBpENKWxYx3TYnoNzW8OycMb0= -github.com/IBM/logs-router-go-sdk v1.0.3/go.mod h1:tCN2vFgu5xG0ob9iJcxi5M4bJ6mWmu3nhmRPnvlwev0= +github.com/IBM/logs-router-go-sdk v1.0.5 h1:r0kC1+HfmSeQCD6zQTUp4PDI/zp4Ueo1Zo19ipHuNlw= +github.com/IBM/logs-router-go-sdk v1.0.5/go.mod h1:tCN2vFgu5xG0ob9iJcxi5M4bJ6mWmu3nhmRPnvlwev0= github.com/IBM/mqcloud-go-sdk v0.1.0 h1:fWt4uisg5GbbsfNmAxx5/6c5gQIPM+VrEsTtnimELeA= github.com/IBM/mqcloud-go-sdk v0.1.0/go.mod h1:LesMQlKHXvdks4jqQLZH7HfATY5lvTzHuwQU5+y7b2g= github.com/IBM/networking-go-sdk v0.49.0 h1:lPS34u3C0JVrbxH+Ulua76Nwl6Frv8BEfq6LRkyvOv0= @@ -183,16 +183,16 @@ github.com/IBM/sarama v1.41.2 h1:ZDBZfGPHAD4uuAtSv4U22fRZBgst0eEwGFzLj0fb85c= github.com/IBM/sarama v1.41.2/go.mod h1:xdpu7sd6OE1uxNdjYTSKUfY8FaKkJES9/+EyjSgiGQk= github.com/IBM/scc-go-sdk/v5 v5.4.1 h1:RXIuxOo9/hxkWyHCI69ae+KIJgSbXcAkJwTEl+fO3LQ= github.com/IBM/scc-go-sdk/v5 v5.4.1/go.mod h1:2xQTDgNXG5QMEfQxBDKB067z+5ha6OgcaKCTcdGDAo8= -github.com/IBM/schematics-go-sdk v0.2.3 h1:lgTt0Sbudii3cuSk1YSQgrtiZAXDbBABAoVj3eQuBrU= -github.com/IBM/schematics-go-sdk v0.2.3/go.mod h1:Tw2OSAPdpC69AxcwoyqcYYaGTTW6YpERF9uNEU+BFRQ= -github.com/IBM/secrets-manager-go-sdk/v2 v2.0.5 h1:VMc/Zd6RzB8j60CqZekkwYT2wQsCfrkGV2n01Gviuaw= -github.com/IBM/secrets-manager-go-sdk/v2 v2.0.5/go.mod h1:5kUgJ1dG9cdiAcPDqVz46m362bPnoqZQSth24NiowSg= +github.com/IBM/schematics-go-sdk v0.3.0 h1:Vwxw85SONflakiBsNHAfViKLyp9zJiH5/hh6SewOP5Q= +github.com/IBM/schematics-go-sdk v0.3.0/go.mod h1:Tw2OSAPdpC69AxcwoyqcYYaGTTW6YpERF9uNEU+BFRQ= +github.com/IBM/secrets-manager-go-sdk/v2 v2.0.6 h1:bF6bAdI4wDZSje6+Yx1mJxvirboxO+uMuKhzgfRCNxE= +github.com/IBM/secrets-manager-go-sdk/v2 v2.0.6/go.mod h1:XWYnbcc5vN1RnKwk/fCzfD8aZd7At/Y1/b6c+oDyliU= github.com/IBM/vmware-go-sdk v0.1.2 h1:5lKWFyInWz9e2hwGsoFTEoLa1jYkD30SReN0fQ10w9M= github.com/IBM/vmware-go-sdk v0.1.2/go.mod h1:2UGPBJju3jiv5VKKBBm9a5L6bzF/aJdKOKAzJ7HaOjA= github.com/IBM/vpc-beta-go-sdk v0.6.0 h1:wfM3AcW3zOM3xsRtZ+EA6+sESlGUjQ6Yf4n5QQyz4uc= github.com/IBM/vpc-beta-go-sdk v0.6.0/go.mod h1:fzHDAQIqH/5yJmYsKodKHLcqxMDT+yfH6vZjdiw8CQA= -github.com/IBM/vpc-go-sdk v0.57.0 h1:E8CPDpUE4z0cvvmFZzqUthMtGJx71Fne6vdvkjZdXfg= -github.com/IBM/vpc-go-sdk v0.57.0/go.mod h1:swmxiYLT+OfBsBYqJWGeRd6NPmBk4u/het2PZdtzIaw= +github.com/IBM/vpc-go-sdk v0.58.0 h1:Slk1jkcV7tPnf0iECQV2Oja7W8Bom0z7k9M4fMBY4bI= +github.com/IBM/vpc-go-sdk v0.58.0/go.mod h1:swmxiYLT+OfBsBYqJWGeRd6NPmBk4u/het2PZdtzIaw= github.com/Jeffail/gabs v1.1.1 h1:V0uzR08Hj22EX8+8QMhyI9sX2hwRu+/RJhJUmnwda/E= github.com/Jeffail/gabs v1.1.1/go.mod h1:6xMvQMK4k33lb7GUUpaAPh6nKMmemQeg5d4gn7/bOXc= github.com/Logicalis/asn1 v0.0.0-20190312173541-d60463189a56 h1:vuquMR410psHNax14XKNWa0Ae/kYgWJcXi0IFuX60N0= @@ -525,8 +525,9 @@ github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbV github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.3.0 h1:2y3SDp0ZXuc6/cjLSZ+Q3ir+QB9T/iG5yYRXqsagWSY= github.com/go-logr/logr v1.3.0/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ= +github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-logr/zapr v0.1.0/go.mod h1:tabnROwaDl0UNxkVeFRbY8bwB37GwRv0P8lg6aAiEnk= @@ -640,6 +641,8 @@ github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/me github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI= github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572/go.mod h1:9Pwr4B2jHnOSGXyyzV8ROjYa2ojvAY6HCGYYfMoC3Ls= +github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= +github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= github.com/go-test/deep v1.0.1/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA= github.com/go-test/deep v1.0.2-0.20181118220953-042da051cf31/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA= github.com/go-test/deep v1.0.2/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA= @@ -775,8 +778,8 @@ github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLe github.com/google/pprof v0.0.0-20210122040257-d980be63207e/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20230510103437-eeec1cb781c3 h1:2XF1Vzq06X+inNqgJ9tRnGuw+ZVCB3FazXODD6JE1R8= -github.com/google/pprof v0.0.0-20230510103437-eeec1cb781c3/go.mod h1:79YE0hCXdHag9sBkw2o+N/YnZtTkXi0UT9Nnixa5eYk= +github.com/google/pprof v0.0.0-20240424215950-a892ee059fd6 h1:k7nVchz72niMH6YLQNvHSdIE7iqsQxK1P41mySCvssg= +github.com/google/pprof v0.0.0-20240424215950-a892ee059fd6/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -947,10 +950,11 @@ github.com/hashicorp/go-uuid v1.0.2-0.20191001231223-f32f5fe8d6a8/go.mod h1:6SBZ github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-version v1.0.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/go-version v1.1.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/go-version v1.6.0 h1:feTTfFNnjP967rlCxM/I9g701jU+RN74YKx2mOkIeek= -github.com/hashicorp/go-version v1.6.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/go-version v1.7.0 h1:5tqGy27NaOTB8yJKUZELlFAS/LTKJkrmONwQKeRZfjY= +github.com/hashicorp/go-version v1.7.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90= github.com/hashicorp/golang-lru v0.0.0-20180201235237-0fb14efe8c47/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= @@ -1257,7 +1261,10 @@ github.com/mitchellh/go-testing-interface v1.14.1/go.mod h1:gfgS7OtZj6MA4U1UrDRp github.com/mitchellh/go-wordwrap v1.0.0 h1:6GlHJ/LTGMrIJbwgdqdl2eEH8o+Exx/0m8ir9Gns0u4= github.com/mitchellh/go-wordwrap v1.0.0/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg= +github.com/mitchellh/gox v1.0.1 h1:x0jD3dcHk9a9xPSDN6YEL4xL6Qz0dvNYm8yZqui5chI= +github.com/mitchellh/gox v1.0.1/go.mod h1:ED6BioOGXMswlXa2zxfh/xdd5QhwYliBFn9V18Ap4z4= github.com/mitchellh/hashstructure v1.0.0/go.mod h1:QjSHrPWS+BGUVBYkbTZWEnOh3G1DutKwClXU/ABz6AQ= +github.com/mitchellh/iochan v1.0.0 h1:C+X3KsSTLFVBr/tK1eYN/vs4rJcvsiLU338UhYPJWeY= github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= @@ -1343,8 +1350,9 @@ github.com/onsi/ginkgo/v2 v2.9.5/go.mod h1:tvAoo1QUJwNEU2ITftXTpR7R1RbCzoZUOs3Ro github.com/onsi/ginkgo/v2 v2.9.7/go.mod h1:cxrmXWykAwTwhQsJOPfdIDiJ+l2RYq7U8hFU+M/1uw0= github.com/onsi/ginkgo/v2 v2.11.0/go.mod h1:ZhrRA5XmEE3x3rhlzamx/JJvujdZoJ2uvgI7kR0iZvM= github.com/onsi/ginkgo/v2 v2.13.0/go.mod h1:TE309ZR8s5FsKKpuB1YAQYBzCaAfUgatB/xlT/ETL/o= -github.com/onsi/ginkgo/v2 v2.15.0 h1:79HwNRBAZHOEwrczrgSOPy+eFTTlIGELKy5as+ClttY= github.com/onsi/ginkgo/v2 v2.15.0/go.mod h1:HlxMHtYF57y6Dpf+mc5529KKmSq9h2FpCF+/ZkwUxKM= +github.com/onsi/ginkgo/v2 v2.19.0 h1:9Cnnf7UHo57Hy3k6/m5k3dRfGTMXGvxhHFvkDTCTpvA= +github.com/onsi/ginkgo/v2 v2.19.0/go.mod h1:rlwLi9PilAFJ8jCg9UE1QP6VBpd6/xj3SRC0d6TU0To= github.com/onsi/gomega v0.0.0-20170829124025-dcabb60a477c/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= github.com/onsi/gomega v0.0.0-20190113212917-5533ce8a0da3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/onsi/gomega v1.4.2/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= @@ -1376,8 +1384,8 @@ github.com/onsi/gomega v1.27.8/go.mod h1:2J8vzI/s+2shY9XHRApDkdgPo1TKT7P2u6fXeJK github.com/onsi/gomega v1.27.10/go.mod h1:RsS8tutOdbdgzbPtzzATp12yT7kM5I5aElG3evPbQ0M= github.com/onsi/gomega v1.30.0/go.mod h1:9sxs+SwGrKI0+PWe4Fxa9tFQQBG5xSsSbMXOI8PPpoQ= github.com/onsi/gomega v1.31.1/go.mod h1:y40C95dwAD1Nz36SsEnxvfFe8FFfNxzI5eJ0EYGyAy0= -github.com/onsi/gomega v1.33.1 h1:dsYjIxxSR755MDmKVsaFQTE22ChNBcuuTWgkUDSubOk= -github.com/onsi/gomega v1.33.1/go.mod h1:U4R44UsT+9eLIaYRB2a5qajjtQYn0hauxvRm16AVYg0= +github.com/onsi/gomega v1.34.1 h1:EUMJIKUjM8sKjYbtxQI9A4z2o+rruxnzNvpknOXie6k= +github.com/onsi/gomega v1.34.1/go.mod h1:kU1QgUvBDLXBJq618Xvm2LUX6rSAfRaFRTcdOeDLwwY= github.com/opencontainers/go-digest v1.0.0-rc1/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= @@ -1782,6 +1790,8 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0 golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= +golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 h1:2dVuKD2vS7b0QIHQbpyTISPd0LeHDbnYEryqj5Q1ug8= +golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56/go.mod h1:M4RDyNAINzryxdtnbRXRL/OHtkFuWGRjvuhBJpk2IlY= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= @@ -2187,8 +2197,8 @@ golang.org/x/tools v0.9.3/go.mod h1:owI94Op576fPu3cIGQeHs3joujW/2Oc6MtlxbF5dfNc= golang.org/x/tools v0.12.0/go.mod h1:Sc0INKfu04TlqNoRA1hgpFZbhYXHPr4V5DzpSBTPqQM= golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= golang.org/x/tools v0.16.1/go.mod h1:kYVVN6I1mBNoB1OX+noeBjbRk4IUEPa7JJ+TJMEooJ0= -golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg= -golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= +golang.org/x/tools v0.23.0 h1:SGsXPZ+2l4JsgaCKkx+FQ9YZ5XEtA1GZYuoDjenLjvg= +golang.org/x/tools v0.23.0/go.mod h1:pnu6ufv6vQkll6szChhK3C3L/ruaIv5eBeztNG8wtsI= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/ibm/acctest/acctest.go b/ibm/acctest/acctest.go index 410539545e..7fdb4aefea 100644 --- a/ibm/acctest/acctest.go +++ b/ibm/acctest/acctest.go @@ -393,7 +393,8 @@ var ( // For IAM Access Management var ( - TargetAccountId string + TargetAccountId string + TargetEnterpriseId string ) // For Partner Center Sell @@ -1870,6 +1871,11 @@ func init() { fmt.Println("[INFO] Set the environment variable IBM_POLICY_ASSIGNMENT_TARGET_ACCOUNT_ID for testing ibm_iam_policy_assignment resource else tests will fail if this is not set correctly") } + TargetEnterpriseId = os.Getenv("IBM_POLICY_ASSIGNMENT_TARGET_ENTERPRISE_ID") + if TargetEnterpriseId == "" { + fmt.Println("[INFO] Set the environment variable IBM_POLICY_ASSIGNMENT_TARGET_ENTERPRISE_ID for testing ibm_iam_policy_assignment resource else tests will fail if this is not set correctly") + } + PcsRegistrationAccountId = os.Getenv("PCS_REGISTRATION_ACCOUNT_ID") if PcsRegistrationAccountId == "" { fmt.Println("[WARN] Set the environment variable PCS_REGISTRATION_ACCOUNT_ID for testing iam_onboarding resource else tests will fail if this is not set correctly") diff --git a/ibm/conns/config.go b/ibm/conns/config.go index 83ae73f383..06f1599ef6 100644 --- a/ibm/conns/config.go +++ b/ibm/conns/config.go @@ -93,6 +93,8 @@ import ( jwt "github.com/golang-jwt/jwt" slsession "github.com/softlayer/softlayer-go/session" + "github.com/IBM/configuration-aggregator-go-sdk/configurationaggregatorv1" + bluemix "github.com/IBM-Cloud/bluemix-go" "github.com/IBM-Cloud/bluemix-go/api/account/accountv1" "github.com/IBM-Cloud/bluemix-go/api/account/accountv2" @@ -220,6 +222,7 @@ type ClientSession interface { ContainerAPI() (containerv1.ContainerServiceAPI, error) VpcContainerAPI() (containerv2.ContainerServiceAPI, error) ContainerRegistryV1() (*containerregistryv1.ContainerRegistryV1, error) + ConfigurationAggregatorV1() (*configurationaggregatorv1.ConfigurationAggregatorV1, error) FunctionClient() (*whisk.Client, error) GlobalSearchAPI() (globalsearchv2.GlobalSearchServiceAPI, error) GlobalTaggingAPI() (globaltaggingv3.GlobalTaggingServiceAPI, error) @@ -327,6 +330,9 @@ type clientSession struct { accountV1ConfigErr error bmxAccountv1ServiceAPI accountv1.AccountServiceAPI + configurationAggregatorClient *configurationaggregatorv1.ConfigurationAggregatorV1 + configurationAggregatorClientErr error + bmxUserDetails *UserConfig bmxUserFetchErr error @@ -667,6 +673,11 @@ func (session clientSession) PartnerCenterSellV1() (*partnercentersellv1.Partner return session.partnerCenterSellClient, session.partnerCenterSellClientErr } +// Configuration Aggregator +func (session clientSession) ConfigurationAggregatorV1() (*configurationaggregatorv1.ConfigurationAggregatorV1, error) { + return session.configurationAggregatorClient, session.configurationAggregatorClientErr +} + // AppIDAPI provides AppID Service APIs ... func (session clientSession) AppIDAPI() (*appid.AppIDManagementV4, error) { return session.appidAPI, session.appidErr @@ -2381,6 +2392,28 @@ func (c *Config) ClientSession() (interface{}, error) { // }) } + // Construct an instance of the 'Configuration Aggregator' service. + if session.configurationAggregatorClientErr == nil { + // Construct the service options. + configurationAggregatorClientOptions := &configurationaggregatorv1.ConfigurationAggregatorV1Options{ + URL: EnvFallBack([]string{"IBMCLOUD_IAM_API_ENDPOINT"}, iamURL), + Authenticator: authenticator, + } + + // Construct the service client. + session.configurationAggregatorClient, err = configurationaggregatorv1.NewConfigurationAggregatorV1(configurationAggregatorClientOptions) + if err == nil { + // Enable retries for API calls + session.configurationAggregatorClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) + // Add custom header for analytics + session.configurationAggregatorClient.SetDefaultHeaders(gohttp.Header{ + "X-Original-User-Agent": {fmt.Sprintf("terraform-provider-ibm/%s", version.Version)}, + }) + } else { + session.configurationAggregatorClientErr = fmt.Errorf("Error occurred while constructing 'Configuration Aggregator' service client: %q", err) + } + } + // CIS Service instances starts here. cisURL := ContructEndpoint("api.cis", cloudEndpoint) if c.Visibility == "private" { diff --git a/ibm/flex/structures.go b/ibm/flex/structures.go index da354497e6..1164864179 100644 --- a/ibm/flex/structures.go +++ b/ibm/flex/structures.go @@ -65,6 +65,8 @@ const ( ResourceStatus = "resource_status" //ResourceGroupName ... ResourceGroupName = "resource_group_name" + //DeletionProtection ... + DeletionProtection = "deletion_protection" //RelatedCRN ... RelatedCRN = "related_crn" SystemIBMLabelPrefix = "ibm-cloud.kubernetes.io/" @@ -930,6 +932,111 @@ func ReplicationRuleGet(in *s3.ReplicationConfiguration) []map[string]interface{ return rules } +func flattenLifecycleExpiration(expiration *s3.LifecycleExpiration) []interface{} { + if expiration == nil { + return []interface{}{} + } + m := make(map[string]interface{}) + if expiration.Date != nil { + m["date"] = expiration.Date.Format(time.RFC3339) + } + if expiration.Days != nil { + m["days"] = int(aws.Int64Value(expiration.Days)) + } + if expiration.ExpiredObjectDeleteMarker != nil { + m["expired_object_delete_marker"] = aws.Bool(*expiration.ExpiredObjectDeleteMarker) + } + return []interface{}{m} +} + +func flattenNoncurrentVersionExpiration(expiration *s3.NoncurrentVersionExpiration) []interface{} { + if expiration == nil { + return []interface{}{} + } + m := make(map[string]interface{}) + if expiration.NoncurrentDays != nil { + m["noncurrent_days"] = int(aws.Int64Value(expiration.NoncurrentDays)) + } + return []interface{}{m} +} +func flattenTransitions(transitions []*s3.Transition) []interface{} { + if len(transitions) == 0 { + return []interface{}{} + } + var results []interface{} + for _, transition := range transitions { + m := make(map[string]interface{}) + if transition.StorageClass != nil { + m["storage_class"] = transition.StorageClass + } + if transition.Date != nil { + m["date"] = transition.Date.Format(time.RFC3339) + } + if transition.Days != nil { + m["days"] = int(aws.Int64Value(transition.Days)) + } + results = append(results, m) + } + return results +} + +func flattenLifecycleRuleFilter(filter *s3.LifecycleRuleFilter) []interface{} { + if filter == nil { + return []interface{}{} + } + m := make(map[string]interface{}) + if filter.Prefix != nil { + m["prefix"] = aws.String(*filter.Prefix) + } + return []interface{}{m} +} + +func flattenAbortIncompleteMultipartUpload(abortIncompleteMultipartUploadInput *s3.AbortIncompleteMultipartUpload) []interface{} { + if abortIncompleteMultipartUploadInput == nil { + return []interface{}{} + } + abortIncompleteMultipartUploadMap := make(map[string]interface{}) + if abortIncompleteMultipartUploadInput.DaysAfterInitiation != nil { + abortIncompleteMultipartUploadMap["days_after_initiation"] = int(aws.Int64Value(abortIncompleteMultipartUploadInput.DaysAfterInitiation)) + } + return []interface{}{abortIncompleteMultipartUploadMap} +} + +func LifecylceRuleGet(lifecycleRuleInput []*s3.LifecycleRule) []map[string]interface{} { + rules := make([]map[string]interface{}, 0, len(lifecycleRuleInput)) + if lifecycleRuleInput != nil { + for _, lifecyclerule := range lifecycleRuleInput { + lifecycleRuleConfig := make(map[string]interface{}) + if lifecyclerule.Status != nil { + if *lifecyclerule.Status == "Enabled" { + lifecycleRuleConfig["status"] = "enable" + } else { + lifecycleRuleConfig["status"] = "disable" + } + } + if lifecyclerule.ID != nil { + lifecycleRuleConfig["rule_id"] = *lifecyclerule.ID + } + if lifecyclerule.Expiration != nil { + lifecycleRuleConfig["expiration"] = flattenLifecycleExpiration(lifecyclerule.Expiration) + } + if lifecyclerule.Transitions != nil { + lifecycleRuleConfig["transition"] = flattenTransitions(lifecyclerule.Transitions) + } + if lifecyclerule.AbortIncompleteMultipartUpload != nil { + lifecycleRuleConfig["abort_incomplete_multipart_upload"] = flattenAbortIncompleteMultipartUpload(lifecyclerule.AbortIncompleteMultipartUpload) + } + if lifecyclerule.NoncurrentVersionExpiration != nil { + lifecycleRuleConfig["noncurrent_version_expiration"] = flattenNoncurrentVersionExpiration(lifecyclerule.NoncurrentVersionExpiration) + } + if lifecyclerule.Filter != nil { + lifecycleRuleConfig["filter"] = flattenLifecycleRuleFilter(lifecyclerule.Filter) + } + rules = append(rules, lifecycleRuleConfig) + } + } + return rules +} func ObjectLockConfigurationGet(in *s3.ObjectLockConfiguration) []map[string]interface{} { configuration := make([]map[string]interface{}, 0, 1) if in != nil { @@ -2401,34 +2508,46 @@ func GetTags(d *schema.ResourceData, meta interface{}) error { // } func GetGlobalTagsUsingCRN(meta interface{}, resourceID, resourceType, tagType string) (*schema.Set, error) { + taggingResult, err := GetGlobalTagsUsingSearchAPI(meta, resourceID, resourceType, tagType) + if err != nil { + return nil, err + } + return taggingResult, nil +} + +func GetTagsUsingResourceCRNFromTaggingApi(meta interface{}, resourceID, resourceType, tagType string) (*schema.Set, error) { + gtClient, err := meta.(conns.ClientSession).GlobalTaggingAPIv1() + if err != nil { + return nil, fmt.Errorf("[ERROR] Error getting global tagging client settings: %s", err) + } userDetails, err := meta.(conns.ClientSession).BluemixUserDetails() if err != nil { return nil, err } accountID := userDetails.UserAccount ListTagsOptions := &globaltaggingv1.ListTagsOptions{} - if resourceID != "" { - ListTagsOptions.AttachedTo = &resourceID - } + ListTagsOptions.AttachedTo = &resourceID if strings.HasPrefix(resourceType, "Softlayer_") { ListTagsOptions.Providers = []string{"ims"} } if len(tagType) > 0 { ListTagsOptions.TagType = PtrToString(tagType) - if tagType == "service" { ListTagsOptions.AccountID = PtrToString(accountID) } } - taggingResult, err := GetGlobalTagsUsingSearchAPI(meta, resourceID, resourceType, tagType) + taggingResult, _, err := gtClient.ListTags(ListTagsOptions) if err != nil { return nil, err } - return taggingResult, nil + var taglist []string + for _, item := range taggingResult.Items { + taglist = append(taglist, *item.Name) + } + return NewStringSet(ResourceIBMVPCHash, taglist), nil } func GetGlobalTagsUsingSearchAPI(meta interface{}, resourceID, resourceType, tagType string) (*schema.Set, error) { - gsClient, err := meta.(conns.ClientSession).GlobalSearchAPIV2() if err != nil { return nil, fmt.Errorf("[ERROR] Error getting global search client settings: %s", err) @@ -2531,18 +2650,20 @@ func UpdateGlobalTagsUsingCRN(oldList, newList interface{}, meta interface{}, re detachTagOptions.AccountID = PtrToString(acctID) } } - - _, resp, err := gtClient.DetachTag(detachTagOptions) + results, fullResponse, err := gtClient.DetachTag(detachTagOptions) if err != nil { - return fmt.Errorf("[ERROR] Error detaching database tags %v: %s\n%s", remove, err, resp) + return fmt.Errorf("[ERROR] Error detaching tags calling api %v: %s\n%s", remove, err, fullResponse) } - for _, v := range remove { - delTagOptions := &globaltaggingv1.DeleteTagOptions{ - TagName: PtrToString(v), + if results != nil { + errMap := make([]globaltaggingv1.TagResultsItem, 0) + for _, res := range results.Results { + if res.IsError != nil && *res.IsError { + errMap = append(errMap, res) + } } - _, resp, err := gtClient.DeleteTag(delTagOptions) - if err != nil { - return fmt.Errorf("[ERROR] Error deleting database tag %v: %s\n%s", v, err, resp) + if len(errMap) > 0 { + output, _ := json.MarshalIndent(errMap, "", " ") + return fmt.Errorf("[ERROR] Error detaching tag in results %v: %s\n%s", remove, string(output), fullResponse) } } } @@ -2624,7 +2745,7 @@ func GetTagsUsingCRN(meta interface{}, resourceCRN string) (*schema.Set, error) } func UpdateTagsUsingCRN(oldList, newList interface{}, meta interface{}, resourceCRN string) error { - gtClient, err := meta.(conns.ClientSession).GlobalTaggingAPI() + gtClient, err := meta.(conns.ClientSession).GlobalTaggingAPIv1() if err != nil { return fmt.Errorf("[ERROR] Error getting global tagging client settings: %s", err) } @@ -2654,23 +2775,74 @@ func UpdateTagsUsingCRN(oldList, newList interface{}, meta interface{}, resource add = append(add, envTags...) } + resources := []globaltaggingv1.Resource{} + r := globaltaggingv1.Resource{ResourceID: &resourceCRN} + resources = append(resources, r) + if len(remove) > 0 { - _, err := gtClient.Tags().DetachTags(resourceCRN, remove) + detachTagOptions := &globaltaggingv1.DetachTagOptions{} + detachTagOptions.Resources = resources + detachTagOptions.TagNames = remove + + results, fullResponse, err := gtClient.DetachTag(detachTagOptions) if err != nil { - return fmt.Errorf("[ERROR] Error detaching database tags %v: %s", remove, err) + return fmt.Errorf("[ERROR] Error detaching tags %v: %s", remove, err) + } + if results != nil { + errMap := make([]globaltaggingv1.TagResultsItem, 0) + for _, res := range results.Results { + if res.IsError != nil && *res.IsError { + errMap = append(errMap, res) + } + } + if len(errMap) > 0 { + output, _ := json.MarshalIndent(errMap, "", " ") + return fmt.Errorf("[ERROR] Error detaching tag %v: %s\n%s", remove, string(output), fullResponse) + } } for _, v := range remove { - _, err := gtClient.Tags().DeleteTag(v) + delTagOptions := &globaltaggingv1.DeleteTagOptions{ + TagName: PtrToString(v), + } + results, fullResponse, err := gtClient.DeleteTag(delTagOptions) if err != nil { - return fmt.Errorf("[ERROR] Error deleting database tag %v: %s", v, err) + return fmt.Errorf("[ERROR] Error deleting tag %v: %s\n%s", v, err, fullResponse) + } + + if results != nil { + errMap := make([]globaltaggingv1.DeleteTagResultsItem, 0) + for _, res := range results.Results { + if res.IsError != nil && *res.IsError { + errMap = append(errMap, res) + } + } + if len(errMap) > 0 { + output, _ := json.MarshalIndent(errMap, "", " ") + return fmt.Errorf("[ERROR] Error deleting tag %s: %s\n%s", v, string(output), fullResponse) + } } } } if len(add) > 0 { - _, err := gtClient.Tags().AttachTags(resourceCRN, add) + AttachTagOptions := &globaltaggingv1.AttachTagOptions{} + AttachTagOptions.Resources = resources + AttachTagOptions.TagNames = add + results, fullResponse, err := gtClient.AttachTag(AttachTagOptions) if err != nil { - return fmt.Errorf("[ERROR] Error updating database tags %v : %s", add, err) + return fmt.Errorf("[ERROR] Error updating tags %v : %s", add, err) + } + if results != nil { + errMap := make([]globaltaggingv1.TagResultsItem, 0) + for _, res := range results.Results { + if res.IsError != nil && *res.IsError { + errMap = append(errMap, res) + } + } + if len(errMap) > 0 { + output, _ := json.MarshalIndent(errMap, "", " ") + return fmt.Errorf("Error while updating tag: %s - Full response: %s", string(output), fullResponse) + } } } diff --git a/ibm/provider/provider.go b/ibm/provider/provider.go index dc4a116869..34fc914a2a 100644 --- a/ibm/provider/provider.go +++ b/ibm/provider/provider.go @@ -30,6 +30,7 @@ import ( "github.com/IBM-Cloud/terraform-provider-ibm/ibm/service/cloudfoundry" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/service/cloudshell" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/service/codeengine" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/service/configurationaggregator" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/service/contextbasedrestrictions" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/service/cos" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/service/database" @@ -230,12 +231,15 @@ func Provider() *schema.Provider { }, DataSourcesMap: map[string]*schema.Resource{ - "ibm_api_gateway": apigateway.DataSourceIBMApiGateway(), - "ibm_account": cloudfoundry.DataSourceIBMAccount(), - "ibm_app": cloudfoundry.DataSourceIBMApp(), - "ibm_app_domain_private": cloudfoundry.DataSourceIBMAppDomainPrivate(), - "ibm_app_domain_shared": cloudfoundry.DataSourceIBMAppDomainShared(), - "ibm_app_route": cloudfoundry.DataSourceIBMAppRoute(), + "ibm_api_gateway": apigateway.DataSourceIBMApiGateway(), + "ibm_account": cloudfoundry.DataSourceIBMAccount(), + "ibm_app": cloudfoundry.DataSourceIBMApp(), + "ibm_app_domain_private": cloudfoundry.DataSourceIBMAppDomainPrivate(), + "ibm_app_domain_shared": cloudfoundry.DataSourceIBMAppDomainShared(), + "ibm_app_route": cloudfoundry.DataSourceIBMAppRoute(), + "ibm_config_aggregator_configurations": configurationaggregator.DataSourceIbmConfigAggregatorConfigurations(), + "ibm_config_aggregator_settings": configurationaggregator.DataSourceIbmConfigAggregatorSettings(), + "ibm_config_aggregator_resource_collection_status": configurationaggregator.DataSourceIbmConfigAggregatorResourceCollectionStatus(), // // AppID "ibm_appid_action_url": appid.DataSourceIBMAppIDActionURL(), @@ -932,6 +936,7 @@ func Provider() *schema.Provider { "ibm_code_engine_build": codeengine.DataSourceIbmCodeEngineBuild(), "ibm_code_engine_config_map": codeengine.DataSourceIbmCodeEngineConfigMap(), "ibm_code_engine_domain_mapping": codeengine.DataSourceIbmCodeEngineDomainMapping(), + "ibm_code_engine_function": codeengine.DataSourceIbmCodeEngineFunction(), "ibm_code_engine_job": codeengine.DataSourceIbmCodeEngineJob(), "ibm_code_engine_project": codeengine.DataSourceIbmCodeEngineProject(), "ibm_code_engine_secret": codeengine.DataSourceIbmCodeEngineSecret(), @@ -976,6 +981,7 @@ func Provider() *schema.Provider { "ibm_app_domain_private": cloudfoundry.ResourceIBMAppDomainPrivate(), "ibm_app_domain_shared": cloudfoundry.ResourceIBMAppDomainShared(), "ibm_app_route": cloudfoundry.ResourceIBMAppRoute(), + "ibm_config_aggregator_settings": configurationaggregator.ResourceIbmConfigAggregatorSettings(), // AppID "ibm_appid_action_url": appid.ResourceIBMAppIDActionURL(), @@ -1094,6 +1100,7 @@ func Provider() *schema.Provider { "ibm_cos_bucket_object": cos.ResourceIBMCOSBucketObject(), "ibm_cos_bucket_object_lock_configuration": cos.ResourceIBMCOSBucketObjectlock(), "ibm_cos_bucket_website_configuration": cos.ResourceIBMCOSBucketWebsiteConfiguration(), + "ibm_cos_bucket_lifecycle_configuration": cos.ResourceIBMCOSBucketLifecycleConfiguration(), "ibm_dns_domain": classicinfrastructure.ResourceIBMDNSDomain(), "ibm_dns_domain_registration_nameservers": classicinfrastructure.ResourceIBMDNSDomainRegistrationNameservers(), "ibm_dns_secondary": classicinfrastructure.ResourceIBMDNSSecondary(), @@ -1196,6 +1203,7 @@ func Provider() *schema.Provider { "ibm_is_reservation": vpc.ResourceIBMISReservation(), "ibm_is_reservation_activate": vpc.ResourceIBMISReservationActivate(), "ibm_is_subnet_reserved_ip": vpc.ResourceIBMISReservedIP(), + "ibm_is_subnet_reserved_ip_patch": vpc.ResourceIBMISReservedIPPatch(), "ibm_is_subnet_network_acl_attachment": vpc.ResourceIBMISSubnetNetworkACLAttachment(), "ibm_is_subnet_public_gateway_attachment": vpc.ResourceIBMISSubnetPublicGatewayAttachment(), "ibm_is_subnet_routing_table_attachment": vpc.ResourceIBMISSubnetRoutingTableAttachment(), @@ -1407,6 +1415,9 @@ func Provider() *schema.Provider { "ibm_resource_tag": globaltagging.ResourceIBMResourceTag(), "ibm_resource_access_tag": globaltagging.ResourceIBMResourceAccessTag(), + // Added for Iam Access Tag + "ibm_iam_access_tag": globaltagging.ResourceIBMIamAccessTag(), + // Atracker "ibm_atracker_target": atracker.ResourceIBMAtrackerTarget(), "ibm_atracker_route": atracker.ResourceIBMAtrackerRoute(), @@ -1530,6 +1541,7 @@ func Provider() *schema.Provider { "ibm_code_engine_build": codeengine.ResourceIbmCodeEngineBuild(), "ibm_code_engine_config_map": codeengine.ResourceIbmCodeEngineConfigMap(), "ibm_code_engine_domain_mapping": codeengine.ResourceIbmCodeEngineDomainMapping(), + "ibm_code_engine_function": codeengine.ResourceIbmCodeEngineFunction(), "ibm_code_engine_job": codeengine.ResourceIbmCodeEngineJob(), "ibm_code_engine_project": codeengine.ResourceIbmCodeEngineProject(), "ibm_code_engine_secret": codeengine.ResourceIbmCodeEngineSecret(), @@ -1635,6 +1647,26 @@ func wrapFunction( ) func(context.Context, *schema.ResourceData, interface{}) diag.Diagnostics { if function != nil { return func(context context.Context, schema *schema.ResourceData, meta interface{}) diag.Diagnostics { + + // only allow deletion if the resource is not marked as protected + if operationName == "delete" && schema.Get("deletion_protection") != nil { + // we check the value in state, not current config. Current config will always be null for a delete + + if schema.Get("deletion_protection") == true { + log.Printf("[DEBUG] Resource has deletion protection turned on %s", resourceName) + var diags diag.Diagnostics + summary := fmt.Sprintf("Deletion protection is enabled for resource %s to prevent accidential deletion", schema.Get("name")) + return append( + diags, + diag.Diagnostic{ + Severity: diag.Error, + Summary: summary, + Detail: "Set deletion_protection to false, apply and then destroy if deletion should proceed", + }, + ) + } + } + return function(context, schema, meta) } } else if fallback != nil { @@ -1791,6 +1823,7 @@ func Validator() validate.ValidatorDict { "ibm_hpcs_keystore": hpcs.ResourceIbmKeystoreValidator(), "ibm_hpcs_key_template": hpcs.ResourceIbmKeyTemplateValidator(), "ibm_hpcs_vault": hpcs.ResourceIbmVaultValidator(), + "ibm_config_aggregator_settings": configurationaggregator.ResourceIbmConfigAggregatorSettingsValidator(), // MQ on Cloud "ibm_mqcloud_queue_manager": mqcloud.ResourceIbmMqcloudQueueManagerValidator(), @@ -1875,6 +1908,7 @@ func Validator() validate.ValidatorDict { "ibm_is_virtual_endpoint_gateway": vpc.ResourceIBMISEndpointGatewayValidator(), "ibm_resource_tag": globaltagging.ResourceIBMResourceTagValidator(), "ibm_resource_access_tag": globaltagging.ResourceIBMResourceAccessTagValidator(), + "ibm_iam_access_tag": globaltagging.ResourceIBMIamAccessTagValidator(), "ibm_satellite_location": satellite.ResourceIBMSatelliteLocationValidator(), "ibm_satellite_cluster": satellite.ResourceIBMSatelliteClusterValidator(), "ibm_pi_volume": power.ResourceIBMPIVolumeValidator(), @@ -1985,6 +2019,7 @@ func Validator() validate.ValidatorDict { "ibm_code_engine_build": codeengine.ResourceIbmCodeEngineBuildValidator(), "ibm_code_engine_config_map": codeengine.ResourceIbmCodeEngineConfigMapValidator(), "ibm_code_engine_domain_mapping": codeengine.ResourceIbmCodeEngineDomainMappingValidator(), + "ibm_code_engine_function": codeengine.ResourceIbmCodeEngineFunctionValidator(), "ibm_code_engine_job": codeengine.ResourceIbmCodeEngineJobValidator(), "ibm_code_engine_project": codeengine.ResourceIbmCodeEngineProjectValidator(), "ibm_code_engine_secret": codeengine.ResourceIbmCodeEngineSecretValidator(), diff --git a/ibm/service/codeengine/data_source_ibm_code_engine_function.go b/ibm/service/codeengine/data_source_ibm_code_engine_function.go new file mode 100644 index 0000000000..5fc67cd134 --- /dev/null +++ b/ibm/service/codeengine/data_source_ibm_code_engine_function.go @@ -0,0 +1,373 @@ +// Copyright IBM Corp. 2024 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package codeengine + +import ( + "context" + "fmt" + "log" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" + "github.com/IBM/code-engine-go-sdk/codeenginev2" +) + +func DataSourceIbmCodeEngineFunction() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmCodeEngineFunctionRead, + + Schema: map[string]*schema.Schema{ + "project_id": { + Type: schema.TypeString, + Required: true, + Description: "The ID of the project.", + }, + "name": { + Type: schema.TypeString, + Required: true, + Description: "The name of your function.", + }, + "code_binary": { + Type: schema.TypeBool, + Computed: true, + Description: "Specifies whether the code is binary or not. Defaults to false when `code_reference` is set to a data URL. When `code_reference` is set to a code bundle URL, this field is always true.", + }, + "code_main": { + Type: schema.TypeString, + Computed: true, + Description: "Specifies the name of the function that should be invoked.", + }, + "code_reference": { + Type: schema.TypeString, + Computed: true, + Description: "Specifies either a reference to a code bundle or the source code itself. To specify the source code, use the data URL scheme and include the source code as base64 encoded. The data URL scheme is defined in [RFC 2397](https://tools.ietf.org/html/rfc2397).", + }, + "code_secret": { + Type: schema.TypeString, + Computed: true, + Description: "The name of the secret that is used to access the specified `code_reference`. The secret is used to authenticate with a non-public endpoint that is specified as`code_reference`.", + }, + "created_at": { + Type: schema.TypeString, + Computed: true, + Description: "The timestamp when the resource was created.", + }, + "endpoint": { + Type: schema.TypeString, + Computed: true, + Description: "URL to invoke the function.", + }, + "endpoint_internal": { + Type: schema.TypeString, + Computed: true, + Description: "URL to function that is only visible within the project.", + }, + "entity_tag": { + Type: schema.TypeString, + Computed: true, + Description: "The version of the function instance, which is used to achieve optimistic locking.", + }, + "href": { + Type: schema.TypeString, + Computed: true, + Description: "When you provision a new function, a relative URL path is created identifying the location of the instance.", + }, + "function_id": { + Type: schema.TypeString, + Computed: true, + Description: "The identifier of the resource.", + }, + "managed_domain_mappings": { + Type: schema.TypeString, + Computed: true, + Description: "Optional value controlling which of the system managed domain mappings will be setup for the function. Valid values are 'local_public', 'local_private' and 'local'. Visibility can only be 'local_private' if the project supports function private visibility.", + }, + "region": { + Type: schema.TypeString, + Computed: true, + Description: "The region of the project the resource is located in. Possible values: 'au-syd', 'br-sao', 'ca-tor', 'eu-de', 'eu-gb', 'jp-osa', 'jp-tok', 'us-east', 'us-south'.", + }, + "resource_type": { + Type: schema.TypeString, + Computed: true, + Description: "The type of the function.", + }, + "run_env_variables": { + Type: schema.TypeList, + Computed: true, + Description: "References to config maps, secrets or literal values, which are defined by the function owner and are exposed as environment variables in the function.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "key": { + Type: schema.TypeString, + Computed: true, + Description: "The key to reference as environment variable.", + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: "The name of the environment variable.", + }, + "prefix": { + Type: schema.TypeString, + Computed: true, + Description: "A prefix that can be added to all keys of a full secret or config map reference.", + }, + "reference": { + Type: schema.TypeString, + Computed: true, + Description: "The name of the secret or config map.", + }, + "type": { + Type: schema.TypeString, + Computed: true, + Description: "Specify the type of the environment variable.", + }, + "value": { + Type: schema.TypeString, + Computed: true, + Description: "The literal value of the environment variable.", + }, + }, + }, + }, + "runtime": { + Type: schema.TypeString, + Computed: true, + Description: "The managed runtime used to execute the injected code.", + }, + "scale_concurrency": { + Type: schema.TypeInt, + Computed: true, + Description: "Number of parallel requests handled by a single instance, supported only by Node.js, default is `1`.", + }, + "scale_cpu_limit": { + Type: schema.TypeString, + Computed: true, + Description: "Optional amount of CPU set for the instance of the function. For valid values see [Supported memory and CPU combinations](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo).", + }, + "scale_down_delay": { + Type: schema.TypeInt, + Computed: true, + Description: "Optional amount of time in seconds that delays the scale down behavior for a function.", + }, + "scale_max_execution_time": { + Type: schema.TypeInt, + Computed: true, + Description: "Timeout in secs after which the function is terminated.", + }, + "scale_memory_limit": { + Type: schema.TypeString, + Computed: true, + Description: "Optional amount of memory set for the instance of the function. For valid values see [Supported memory and CPU combinations](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo). The units for specifying memory are Megabyte (M) or Gigabyte (G), whereas G and M are the shorthand expressions for GB and MB. For more information see [Units of measurement](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo#unit-measurements).", + }, + "status": { + Type: schema.TypeString, + Computed: true, + Description: "The current status of the function.", + }, + "status_details": { + Type: schema.TypeList, + Computed: true, + Description: "The detailed status of the function.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "reason": { + Type: schema.TypeString, + Computed: true, + Description: "Provides additional information about the status of the function.", + }, + }, + }, + }, + }, + } +} + +func dataSourceIbmCodeEngineFunctionRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + codeEngineClient, err := meta.(conns.ClientSession).CodeEngineV2() + if err != nil { + tfErr := flex.TerraformErrorf(err, err.Error(), "(Data) ibm_code_engine_function", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + getFunctionOptions := &codeenginev2.GetFunctionOptions{} + + getFunctionOptions.SetProjectID(d.Get("project_id").(string)) + getFunctionOptions.SetName(d.Get("name").(string)) + + function, _, err := codeEngineClient.GetFunctionWithContext(context, getFunctionOptions) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetFunctionWithContext failed: %s", err.Error()), "(Data) ibm_code_engine_function", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + d.SetId(fmt.Sprintf("%s/%s", *getFunctionOptions.ProjectID, *getFunctionOptions.Name)) + + if err = d.Set("code_binary", function.CodeBinary); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting code_binary: %s", err), "(Data) ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + + if err = d.Set("code_main", function.CodeMain); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting code_main: %s", err), "(Data) ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + + if err = d.Set("code_reference", function.CodeReference); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting code_reference: %s", err), "(Data) ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + + if err = d.Set("code_secret", function.CodeSecret); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting code_secret: %s", err), "(Data) ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + + if err = d.Set("created_at", function.CreatedAt); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at: %s", err), "(Data) ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + + if err = d.Set("endpoint", function.Endpoint); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting endpoint: %s", err), "(Data) ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + + if err = d.Set("endpoint_internal", function.EndpointInternal); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting endpoint_internal: %s", err), "(Data) ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + + if err = d.Set("entity_tag", function.EntityTag); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting entity_tag: %s", err), "(Data) ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + + if err = d.Set("href", function.Href); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting href: %s", err), "(Data) ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + + if err = d.Set("function_id", function.ID); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting function_id: %s", err), "(Data) ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + + if err = d.Set("managed_domain_mappings", function.ManagedDomainMappings); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting managed_domain_mappings: %s", err), "(Data) ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + + if err = d.Set("region", function.Region); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region: %s", err), "(Data) ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + + if err = d.Set("resource_type", function.ResourceType); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting resource_type: %s", err), "(Data) ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + + runEnvVariables := []map[string]interface{}{} + if function.RunEnvVariables != nil { + for _, modelItem := range function.RunEnvVariables { + modelMap, err := dataSourceIbmCodeEngineFunctionEnvVarToMap(&modelItem) /* #nosec G601 */ + if err != nil { + tfErr := flex.TerraformErrorf(err, err.Error(), "(Data) ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + runEnvVariables = append(runEnvVariables, modelMap) + } + } + if err = d.Set("run_env_variables", runEnvVariables); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting run_env_variables: %s", err), "(Data) ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + + if err = d.Set("runtime", function.Runtime); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting runtime: %s", err), "(Data) ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + + if err = d.Set("scale_concurrency", flex.IntValue(function.ScaleConcurrency)); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting scale_concurrency: %s", err), "(Data) ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + + if err = d.Set("scale_cpu_limit", function.ScaleCpuLimit); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting scale_cpu_limit: %s", err), "(Data) ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + + if err = d.Set("scale_down_delay", flex.IntValue(function.ScaleDownDelay)); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting scale_down_delay: %s", err), "(Data) ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + + if err = d.Set("scale_max_execution_time", flex.IntValue(function.ScaleMaxExecutionTime)); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting scale_max_execution_time: %s", err), "(Data) ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + + if err = d.Set("scale_memory_limit", function.ScaleMemoryLimit); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting scale_memory_limit: %s", err), "(Data) ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + + if err = d.Set("status", function.Status); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting status: %s", err), "(Data) ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + + statusDetails := []map[string]interface{}{} + if function.StatusDetails != nil { + modelMap, err := dataSourceIbmCodeEngineFunctionFunctionStatusToMap(function.StatusDetails) + if err != nil { + tfErr := flex.TerraformErrorf(err, err.Error(), "(Data) ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + statusDetails = append(statusDetails, modelMap) + } + if err = d.Set("status_details", statusDetails); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting status_details: %s", err), "(Data) ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + + return nil +} + +func dataSourceIbmCodeEngineFunctionEnvVarToMap(model *codeenginev2.EnvVar) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Key != nil { + modelMap["key"] = *model.Key + } + if model.Name != nil { + modelMap["name"] = *model.Name + } + if model.Prefix != nil { + modelMap["prefix"] = *model.Prefix + } + if model.Reference != nil { + modelMap["reference"] = *model.Reference + } + modelMap["type"] = *model.Type + if model.Value != nil { + modelMap["value"] = *model.Value + } + return modelMap, nil +} + +func dataSourceIbmCodeEngineFunctionFunctionStatusToMap(model *codeenginev2.FunctionStatus) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Reason != nil { + modelMap["reason"] = *model.Reason + } + return modelMap, nil +} diff --git a/ibm/service/codeengine/data_source_ibm_code_engine_function_test.go b/ibm/service/codeengine/data_source_ibm_code_engine_function_test.go new file mode 100644 index 0000000000..9700e13223 --- /dev/null +++ b/ibm/service/codeengine/data_source_ibm_code_engine_function_test.go @@ -0,0 +1,147 @@ +// Copyright IBM Corp. 2024 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package codeengine_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmCodeEngineFunctionDataSourceBasic(t *testing.T) { + functionName := fmt.Sprintf("%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlpha)) + functionRuntime := "nodejs-20" + functionCodeReference := "data:text/plain;base64,foo" + + projectID := acc.CeProjectId + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmCodeEngineFunctionDataSourceConfigBasic(projectID, functionCodeReference, functionName, functionRuntime), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_code_engine_function.code_engine_function_instance", "function_id"), + resource.TestCheckResourceAttr("data.ibm_code_engine_function.code_engine_function_instance", "project_id", projectID), + resource.TestCheckResourceAttr("data.ibm_code_engine_function.code_engine_function_instance", "resource_type", "function_v2"), + resource.TestCheckResourceAttr("data.ibm_code_engine_function.code_engine_function_instance", "name", functionName), + resource.TestCheckResourceAttr("data.ibm_code_engine_function.code_engine_function_instance", "code_binary", "false"), + resource.TestCheckResourceAttr("data.ibm_code_engine_function.code_engine_function_instance", "code_reference", functionCodeReference), + resource.TestCheckResourceAttr("data.ibm_code_engine_function.code_engine_function_instance", "managed_domain_mappings", "local_public"), + resource.TestCheckResourceAttr("data.ibm_code_engine_function.code_engine_function_instance", "runtime", functionRuntime), + resource.TestCheckResourceAttr("data.ibm_code_engine_function.code_engine_function_instance", "scale_concurrency", "1"), + resource.TestCheckResourceAttr("data.ibm_code_engine_function.code_engine_function_instance", "scale_cpu_limit", "1"), + resource.TestCheckResourceAttr("data.ibm_code_engine_function.code_engine_function_instance", "scale_down_delay", "1"), + resource.TestCheckResourceAttr("data.ibm_code_engine_function.code_engine_function_instance", "scale_max_execution_time", "60"), + resource.TestCheckResourceAttr("data.ibm_code_engine_function.code_engine_function_instance", "scale_memory_limit", "4G"), + ), + }, + }, + }) +} + +func TestAccIbmCodeEngineFunctionDataSourceExtended(t *testing.T) { + functionName := fmt.Sprintf("%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlpha)) + functionRuntime := "nodejs-20" + functionCodeReference := "data:text/plain;base64,foo" + functionManagedDomainMappings := "local_private" + functionScaleCpuLimit := "0.5" + functionScaleDownDelay := "20" + functionScaleMaxExecutionTime := "30" + functionScaleMemoryLimit := "2G" + + projectID := acc.CeProjectId + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmCodeEngineFunctionDataSourceConfig(projectID, functionCodeReference, functionManagedDomainMappings, functionName, functionRuntime, functionScaleCpuLimit, functionScaleDownDelay, functionScaleMaxExecutionTime, functionScaleMemoryLimit), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("data.ibm_code_engine_function.code_engine_function_instance", "project_id", projectID), + resource.TestCheckResourceAttr("data.ibm_code_engine_function.code_engine_function_instance", "resource_type", "function_v2"), + resource.TestCheckResourceAttr("data.ibm_code_engine_function.code_engine_function_instance", "name", functionName), + resource.TestCheckResourceAttr("data.ibm_code_engine_function.code_engine_function_instance", "code_binary", "false"), + resource.TestCheckResourceAttr("data.ibm_code_engine_function.code_engine_function_instance", "code_reference", functionCodeReference), + resource.TestCheckResourceAttr("data.ibm_code_engine_function.code_engine_function_instance", "managed_domain_mappings", functionManagedDomainMappings), + resource.TestCheckResourceAttr("data.ibm_code_engine_function.code_engine_function_instance", "runtime", functionRuntime), + resource.TestCheckResourceAttr("data.ibm_code_engine_function.code_engine_function_instance", "scale_concurrency", "1"), + resource.TestCheckResourceAttr("data.ibm_code_engine_function.code_engine_function_instance", "scale_cpu_limit", functionScaleCpuLimit), + resource.TestCheckResourceAttr("data.ibm_code_engine_function.code_engine_function_instance", "scale_down_delay", functionScaleDownDelay), + resource.TestCheckResourceAttr("data.ibm_code_engine_function.code_engine_function_instance", "scale_max_execution_time", functionScaleMaxExecutionTime), + resource.TestCheckResourceAttr("data.ibm_code_engine_function.code_engine_function_instance", "scale_memory_limit", functionScaleMemoryLimit), + ), + }, + }, + }) +} + +func testAccCheckIbmCodeEngineFunctionDataSourceConfigBasic(projectID string, functionCodeReference string, functionName string, functionRuntime string) string { + return fmt.Sprintf(` + data "ibm_code_engine_project" "code_engine_project_instance" { + project_id = "%s" + } + + resource "ibm_code_engine_function" "code_engine_function_instance" { + project_id = data.ibm_code_engine_project.code_engine_project_instance.project_id + code_reference = "%s" + name = "%s" + runtime = "%s" + + lifecycle { + ignore_changes = [ + run_env_variables + ] + } + } + + data "ibm_code_engine_function" "code_engine_function_instance" { + project_id = ibm_code_engine_function.code_engine_function_instance.project_id + name = ibm_code_engine_function.code_engine_function_instance.name + } + `, projectID, functionCodeReference, functionName, functionRuntime) +} + +func testAccCheckIbmCodeEngineFunctionDataSourceConfig(projectID string, functionCodeReference string, functionManagedDomainMappings string, functionName string, functionRuntime string, functionScaleCpuLimit string, functionScaleDownDelay string, functionScaleMaxExecutionTime string, functionScaleMemoryLimit string) string { + return fmt.Sprintf(` + data "ibm_code_engine_project" "code_engine_project_instance" { + project_id = "%s" + } + + resource "ibm_code_engine_function" "code_engine_function_instance" { + project_id = data.ibm_code_engine_project.code_engine_project_instance.project_id + code_reference = "%s" + managed_domain_mappings = "%s" + name = "%s" + runtime = "%s" + scale_cpu_limit = "%s" + scale_down_delay = %s + scale_max_execution_time = %s + scale_memory_limit = "%s" + + run_env_variables { + type = "literal" + name = "name" + value = "value" + } + + lifecycle { + ignore_changes = [ + run_env_variables + ] + } + } + + data "ibm_code_engine_function" "code_engine_function_instance" { + project_id = ibm_code_engine_function.code_engine_function_instance.project_id + name = ibm_code_engine_function.code_engine_function_instance.name + } + `, projectID, functionCodeReference, functionManagedDomainMappings, functionName, functionRuntime, functionScaleCpuLimit, functionScaleDownDelay, functionScaleMaxExecutionTime, functionScaleMemoryLimit) +} diff --git a/ibm/service/codeengine/resource_ibm_code_engine_function.go b/ibm/service/codeengine/resource_ibm_code_engine_function.go new file mode 100644 index 0000000000..981aecdf1c --- /dev/null +++ b/ibm/service/codeengine/resource_ibm_code_engine_function.go @@ -0,0 +1,839 @@ +// Copyright IBM Corp. 2024 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package codeengine + +import ( + "context" + "fmt" + "log" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" + "github.com/IBM/code-engine-go-sdk/codeenginev2" + "github.com/IBM/go-sdk-core/v5/core" +) + +func ResourceIbmCodeEngineFunction() *schema.Resource { + return &schema.Resource{ + CreateContext: resourceIbmCodeEngineFunctionCreate, + ReadContext: resourceIbmCodeEngineFunctionRead, + UpdateContext: resourceIbmCodeEngineFunctionUpdate, + DeleteContext: resourceIbmCodeEngineFunctionDelete, + Importer: &schema.ResourceImporter{}, + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(10 * time.Minute), + Update: schema.DefaultTimeout(10 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "project_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validate.InvokeValidator("ibm_code_engine_function", "project_id"), + Description: "The ID of the project.", + }, + "code_binary": { + Type: schema.TypeBool, + Optional: true, + Description: "Specifies whether the code is binary or not. Defaults to false when `code_reference` is set to a data URL. When `code_reference` is set to a code bundle URL, this field is always true.", + }, + "code_main": { + Type: schema.TypeString, + Optional: true, + Default: "main", + ValidateFunc: validate.InvokeValidator("ibm_code_engine_function", "code_main"), + Description: "Specifies the name of the function that should be invoked.", + }, + "code_reference": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validate.InvokeValidator("ibm_code_engine_function", "code_reference"), + Description: "Specifies either a reference to a code bundle or the source code itself. To specify the source code, use the data URL scheme and include the source code as base64 encoded. The data URL scheme is defined in [RFC 2397](https://tools.ietf.org/html/rfc2397).", + }, + "code_secret": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.InvokeValidator("ibm_code_engine_function", "code_secret"), + Description: "The name of the secret that is used to access the specified `code_reference`. The secret is used to authenticate with a non-public endpoint that is specified as`code_reference`.", + }, + "managed_domain_mappings": { + Type: schema.TypeString, + Optional: true, + Default: "local_public", + ValidateFunc: validate.InvokeValidator("ibm_code_engine_function", "managed_domain_mappings"), + Description: "Optional value controlling which of the system managed domain mappings will be setup for the function. Valid values are 'local_public', 'local_private' and 'local'. Visibility can only be 'local_private' if the project supports function private visibility.", + }, + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validate.InvokeValidator("ibm_code_engine_function", "name"), + Description: "The name of the function.", + }, + "run_env_variables": { + Type: schema.TypeList, + Optional: true, + Description: "References to config maps, secrets or literal values, which are defined by the function owner and are exposed as environment variables in the function.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "key": { + Type: schema.TypeString, + Optional: true, + Description: "The key to reference as environment variable.", + }, + "name": { + Type: schema.TypeString, + Optional: true, + Description: "The name of the environment variable.", + }, + "prefix": { + Type: schema.TypeString, + Optional: true, + Description: "A prefix that can be added to all keys of a full secret or config map reference.", + }, + "reference": { + Type: schema.TypeString, + Optional: true, + Description: "The name of the secret or config map.", + }, + "type": { + Type: schema.TypeString, + Optional: true, + Default: "literal", + Description: "Specify the type of the environment variable.", + }, + "value": { + Type: schema.TypeString, + Optional: true, + Description: "The literal value of the environment variable.", + }, + }, + }, + }, + "runtime": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validate.InvokeValidator("ibm_code_engine_function", "runtime"), + Description: "The managed runtime used to execute the injected code.", + }, + "scale_concurrency": { + Type: schema.TypeInt, + Optional: true, + Default: 1, + ValidateFunc: validate.InvokeValidator("ibm_code_engine_function", "scale_concurrency"), + Description: "Number of parallel requests handled by a single instance, supported only by Node.js, default is `1`.", + }, + "scale_cpu_limit": { + Type: schema.TypeString, + Optional: true, + Default: "1", + ValidateFunc: validate.InvokeValidator("ibm_code_engine_function", "scale_cpu_limit"), + Description: "Optional amount of CPU set for the instance of the function. For valid values see [Supported memory and CPU combinations](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo).", + }, + "scale_down_delay": { + Type: schema.TypeInt, + Optional: true, + Default: 1, + ValidateFunc: validate.InvokeValidator("ibm_code_engine_function", "scale_down_delay"), + Description: "Optional amount of time in seconds that delays the scale down behavior for a function.", + }, + "scale_max_execution_time": { + Type: schema.TypeInt, + Optional: true, + Default: 60, + ValidateFunc: validate.InvokeValidator("ibm_code_engine_function", "scale_max_execution_time"), + Description: "Timeout in secs after which the function is terminated.", + }, + "scale_memory_limit": { + Type: schema.TypeString, + Optional: true, + Default: "4G", + ValidateFunc: validate.InvokeValidator("ibm_code_engine_function", "scale_memory_limit"), + Description: "Optional amount of memory set for the instance of the function. For valid values see [Supported memory and CPU combinations](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo). The units for specifying memory are Megabyte (M) or Gigabyte (G), whereas G and M are the shorthand expressions for GB and MB. For more information see [Units of measurement](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo#unit-measurements).", + }, + "created_at": { + Type: schema.TypeString, + Computed: true, + Description: "The timestamp when the resource was created.", + }, + "endpoint": { + Type: schema.TypeString, + Computed: true, + Description: "URL to invoke the function.", + }, + "endpoint_internal": { + Type: schema.TypeString, + Computed: true, + Description: "URL to function that is only visible within the project.", + }, + "entity_tag": { + Type: schema.TypeString, + Computed: true, + Description: "The version of the function instance, which is used to achieve optimistic locking.", + }, + "href": { + Type: schema.TypeString, + Computed: true, + Description: "When you provision a new function, a relative URL path is created identifying the location of the instance.", + }, + "function_id": { + Type: schema.TypeString, + Computed: true, + Description: "The identifier of the resource.", + }, + "region": { + Type: schema.TypeString, + Computed: true, + Description: "The region of the project the resource is located in. Possible values: 'au-syd', 'br-sao', 'ca-tor', 'eu-de', 'eu-gb', 'jp-osa', 'jp-tok', 'us-east', 'us-south'.", + }, + "resource_type": { + Type: schema.TypeString, + Computed: true, + Description: "The type of the function.", + }, + "status": { + Type: schema.TypeString, + Computed: true, + Description: "The current status of the function.", + }, + "status_details": { + Type: schema.TypeList, + Computed: true, + Description: "The detailed status of the function.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "reason": { + Type: schema.TypeString, + Computed: true, + Description: "Provides additional information about the status of the function.", + }, + }, + }, + }, + "etag": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func ResourceIbmCodeEngineFunctionValidator() *validate.ResourceValidator { + validateSchema := make([]validate.ValidateSchema, 0) + validateSchema = append(validateSchema, + validate.ValidateSchema{ + Identifier: "project_id", + ValidateFunctionIdentifier: validate.ValidateRegexpLen, + Type: validate.TypeString, + Required: true, + Regexp: `^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$`, + MinValueLength: 36, + MaxValueLength: 36, + }, + validate.ValidateSchema{ + Identifier: "code_main", + ValidateFunctionIdentifier: validate.ValidateRegexpLen, + Type: validate.TypeString, + Optional: true, + Regexp: `^[a-zA-Z_][a-zA-Z0-9_]*$`, + MinValueLength: 1, + MaxValueLength: 63, + }, + validate.ValidateSchema{ + Identifier: "code_reference", + ValidateFunctionIdentifier: validate.ValidateRegexpLen, + Type: validate.TypeString, + Required: true, + Regexp: `^([a-z0-9][a-z0-9\-_.]+[a-z0-9][\/])?([a-z0-9][a-z0-9\-_]+[a-z0-9][\/])?[a-z0-9][a-z0-9\-_.\/]+[a-z0-9](:[\w][\w.\-]{0,127})?(@sha256:[a-fA-F0-9]{64})?$|data:([-\w]+\/[-+\w.]+)?(;?\w+=[-\w]+)*;base64,.*`, + MinValueLength: 1, + MaxValueLength: 1048576, + }, + validate.ValidateSchema{ + Identifier: "code_secret", + ValidateFunctionIdentifier: validate.ValidateRegexpLen, + Type: validate.TypeString, + Optional: true, + Regexp: `^[a-z0-9]([\-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([\-a-z0-9]*[a-z0-9])?)*$`, + MinValueLength: 1, + MaxValueLength: 253, + }, + validate.ValidateSchema{ + Identifier: "managed_domain_mappings", + ValidateFunctionIdentifier: validate.ValidateAllowedStringValue, + Type: validate.TypeString, + Optional: true, + AllowedValues: "local, local_private, local_public", + }, + validate.ValidateSchema{ + Identifier: "name", + ValidateFunctionIdentifier: validate.ValidateRegexpLen, + Type: validate.TypeString, + Required: true, + Regexp: `^[a-z]([-a-z0-9]*[a-z0-9])?$`, + MinValueLength: 1, + MaxValueLength: 63, + }, + validate.ValidateSchema{ + Identifier: "runtime", + ValidateFunctionIdentifier: validate.ValidateRegexpLen, + Type: validate.TypeString, + Required: true, + Regexp: `^[a-z]*\-[0-9]*(\.[0-9]*)?$`, + MinValueLength: 1, + MaxValueLength: 63, + }, + validate.ValidateSchema{ + Identifier: "scale_concurrency", + ValidateFunctionIdentifier: validate.IntBetween, + Type: validate.TypeInt, + Optional: true, + MinValue: "1", + MaxValue: "100", + }, + validate.ValidateSchema{ + Identifier: "scale_cpu_limit", + ValidateFunctionIdentifier: validate.ValidateRegexpLen, + Type: validate.TypeString, + Optional: true, + Regexp: `^([0-9.]+)([eEinumkKMGTPB]*)$`, + MinValueLength: 0, + MaxValueLength: 10, + }, + validate.ValidateSchema{ + Identifier: "scale_down_delay", + ValidateFunctionIdentifier: validate.IntBetween, + Type: validate.TypeInt, + Optional: true, + MinValue: "0", + MaxValue: "600", + }, + validate.ValidateSchema{ + Identifier: "scale_max_execution_time", + ValidateFunctionIdentifier: validate.IntBetween, + Type: validate.TypeInt, + Optional: true, + MinValue: "1", + MaxValue: "120", + }, + validate.ValidateSchema{ + Identifier: "scale_memory_limit", + ValidateFunctionIdentifier: validate.ValidateRegexpLen, + Type: validate.TypeString, + Optional: true, + Regexp: `^([0-9.]+)([eEinumkKMGTPB]*)$`, + MinValueLength: 0, + MaxValueLength: 10, + }, + ) + + resourceValidator := validate.ResourceValidator{ResourceName: "ibm_code_engine_function", Schema: validateSchema} + return &resourceValidator +} + +func resourceIbmCodeEngineFunctionCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + codeEngineClient, err := meta.(conns.ClientSession).CodeEngineV2() + if err != nil { + tfErr := flex.TerraformErrorf(err, err.Error(), "ibm_code_engine_function", "create") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + createFunctionOptions := &codeenginev2.CreateFunctionOptions{} + + createFunctionOptions.SetProjectID(d.Get("project_id").(string)) + createFunctionOptions.SetCodeReference(d.Get("code_reference").(string)) + createFunctionOptions.SetName(d.Get("name").(string)) + createFunctionOptions.SetRuntime(d.Get("runtime").(string)) + if _, ok := d.GetOk("code_binary"); ok { + createFunctionOptions.SetCodeBinary(d.Get("code_binary").(bool)) + } + if _, ok := d.GetOk("code_main"); ok { + createFunctionOptions.SetCodeMain(d.Get("code_main").(string)) + } + if _, ok := d.GetOk("code_secret"); ok { + createFunctionOptions.SetCodeSecret(d.Get("code_secret").(string)) + } + if _, ok := d.GetOk("managed_domain_mappings"); ok { + createFunctionOptions.SetManagedDomainMappings(d.Get("managed_domain_mappings").(string)) + } + if _, ok := d.GetOk("run_env_variables"); ok { + var runEnvVariables []codeenginev2.EnvVarPrototype + for _, v := range d.Get("run_env_variables").([]interface{}) { + value := v.(map[string]interface{}) + runEnvVariablesItem, err := resourceIbmCodeEngineFunctionMapToEnvVarPrototype(value) + if err != nil { + return diag.FromErr(err) + } + runEnvVariables = append(runEnvVariables, *runEnvVariablesItem) + } + createFunctionOptions.SetRunEnvVariables(runEnvVariables) + } + if _, ok := d.GetOk("scale_concurrency"); ok { + createFunctionOptions.SetScaleConcurrency(int64(d.Get("scale_concurrency").(int))) + } + if _, ok := d.GetOk("scale_cpu_limit"); ok { + createFunctionOptions.SetScaleCpuLimit(d.Get("scale_cpu_limit").(string)) + } + if _, ok := d.GetOk("scale_down_delay"); ok { + createFunctionOptions.SetScaleDownDelay(int64(d.Get("scale_down_delay").(int))) + } + if _, ok := d.GetOk("scale_max_execution_time"); ok { + createFunctionOptions.SetScaleMaxExecutionTime(int64(d.Get("scale_max_execution_time").(int))) + } + if _, ok := d.GetOk("scale_memory_limit"); ok { + createFunctionOptions.SetScaleMemoryLimit(d.Get("scale_memory_limit").(string)) + } + + function, _, err := codeEngineClient.CreateFunctionWithContext(context, createFunctionOptions) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateFunctionWithContext failed: %s", err.Error()), "ibm_code_engine_function", "create") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + d.SetId(fmt.Sprintf("%s/%s", *createFunctionOptions.ProjectID, *function.Name)) + + _, err = waitForIbmCodeEngineFunctionCreate(d, meta) + if err != nil { + errMsg := fmt.Sprintf("Error waiting for resource IbmCodeEngineFunction (%s) to be created: %s", d.Id(), err) + tfErr := flex.TerraformErrorf(err, errMsg, "ibm_code_engine_function", "create") + return tfErr.GetDiag() + } + + return resourceIbmCodeEngineFunctionRead(context, d, meta) +} + +func waitForIbmCodeEngineFunctionCreate(d *schema.ResourceData, meta interface{}) (interface{}, error) { + codeEngineClient, err := meta.(conns.ClientSession).CodeEngineV2() + if err != nil { + return false, err + } + getFunctionOptions := &codeenginev2.GetFunctionOptions{} + + parts, err := flex.SepIdParts(d.Id(), "/") + if err != nil { + return false, err + } + + getFunctionOptions.SetProjectID(parts[0]) + getFunctionOptions.SetName(parts[1]) + + stateConf := &resource.StateChangeConf{ + Pending: []string{"deploying"}, + Target: []string{"ready", "failed", "offline"}, + Refresh: func() (interface{}, string, error) { + stateObj, response, err := codeEngineClient.GetFunction(getFunctionOptions) + if err != nil { + if sdkErr, ok := err.(*core.SDKProblem); ok && response.GetStatusCode() == 404 { + sdkErr.Summary = fmt.Sprintf("The instance %s does not exist anymore: %s", "getFunctionOptions", err) + return nil, "", sdkErr + } + return nil, "", err + } + failStates := map[string]bool{"failure": true, "failed": true} + if failStates[*stateObj.Status] { + return stateObj, *stateObj.Status, fmt.Errorf("the instance %s failed: %s", "getFunctionOptions", err) + } + return stateObj, *stateObj.Status, nil + }, + Timeout: d.Timeout(schema.TimeoutCreate), + Delay: 60 * time.Second, + MinTimeout: 60 * time.Second, + } + + return stateConf.WaitForState() +} + +func resourceIbmCodeEngineFunctionRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + codeEngineClient, err := meta.(conns.ClientSession).CodeEngineV2() + if err != nil { + tfErr := flex.TerraformErrorf(err, err.Error(), "ibm_code_engine_function", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + getFunctionOptions := &codeenginev2.GetFunctionOptions{} + + parts, err := flex.SepIdParts(d.Id(), "/") + if err != nil { + tfErr := flex.TerraformErrorf(err, err.Error(), "ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + + getFunctionOptions.SetProjectID(parts[0]) + getFunctionOptions.SetName(parts[1]) + + function, response, err := codeEngineClient.GetFunctionWithContext(context, getFunctionOptions) + if err != nil { + if response != nil && response.StatusCode == 404 { + d.SetId("") + return nil + } + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetFunctionWithContext failed: %s", err.Error()), "ibm_code_engine_function", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + if err = d.Set("project_id", function.ProjectID); err != nil { + return diag.FromErr(fmt.Errorf("error setting project_id: %s", err)) + } + if !core.IsNil(function.CodeBinary) { + if err = d.Set("code_binary", function.CodeBinary); err != nil { + return diag.FromErr(fmt.Errorf("error setting code_binary: %s", err)) + } + } + if !core.IsNil(function.CodeMain) { + if err = d.Set("code_main", function.CodeMain); err != nil { + return diag.FromErr(fmt.Errorf("error setting code_main: %s", err)) + } + } + if err = d.Set("code_reference", function.CodeReference); err != nil { + return diag.FromErr(fmt.Errorf("error setting code_reference: %s", err)) + } + if !core.IsNil(function.CodeSecret) { + if err = d.Set("code_secret", function.CodeSecret); err != nil { + return diag.FromErr(fmt.Errorf("error setting code_secret: %s", err)) + } + } + if !core.IsNil(function.ManagedDomainMappings) { + if err = d.Set("managed_domain_mappings", function.ManagedDomainMappings); err != nil { + return diag.FromErr(fmt.Errorf("error setting managed_domain_mappings: %s", err)) + } + } + if err = d.Set("name", function.Name); err != nil { + return diag.FromErr(fmt.Errorf("error setting name: %s", err)) + } + if !core.IsNil(function.RunEnvVariables) { + runEnvVariables := []map[string]interface{}{} + for _, runEnvVariablesItem := range function.RunEnvVariables { + runEnvVariablesItemMap, err := resourceIbmCodeEngineFunctionEnvVarToMap(&runEnvVariablesItem) /* #nosec G601 */ + if err != nil { + return diag.FromErr(err) + } + runEnvVariables = append(runEnvVariables, runEnvVariablesItemMap) + } + if err = d.Set("run_env_variables", runEnvVariables); err != nil { + return diag.FromErr(fmt.Errorf("error setting run_env_variables: %s", err)) + } + } + if err = d.Set("runtime", function.Runtime); err != nil { + return diag.FromErr(fmt.Errorf("error setting runtime: %s", err)) + } + if !core.IsNil(function.ScaleConcurrency) { + if err = d.Set("scale_concurrency", flex.IntValue(function.ScaleConcurrency)); err != nil { + return diag.FromErr(fmt.Errorf("error setting scale_concurrency: %s", err)) + } + } + if !core.IsNil(function.ScaleCpuLimit) { + if err = d.Set("scale_cpu_limit", function.ScaleCpuLimit); err != nil { + return diag.FromErr(fmt.Errorf("error setting scale_cpu_limit: %s", err)) + } + } + if !core.IsNil(function.ScaleDownDelay) { + if err = d.Set("scale_down_delay", flex.IntValue(function.ScaleDownDelay)); err != nil { + return diag.FromErr(fmt.Errorf("error setting scale_down_delay: %s", err)) + } + } + if !core.IsNil(function.ScaleMaxExecutionTime) { + if err = d.Set("scale_max_execution_time", flex.IntValue(function.ScaleMaxExecutionTime)); err != nil { + return diag.FromErr(fmt.Errorf("error setting scale_max_execution_time: %s", err)) + } + } + if !core.IsNil(function.ScaleMemoryLimit) { + if err = d.Set("scale_memory_limit", function.ScaleMemoryLimit); err != nil { + return diag.FromErr(fmt.Errorf("error setting scale_memory_limit: %s", err)) + } + } + if !core.IsNil(function.CreatedAt) { + if err = d.Set("created_at", function.CreatedAt); err != nil { + return diag.FromErr(fmt.Errorf("error setting created_at: %s", err)) + } + } + if !core.IsNil(function.Endpoint) { + if err = d.Set("endpoint", function.Endpoint); err != nil { + return diag.FromErr(fmt.Errorf("error setting endpoint: %s", err)) + } + } + if !core.IsNil(function.EndpointInternal) { + if err = d.Set("endpoint_internal", function.EndpointInternal); err != nil { + return diag.FromErr(fmt.Errorf("error setting endpoint_internal: %s", err)) + } + } + if err = d.Set("entity_tag", function.EntityTag); err != nil { + return diag.FromErr(fmt.Errorf("error setting entity_tag: %s", err)) + } + if !core.IsNil(function.Href) { + if err = d.Set("href", function.Href); err != nil { + return diag.FromErr(fmt.Errorf("error setting href: %s", err)) + } + } + if !core.IsNil(function.ID) { + if err = d.Set("function_id", function.ID); err != nil { + return diag.FromErr(fmt.Errorf("error setting function_id: %s", err)) + } + } + if !core.IsNil(function.Region) { + if err = d.Set("region", function.Region); err != nil { + return diag.FromErr(fmt.Errorf("error setting region: %s", err)) + } + } + if !core.IsNil(function.ResourceType) { + if err = d.Set("resource_type", function.ResourceType); err != nil { + return diag.FromErr(fmt.Errorf("error setting resource_type: %s", err)) + } + } + if !core.IsNil(function.Status) { + if err = d.Set("status", function.Status); err != nil { + return diag.FromErr(fmt.Errorf("error setting status: %s", err)) + } + } + statusDetailsMap, err := resourceIbmCodeEngineFunctionFunctionStatusToMap(function.StatusDetails) + if err != nil { + return diag.FromErr(err) + } + if err = d.Set("status_details", []map[string]interface{}{statusDetailsMap}); err != nil { + return diag.FromErr(fmt.Errorf("error setting status_details: %s", err)) + } + if err = d.Set("etag", response.Headers.Get("Etag")); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting etag: %s", err), "ibm_code_engine_function", "read") + return tfErr.GetDiag() + } + + return nil +} + +func resourceIbmCodeEngineFunctionUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + codeEngineClient, err := meta.(conns.ClientSession).CodeEngineV2() + if err != nil { + tfErr := flex.TerraformErrorf(err, err.Error(), "ibm_code_engine_function", "update") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + updateFunctionOptions := &codeenginev2.UpdateFunctionOptions{} + + parts, err := flex.SepIdParts(d.Id(), "/") + if err != nil { + tfErr := flex.TerraformErrorf(err, err.Error(), "ibm_code_engine_function", "update") + return tfErr.GetDiag() + } + + updateFunctionOptions.SetProjectID(parts[0]) + updateFunctionOptions.SetName(parts[1]) + + hasChange := false + + patchVals := &codeenginev2.FunctionPatch{} + if d.HasChange("code_binary") { + newCodeBinary := d.Get("code_binary").(bool) + patchVals.CodeBinary = &newCodeBinary + hasChange = true + } + if d.HasChange("code_main") { + newCodeMain := d.Get("code_main").(string) + patchVals.CodeMain = &newCodeMain + hasChange = true + } + if d.HasChange("code_reference") { + newCodeReference := d.Get("code_reference").(string) + patchVals.CodeReference = &newCodeReference + hasChange = true + } + if d.HasChange("code_secret") { + newCodeSecret := d.Get("code_secret").(string) + patchVals.CodeSecret = &newCodeSecret + hasChange = true + } + if d.HasChange("managed_domain_mappings") { + newManagedDomainMappings := d.Get("managed_domain_mappings").(string) + patchVals.ManagedDomainMappings = &newManagedDomainMappings + hasChange = true + } + if d.HasChange("run_env_variables") { + var runEnvVariables []codeenginev2.EnvVarPrototype + for _, v := range d.Get("run_env_variables").([]interface{}) { + value := v.(map[string]interface{}) + runEnvVariablesItem, err := resourceIbmCodeEngineFunctionMapToEnvVarPrototype(value) + if err != nil { + return diag.FromErr(err) + } + runEnvVariables = append(runEnvVariables, *runEnvVariablesItem) + } + patchVals.RunEnvVariables = runEnvVariables + hasChange = true + } + if d.HasChange("runtime") { + newRuntime := d.Get("runtime").(string) + patchVals.Runtime = &newRuntime + hasChange = true + } + if d.HasChange("scale_concurrency") { + newScaleConcurrency := int64(d.Get("scale_concurrency").(int)) + patchVals.ScaleConcurrency = &newScaleConcurrency + hasChange = true + } + if d.HasChange("scale_cpu_limit") { + newScaleCpuLimit := d.Get("scale_cpu_limit").(string) + patchVals.ScaleCpuLimit = &newScaleCpuLimit + hasChange = true + } + if d.HasChange("scale_down_delay") { + newScaleDownDelay := int64(d.Get("scale_down_delay").(int)) + patchVals.ScaleDownDelay = &newScaleDownDelay + hasChange = true + } + if d.HasChange("scale_max_execution_time") { + newScaleMaxExecutionTime := int64(d.Get("scale_max_execution_time").(int)) + patchVals.ScaleMaxExecutionTime = &newScaleMaxExecutionTime + hasChange = true + } + if d.HasChange("scale_memory_limit") { + newScaleMemoryLimit := d.Get("scale_memory_limit").(string) + patchVals.ScaleMemoryLimit = &newScaleMemoryLimit + hasChange = true + } + updateFunctionOptions.SetIfMatch(d.Get("etag").(string)) + + if hasChange { + updateFunctionOptions.Function, _ = patchVals.AsPatch() + + // Fields with `nil` values are omitted from the generic map, + // so we need to re-add them to support removing arguments. + if _, exists := d.GetOk("code_binary"); d.HasChange("code_binary") && !exists { + updateFunctionOptions.Function["code_binary"] = nil + } + if _, exists := d.GetOk("code_main"); d.HasChange("code_main") && !exists { + updateFunctionOptions.Function["code_main"] = nil + } + if _, exists := d.GetOk("code_reference"); d.HasChange("code_reference") && !exists { + updateFunctionOptions.Function["code_reference"] = nil + } + if _, exists := d.GetOk("code_secret"); d.HasChange("code_secret") && !exists { + updateFunctionOptions.Function["code_secret"] = nil + } + if _, exists := d.GetOk("managed_domain_mappings"); d.HasChange("managed_domain_mappings") && !exists { + updateFunctionOptions.Function["managed_domain_mappings"] = nil + } + if _, exists := d.GetOk("run_env_variables"); d.HasChange("run_env_variables") && !exists { + updateFunctionOptions.Function["run_env_variables"] = nil + } + if _, exists := d.GetOk("runtime"); d.HasChange("runtime") && !exists { + updateFunctionOptions.Function["runtime"] = nil + } + if _, exists := d.GetOk("scale_concurrency"); d.HasChange("scale_concurrency") && !exists { + updateFunctionOptions.Function["scale_concurrency"] = nil + } + if _, exists := d.GetOk("scale_cpu_limit"); d.HasChange("scale_cpu_limit") && !exists { + updateFunctionOptions.Function["scale_cpu_limit"] = nil + } + if _, exists := d.GetOk("scale_down_delay"); d.HasChange("scale_down_delay") && !exists { + updateFunctionOptions.Function["scale_down_delay"] = nil + } + if _, exists := d.GetOk("scale_max_execution_time"); d.HasChange("scale_max_execution_time") && !exists { + updateFunctionOptions.Function["scale_max_execution_time"] = nil + } + if _, exists := d.GetOk("scale_memory_limit"); d.HasChange("scale_memory_limit") && !exists { + updateFunctionOptions.Function["scale_memory_limit"] = nil + } + + _, _, err = codeEngineClient.UpdateFunctionWithContext(context, updateFunctionOptions) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateFunctionWithContext failed: %s", err.Error()), "ibm_code_engine_function", "update") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + } + + return resourceIbmCodeEngineFunctionRead(context, d, meta) +} + +func resourceIbmCodeEngineFunctionDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + codeEngineClient, err := meta.(conns.ClientSession).CodeEngineV2() + if err != nil { + tfErr := flex.TerraformErrorf(err, err.Error(), "ibm_code_engine_function", "delete") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + deleteFunctionOptions := &codeenginev2.DeleteFunctionOptions{} + + parts, err := flex.SepIdParts(d.Id(), "/") + if err != nil { + tfErr := flex.TerraformErrorf(err, err.Error(), "ibm_code_engine_function", "delete") + return tfErr.GetDiag() + } + + deleteFunctionOptions.SetProjectID(parts[0]) + deleteFunctionOptions.SetName(parts[1]) + + _, err = codeEngineClient.DeleteFunctionWithContext(context, deleteFunctionOptions) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("DeleteFunctionWithContext failed: %s", err.Error()), "ibm_code_engine_function", "delete") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + d.SetId("") + + return nil +} + +func resourceIbmCodeEngineFunctionMapToEnvVarPrototype(modelMap map[string]interface{}) (*codeenginev2.EnvVarPrototype, error) { + model := &codeenginev2.EnvVarPrototype{} + if modelMap["key"] != nil && modelMap["key"].(string) != "" { + model.Key = core.StringPtr(modelMap["key"].(string)) + } + if modelMap["name"] != nil && modelMap["name"].(string) != "" { + model.Name = core.StringPtr(modelMap["name"].(string)) + } + if modelMap["prefix"] != nil && modelMap["prefix"].(string) != "" { + model.Prefix = core.StringPtr(modelMap["prefix"].(string)) + } + if modelMap["reference"] != nil && modelMap["reference"].(string) != "" { + model.Reference = core.StringPtr(modelMap["reference"].(string)) + } + if modelMap["type"] != nil && modelMap["type"].(string) != "" { + model.Type = core.StringPtr(modelMap["type"].(string)) + } + if modelMap["value"] != nil && modelMap["value"].(string) != "" { + model.Value = core.StringPtr(modelMap["value"].(string)) + } + return model, nil +} + +func resourceIbmCodeEngineFunctionEnvVarToMap(model *codeenginev2.EnvVar) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Key != nil { + modelMap["key"] = *model.Key + } + if model.Name != nil { + modelMap["name"] = *model.Name + } + if model.Prefix != nil { + modelMap["prefix"] = *model.Prefix + } + if model.Reference != nil { + modelMap["reference"] = *model.Reference + } + modelMap["type"] = *model.Type + if model.Value != nil { + modelMap["value"] = *model.Value + } + return modelMap, nil +} + +func resourceIbmCodeEngineFunctionFunctionStatusToMap(model *codeenginev2.FunctionStatus) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Reason != nil { + modelMap["reason"] = *model.Reason + } + return modelMap, nil +} diff --git a/ibm/service/codeengine/resource_ibm_code_engine_function_test.go b/ibm/service/codeengine/resource_ibm_code_engine_function_test.go new file mode 100644 index 0000000000..7110139707 --- /dev/null +++ b/ibm/service/codeengine/resource_ibm_code_engine_function_test.go @@ -0,0 +1,251 @@ +// Copyright IBM Corp. 2024 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package codeengine_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" + "github.com/IBM/code-engine-go-sdk/codeenginev2" +) + +func TestAccIbmCodeEngineFunctionBasic(t *testing.T) { + var conf codeenginev2.Function + functionName := fmt.Sprintf("%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlpha)) + functionRuntime := "nodejs-20" + functionCodeReference := "data:text/plain;base64,foo" + + projectID := acc.CeProjectId + + functionCodeReferenceUpdate := "data:text/plain;base64,bar" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIbmCodeEngineFunctionDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmCodeEngineFunctionConfigBasic(projectID, functionCodeReference, functionName, functionRuntime), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIbmCodeEngineFunctionExists("ibm_code_engine_function.code_engine_function_instance", conf), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "project_id", projectID), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "name", functionName), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "runtime", functionRuntime), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "code_binary", "false"), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "code_reference", functionCodeReference), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "managed_domain_mappings", "local_public"), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "scale_concurrency", "1"), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "scale_cpu_limit", "1"), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "scale_down_delay", "1"), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "scale_max_execution_time", "60"), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "scale_memory_limit", "4G"), + ), + }, + resource.TestStep{ + Config: testAccCheckIbmCodeEngineFunctionConfigBasic(projectID, functionCodeReferenceUpdate, functionName, functionRuntime), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "project_id", projectID), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "name", functionName), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "runtime", functionRuntime), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "code_binary", "false"), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "code_reference", functionCodeReferenceUpdate), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "managed_domain_mappings", "local_public"), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "scale_concurrency", "1"), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "scale_cpu_limit", "1"), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "scale_down_delay", "1"), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "scale_max_execution_time", "60"), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "scale_memory_limit", "4G"), + ), + }, + }, + }) +} + +func TestAccIbmCodeEngineFunctionExtended(t *testing.T) { + var conf codeenginev2.Function + + functionName := fmt.Sprintf("%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlpha)) + functionRuntime := "nodejs-20" + functionCodeReference := "data:text/plain;base64,foo" + functionManagedDomainMappings := "local_public" + functionScaleCpuLimit := "1" + functionScaleDownDelay := "1" + functionScaleMaxExecutionTime := "60" + functionScaleMemoryLimit := "4G" + + projectID := acc.CeProjectId + + functionCodeReferenceUpdate := "data:text/plain;base64,bar" + functionManagedDomainMappingsUpdate := "local_private" + functionScaleCpuLimitUpdate := "0.5" + functionScaleDownDelayUpdate := "20" + functionScaleMaxExecutionTimeUpdate := "30" + functionScaleMemoryLimitUpdate := "2G" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIbmCodeEngineFunctionDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmCodeEngineFunctionConfig(projectID, functionCodeReference, functionManagedDomainMappings, functionName, functionRuntime, functionScaleCpuLimit, functionScaleDownDelay, functionScaleMaxExecutionTime, functionScaleMemoryLimit), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIbmCodeEngineFunctionExists("ibm_code_engine_function.code_engine_function_instance", conf), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "project_id", projectID), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "name", functionName), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "runtime", functionRuntime), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "code_binary", "false"), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "code_reference", functionCodeReference), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "managed_domain_mappings", functionManagedDomainMappings), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "scale_concurrency", "1"), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "scale_cpu_limit", functionScaleCpuLimit), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "scale_down_delay", functionScaleDownDelay), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "scale_max_execution_time", functionScaleMaxExecutionTime), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "scale_memory_limit", functionScaleMemoryLimit), + ), + }, + resource.TestStep{ + Config: testAccCheckIbmCodeEngineFunctionConfig(projectID, functionCodeReferenceUpdate, functionManagedDomainMappingsUpdate, functionName, functionRuntime, functionScaleCpuLimitUpdate, functionScaleDownDelayUpdate, functionScaleMaxExecutionTimeUpdate, functionScaleMemoryLimitUpdate), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "project_id", projectID), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "name", functionName), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "runtime", functionRuntime), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "code_binary", "false"), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "code_reference", functionCodeReferenceUpdate), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "managed_domain_mappings", functionManagedDomainMappingsUpdate), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "scale_concurrency", "1"), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "scale_cpu_limit", functionScaleCpuLimitUpdate), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "scale_down_delay", functionScaleDownDelayUpdate), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "scale_max_execution_time", functionScaleMaxExecutionTimeUpdate), + resource.TestCheckResourceAttr("ibm_code_engine_function.code_engine_function_instance", "scale_memory_limit", functionScaleMemoryLimitUpdate), + ), + }, + }, + }) +} + +func testAccCheckIbmCodeEngineFunctionConfigBasic(projectID string, codeReference string, name string, runtime string) string { + return fmt.Sprintf(` + data "ibm_code_engine_project" "code_engine_project_instance" { + project_id = "%s" + } + + resource "ibm_code_engine_function" "code_engine_function_instance" { + project_id = data.ibm_code_engine_project.code_engine_project_instance.project_id + code_reference = "%s" + name = "%s" + runtime = "%s" + + lifecycle { + ignore_changes = [ + run_env_variables + ] + } + } + `, projectID, codeReference, name, runtime) +} + +func testAccCheckIbmCodeEngineFunctionConfig(projectID string, codeReference string, managedDomainMappings string, name string, runtime string, scaleCpuLimit string, scaleDownDelay string, scaleMaxExecutionTime string, scaleMemoryLimit string) string { + return fmt.Sprintf(` + data "ibm_code_engine_project" "code_engine_project_instance" { + project_id = "%s" + } + + resource "ibm_code_engine_function" "code_engine_function_instance" { + project_id = data.ibm_code_engine_project.code_engine_project_instance.project_id + code_reference = "%s" + managed_domain_mappings = "%s" + name = "%s" + runtime = "%s" + scale_cpu_limit = "%s" + scale_down_delay = %s + scale_max_execution_time = %s + scale_memory_limit = "%s" + run_env_variables { + type = "literal" + name = "name" + value = "value" + } + + lifecycle { + ignore_changes = [ + run_env_variables + ] + } + } + `, projectID, codeReference, managedDomainMappings, name, runtime, scaleCpuLimit, scaleDownDelay, scaleMaxExecutionTime, scaleMemoryLimit) +} + +func testAccCheckIbmCodeEngineFunctionExists(n string, obj codeenginev2.Function) resource.TestCheckFunc { + + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + codeEngineClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).CodeEngineV2() + if err != nil { + return err + } + + getFunctionOptions := &codeenginev2.GetFunctionOptions{} + + parts, err := flex.SepIdParts(rs.Primary.ID, "/") + if err != nil { + return err + } + + getFunctionOptions.SetProjectID(parts[0]) + getFunctionOptions.SetName(parts[1]) + + function, _, err := codeEngineClient.GetFunction(getFunctionOptions) + if err != nil { + return err + } + + obj = *function + return nil + } +} + +func testAccCheckIbmCodeEngineFunctionDestroy(s *terraform.State) error { + codeEngineClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).CodeEngineV2() + if err != nil { + return err + } + for _, rs := range s.RootModule().Resources { + if rs.Type != "ibm_code_engine_function" { + continue + } + + getFunctionOptions := &codeenginev2.GetFunctionOptions{} + + parts, err := flex.SepIdParts(rs.Primary.ID, "/") + if err != nil { + return err + } + + getFunctionOptions.SetProjectID(parts[0]) + getFunctionOptions.SetName(parts[1]) + + // Try to find the key + _, response, err := codeEngineClient.GetFunction(getFunctionOptions) + + if err == nil { + return fmt.Errorf("code_engine_function still exists: %s", rs.Primary.ID) + } else if response.StatusCode != 404 { + return fmt.Errorf("Error checking for code_engine_function (%s) has been destroyed: %s", rs.Primary.ID, err) + } + } + + return nil +} diff --git a/ibm/service/configurationaggregator/README.md b/ibm/service/configurationaggregator/README.md new file mode 100644 index 0000000000..a6838d1cb7 --- /dev/null +++ b/ibm/service/configurationaggregator/README.md @@ -0,0 +1,11 @@ +# Terraform IBM Provider + +This area is primarily for IBM provider contributors and maintainers. For information on _using_ Terraform and the IBM provider, see the links below. + + +## Handy Links +* [Find out about contributing](../../../CONTRIBUTING.md) to the IBM provider! +* IBM Provider Docs: [Home](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs) +* IBM Provider Docs: [One of the resources](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs/resources/config_aggregator_settings) +* IBM API Docs: [IBM API Docs for ]() +* IBM SDK: [IBM SDK for ](https://github.com/IBM/appconfiguration-go-admin-sdk/tree/master/configurationaggregatorv1) diff --git a/ibm/service/configurationaggregator/data_source_ibm_config_aggregator_configurations.go b/ibm/service/configurationaggregator/data_source_ibm_config_aggregator_configurations.go new file mode 100644 index 0000000000..08a4d8f326 --- /dev/null +++ b/ibm/service/configurationaggregator/data_source_ibm_config_aggregator_configurations.go @@ -0,0 +1,281 @@ +// Copyright IBM Corp. 2024 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.92.0-af5c89a5-20240617-153232 + */ + +package configurationaggregator + +import ( + "context" + "fmt" + "log" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/IBM/configuration-aggregator-go-sdk/configurationaggregatorv1" + + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" +) + +func DataSourceIbmConfigAggregatorConfigurations() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmConfigAggregatorConfigurationsRead, + + Schema: map[string]*schema.Schema{ + "config_type": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "The type of resource configuration that are to be retrieved.", + }, + "service_name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "The name of the IBM Cloud service for which resources are to be retrieved.", + }, + "resource_group_id": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "The resource group id of the resources.", + }, + "location": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "The location or region in which the resources are created.", + }, + "resource_crn": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "The crn of the resource.", + }, + "prev": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The reference to the previous page of entries.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "href": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The reference to the previous page of entries.", + }, + "start": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "the start string for the query to view the page.", + }, + }, + }, + }, + "configs": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Array of resource configurations.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "about": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The basic metadata fetched from the query API.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The account ID in which the resource exists.", + }, + "config_type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The type of configuration of the retrieved resource.", + }, + "resource_crn": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The unique CRN of the IBM Cloud resource.", + }, + "resource_group_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The account ID.", + }, + "service_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The name of the service to which the resources belongs.", + }, + "resource_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "User defined name of the resource.", + }, + "last_config_refresh_time": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Date/time stamp identifying when the information was last collected. Must be in the RFC 3339 format.", + }, + "location": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Location of the resource specified.", + }, + "tags": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Tags associated with the resource.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "tag": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The name of the tag.", + }, + }, + }, + }, + }, + }, + }, + "config": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The configuration of the resource.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{}, + }, + }, + }, + }, + }, + }, + } +} + +func dataSourceIbmConfigAggregatorConfigurationsRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + configurationAggregatorClient, err := meta.(conns.ClientSession).ConfigurationAggregatorV1() + if err != nil { + tfErr := flex.TerraformErrorf(err, err.Error(), "(Data) ibm_config_aggregator_configurations", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + listConfigsOptions := &configurationaggregatorv1.ListConfigsOptions{} + + if _, ok := d.GetOk("config_type"); ok { + listConfigsOptions.SetConfigType(d.Get("config_type").(string)) + } + if _, ok := d.GetOk("service_name"); ok { + listConfigsOptions.SetServiceName(d.Get("service_name").(string)) + } + if _, ok := d.GetOk("resource_group_id"); ok { + listConfigsOptions.SetResourceGroupID(d.Get("resource_group_id").(string)) + } + if _, ok := d.GetOk("location"); ok { + listConfigsOptions.SetLocation(d.Get("location").(string)) + } + if _, ok := d.GetOk("resource_crn"); ok { + listConfigsOptions.SetResourceCrn(d.Get("resource_crn").(string)) + } + + var pager *configurationaggregatorv1.ConfigsPager + pager, err = configurationAggregatorClient.NewConfigsPager(listConfigsOptions) + if err != nil { + tfErr := flex.TerraformErrorf(err, err.Error(), "(Data) ibm_config_aggregator_configurations", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + allItems, err := pager.GetAll() + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("ConfigsPager.GetAll() failed %s", err), "(Data) ibm_config_aggregator_configurations", "read") + log.Printf("[DEBUG] %s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + d.SetId(dataSourceIbmConfigAggregatorConfigurationsID(d)) + + mapSlice := []map[string]interface{}{} + for _, modelItem := range allItems { + modelMap, err := DataSourceIbmConfigAggregatorConfigurationsConfigToMap(&modelItem) + if err != nil { + tfErr := flex.TerraformErrorf(err, err.Error(), "(Data) ibm_config_aggregator_configurations", "read") + return tfErr.GetDiag() + } + mapSlice = append(mapSlice, modelMap) + } + + if err = d.Set("configs", mapSlice); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting configs %s", err), "(Data) ibm_config_aggregator_configurations", "read") + return tfErr.GetDiag() + } + + return nil +} + +// dataSourceIbmConfigAggregatorConfigurationsID returns a reasonable ID for the list. +func dataSourceIbmConfigAggregatorConfigurationsID(d *schema.ResourceData) string { + return time.Now().UTC().String() +} + +func DataSourceIbmConfigAggregatorConfigurationsPaginatedPreviousToMap(model *configurationaggregatorv1.PaginatedPrevious) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Href != nil { + modelMap["href"] = *model.Href + } + if model.Start != nil { + modelMap["start"] = *model.Start + } + return modelMap, nil +} + +func DataSourceIbmConfigAggregatorConfigurationsConfigToMap(model *configurationaggregatorv1.Config) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + aboutMap, err := DataSourceIbmConfigAggregatorConfigurationsAboutToMap(model.About) + if err != nil { + return modelMap, err + } + modelMap["about"] = []map[string]interface{}{aboutMap} + configMap, err := DataSourceIbmConfigAggregatorConfigurationsConfigurationToMap(model.Config) + if err != nil { + return modelMap, err + } + modelMap["config"] = []map[string]interface{}{configMap} + return modelMap, nil +} + +func DataSourceIbmConfigAggregatorConfigurationsAboutToMap(model *configurationaggregatorv1.About) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + modelMap["account_id"] = *model.AccountID + modelMap["config_type"] = *model.ConfigType + modelMap["resource_crn"] = *model.ResourceCrn + modelMap["resource_group_id"] = *model.ResourceGroupID + modelMap["service_name"] = *model.ServiceName + modelMap["resource_name"] = *model.ResourceName + modelMap["last_config_refresh_time"] = model.LastConfigRefreshTime.String() + modelMap["location"] = *model.Location + if model.Tags != nil { + tagsMap, err := DataSourceIbmConfigAggregatorConfigurationsTagsToMap(model.Tags) + if err != nil { + return modelMap, err + } + modelMap["tags"] = []map[string]interface{}{tagsMap} + } + return modelMap, nil +} + +func DataSourceIbmConfigAggregatorConfigurationsTagsToMap(model *configurationaggregatorv1.Tags) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Tag != nil { + modelMap["tag"] = *model.Tag + } + return modelMap, nil +} + +func DataSourceIbmConfigAggregatorConfigurationsConfigurationToMap(model *configurationaggregatorv1.Configuration) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + return modelMap, nil +} diff --git a/ibm/service/configurationaggregator/data_source_ibm_config_aggregator_configurations_test.go b/ibm/service/configurationaggregator/data_source_ibm_config_aggregator_configurations_test.go new file mode 100644 index 0000000000..3c3d1cbc42 --- /dev/null +++ b/ibm/service/configurationaggregator/data_source_ibm_config_aggregator_configurations_test.go @@ -0,0 +1,186 @@ +// Copyright IBM Corp. 2024 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.92.0-af5c89a5-20240617-153232 + */ + +package configurationaggregator_test + +import ( + "fmt" + "testing" + + "github.com/IBM/configuration-aggregator-go-sdk/configurationaggregatorv1" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/service/configurationaggregator" + . "github.com/IBM-Cloud/terraform-provider-ibm/ibm/unittest" + "github.com/IBM/go-sdk-core/v5/core" + "github.com/stretchr/testify/assert" +) + +func TestAccIbmConfigAggregatorConfigurationsDataSourceBasic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmConfigAggregatorConfigurationsDataSourceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_config_aggregator_configurations.config_aggregator_configurations_instance", "id"), + ), + }, + }, + }) +} + +func testAccCheckIbmConfigAggregatorConfigurationsDataSourceConfigBasic() string { + return fmt.Sprintf(` + data "ibm_config_aggregator_configurations" "config_aggregator_configurations_instance" { + config_type = "config_type" + service_name = "service_name" + resource_group_id = "resource_group_id" + location = "location" + resource_crn = "resource_crn" + } + `) +} + +func TestDataSourceIbmConfigAggregatorConfigurationsPaginatedPreviousToMap(t *testing.T) { + checkResult := func(result map[string]interface{}) { + model := make(map[string]interface{}) + model["href"] = "testString" + model["start"] = "testString" + + assert.Equal(t, result, model) + } + + model := new(configurationaggregatorv1.PaginatedPrevious) + model.Href = core.StringPtr("testString") + model.Start = core.StringPtr("testString") + + result, err := configurationaggregator.DataSourceIbmConfigAggregatorConfigurationsPaginatedPreviousToMap(model) + assert.Nil(t, err) + checkResult(result) +} + +func TestDataSourceIbmConfigAggregatorConfigurationsConfigToMap(t *testing.T) { + checkResult := func(result map[string]interface{}) { + tagsModel := make(map[string]interface{}) + tagsModel["tag"] = "testString" + + aboutModel := make(map[string]interface{}) + aboutModel["account_id"] = "testString" + aboutModel["config_type"] = "testString" + aboutModel["resource_crn"] = "testString" + aboutModel["resource_group_id"] = "testString" + aboutModel["service_name"] = "testString" + aboutModel["resource_name"] = "testString" + aboutModel["last_config_refresh_time"] = "2019-01-01T12:00:00.000Z" + aboutModel["location"] = "testString" + aboutModel["tags"] = []map[string]interface{}{tagsModel} + + configurationModel := make(map[string]interface{}) + + model := make(map[string]interface{}) + model["about"] = []map[string]interface{}{aboutModel} + model["config"] = []map[string]interface{}{configurationModel} + + assert.Equal(t, result, model) + } + + tagsModel := new(configurationaggregatorv1.Tags) + tagsModel.Tag = core.StringPtr("testString") + + aboutModel := new(configurationaggregatorv1.About) + aboutModel.AccountID = core.StringPtr("testString") + aboutModel.ConfigType = core.StringPtr("testString") + aboutModel.ResourceCrn = core.StringPtr("testString") + aboutModel.ResourceGroupID = core.StringPtr("testString") + aboutModel.ServiceName = core.StringPtr("testString") + aboutModel.ResourceName = core.StringPtr("testString") + aboutModel.LastConfigRefreshTime = CreateMockDateTime("2019-01-01T12:00:00.000Z") + aboutModel.Location = core.StringPtr("testString") + aboutModel.Tags = tagsModel + + configurationModel := new(configurationaggregatorv1.Configuration) + + model := new(configurationaggregatorv1.Config) + model.About = aboutModel + model.Config = configurationModel + + result, err := configurationaggregator.DataSourceIbmConfigAggregatorConfigurationsConfigToMap(model) + assert.Nil(t, err) + checkResult(result) +} + +func TestDataSourceIbmConfigAggregatorConfigurationsAboutToMap(t *testing.T) { + checkResult := func(result map[string]interface{}) { + tagsModel := make(map[string]interface{}) + tagsModel["tag"] = "testString" + + model := make(map[string]interface{}) + model["account_id"] = "testString" + model["config_type"] = "testString" + model["resource_crn"] = "testString" + model["resource_group_id"] = "testString" + model["service_name"] = "testString" + model["resource_name"] = "testString" + model["last_config_refresh_time"] = "2019-01-01T12:00:00.000Z" + model["location"] = "testString" + model["tags"] = []map[string]interface{}{tagsModel} + + assert.Equal(t, result, model) + } + + tagsModel := new(configurationaggregatorv1.Tags) + tagsModel.Tag = core.StringPtr("testString") + + model := new(configurationaggregatorv1.About) + model.AccountID = core.StringPtr("testString") + model.ConfigType = core.StringPtr("testString") + model.ResourceCrn = core.StringPtr("testString") + model.ResourceGroupID = core.StringPtr("testString") + model.ServiceName = core.StringPtr("testString") + model.ResourceName = core.StringPtr("testString") + model.LastConfigRefreshTime = CreateMockDateTime("2019-01-01T12:00:00.000Z") + model.Location = core.StringPtr("testString") + model.Tags = tagsModel + + result, err := configurationaggregator.DataSourceIbmConfigAggregatorConfigurationsAboutToMap(model) + assert.Nil(t, err) + checkResult(result) +} + +func TestDataSourceIbmConfigAggregatorConfigurationsTagsToMap(t *testing.T) { + checkResult := func(result map[string]interface{}) { + model := make(map[string]interface{}) + model["tag"] = "testString" + + assert.Equal(t, result, model) + } + + model := new(configurationaggregatorv1.Tags) + model.Tag = core.StringPtr("testString") + + result, err := configurationaggregator.DataSourceIbmConfigAggregatorConfigurationsTagsToMap(model) + assert.Nil(t, err) + checkResult(result) +} + +func TestDataSourceIbmConfigAggregatorConfigurationsConfigurationToMap(t *testing.T) { + checkResult := func(result map[string]interface{}) { + model := make(map[string]interface{}) + + assert.Equal(t, result, model) + } + + model := new(configurationaggregatorv1.Configuration) + + result, err := configurationaggregator.DataSourceIbmConfigAggregatorConfigurationsConfigurationToMap(model) + assert.Nil(t, err) + checkResult(result) +} diff --git a/ibm/service/configurationaggregator/data_source_ibm_config_aggregator_resource_collection_status.go b/ibm/service/configurationaggregator/data_source_ibm_config_aggregator_resource_collection_status.go new file mode 100644 index 0000000000..d63778c93d --- /dev/null +++ b/ibm/service/configurationaggregator/data_source_ibm_config_aggregator_resource_collection_status.go @@ -0,0 +1,78 @@ +// Copyright IBM Corp. 2024 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.92.0-af5c89a5-20240617-153232 + */ + +package configurationaggregator + +import ( + "context" + "fmt" + "log" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/IBM/configuration-aggregator-go-sdk/configurationaggregatorv1" + + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" +) + +func DataSourceIbmConfigAggregatorResourceCollectionStatus() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmConfigAggregatorResourceCollectionStatusRead, + + Schema: map[string]*schema.Schema{ + "last_config_refresh_time": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The timestamp at which the configuration was last refreshed.", + }, + "status": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Status of the resource collection.", + }, + }, + } +} + +func dataSourceIbmConfigAggregatorResourceCollectionStatusRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + configurationAggregatorClient, err := meta.(conns.ClientSession).ConfigurationAggregatorV1() + if err != nil { + // Error is coming from SDK client, so it doesn't need to be discriminated. + tfErr := flex.TerraformErrorf(err, err.Error(), "(Data) ibm_config_aggregator_resource_collection_status", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + getResourceCollectionStatusOptions := &configurationaggregatorv1.GetResourceCollectionStatusOptions{} + + statusResponse, _, err := configurationAggregatorClient.GetResourceCollectionStatusWithContext(context, getResourceCollectionStatusOptions) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetResourceCollectionStatusWithContext failed: %s", err.Error()), "(Data) ibm_config_aggregator_resource_collection_status", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + d.SetId(dataSourceIbmConfigAggregatorResourceCollectionStatusID(d)) + + if err = d.Set("last_config_refresh_time", flex.DateTimeToString(statusResponse.LastConfigRefreshTime)); err != nil { + return flex.DiscriminatedTerraformErrorf(err, fmt.Sprintf("Error setting last_config_refresh_time: %s", err), "(Data) ibm_config_aggregator_resource_collection_status", "read", "set-last_config_refresh_time").GetDiag() + } + + if err = d.Set("status", statusResponse.Status); err != nil { + return flex.DiscriminatedTerraformErrorf(err, fmt.Sprintf("Error setting status: %s", err), "(Data) ibm_config_aggregator_resource_collection_status", "read", "set-status").GetDiag() + } + + return nil +} + +// dataSourceIbmConfigAggregatorResourceCollectionStatusID returns a reasonable ID for the list. +func dataSourceIbmConfigAggregatorResourceCollectionStatusID(d *schema.ResourceData) string { + return time.Now().UTC().String() +} diff --git a/ibm/service/configurationaggregator/data_source_ibm_config_aggregator_resource_collection_status_test.go b/ibm/service/configurationaggregator/data_source_ibm_config_aggregator_resource_collection_status_test.go new file mode 100644 index 0000000000..62721f071d --- /dev/null +++ b/ibm/service/configurationaggregator/data_source_ibm_config_aggregator_resource_collection_status_test.go @@ -0,0 +1,39 @@ +// Copyright IBM Corp. 2024 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.92.0-af5c89a5-20240617-153232 + */ + +package configurationaggregator_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmConfigAggregatorResourceCollectionStatusDataSourceBasic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmConfigAggregatorResourceCollectionStatusDataSourceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_config_aggregator_resource_collection_status.config_aggregator_resource_collection_status_instance", "id"), + ), + }, + }, + }) +} + +func testAccCheckIbmConfigAggregatorResourceCollectionStatusDataSourceConfigBasic() string { + return fmt.Sprintf(` + data "ibm_config_aggregator_resource_collection_status" "config_aggregator_resource_collection_status_instance" { + } + `) +} diff --git a/ibm/service/configurationaggregator/data_source_ibm_config_aggregator_settings.go b/ibm/service/configurationaggregator/data_source_ibm_config_aggregator_settings.go new file mode 100644 index 0000000000..4a1789384c --- /dev/null +++ b/ibm/service/configurationaggregator/data_source_ibm_config_aggregator_settings.go @@ -0,0 +1,176 @@ +// Copyright IBM Corp. 2024 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.92.0-af5c89a5-20240617-153232 + */ + +package configurationaggregator + +import ( + "context" + "fmt" + "log" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/IBM/configuration-aggregator-go-sdk/configurationaggregatorv1" + + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" +) + +func DataSourceIbmConfigAggregatorSettings() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmConfigAggregatorSettingsRead, + + Schema: map[string]*schema.Schema{ + "resource_collection_enabled": &schema.Schema{ + Type: schema.TypeBool, + Computed: true, + Description: "The field to check if the resource collection is enabled.", + }, + "trusted_profile_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The trusted profile ID that provides access to App Configuration instance to retrieve resource metadata.", + }, + "last_updated": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The last time the settings was last updated.", + }, + "regions": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Regions for which the resource collection is enabled.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "additional_scope": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The additional scope that enables resource collection for Enterprise acccounts.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The type of scope. Currently allowed value is Enterprise.", + }, + "enterprise_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The Enterprise ID.", + }, + "profile_template": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "The Profile Template details applied on the enterprise account.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The Profile Template ID created in the enterprise account that provides access to App Configuration instance for resource collection.", + }, + "trusted_profile_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "The trusted profile ID that provides access to App Configuration instance to retrieve template information.", + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func dataSourceIbmConfigAggregatorSettingsRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + configurationAggregatorClient, err := meta.(conns.ClientSession).ConfigurationAggregatorV1() + if err != nil { + // Error is coming from SDK client, so it doesn't need to be discriminated. + tfErr := flex.TerraformErrorf(err, err.Error(), "(Data) ibm_config_aggregator_settings", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + getSettingsOptions := &configurationaggregatorv1.GetSettingsOptions{} + + settingsResponse, _, err := configurationAggregatorClient.GetSettingsWithContext(context, getSettingsOptions) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSettingsWithContext failed: %s", err.Error()), "(Data) ibm_config_aggregator_settings", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + d.SetId(dataSourceIbmConfigAggregatorSettingsID(d)) + + if err = d.Set("resource_collection_enabled", settingsResponse.ResourceCollectionEnabled); err != nil { + return flex.DiscriminatedTerraformErrorf(err, fmt.Sprintf("Error setting resource_collection_enabled: %s", err), "(Data) ibm_config_aggregator_settings", "read", "set-resource_collection_enabled").GetDiag() + } + + if err = d.Set("trusted_profile_id", settingsResponse.TrustedProfileID); err != nil { + return flex.DiscriminatedTerraformErrorf(err, fmt.Sprintf("Error setting trusted_profile_id: %s", err), "(Data) ibm_config_aggregator_settings", "read", "set-trusted_profile_id").GetDiag() + } + + if err = d.Set("last_updated", flex.DateTimeToString(settingsResponse.LastUpdated)); err != nil { + return flex.DiscriminatedTerraformErrorf(err, fmt.Sprintf("Error setting last_updated: %s", err), "(Data) ibm_config_aggregator_settings", "read", "set-last_updated").GetDiag() + } + + additionalScope := []map[string]interface{}{} + if settingsResponse.AdditionalScope != nil { + for _, modelItem := range settingsResponse.AdditionalScope { + modelMap, err := DataSourceIbmConfigAggregatorSettingsAdditionalScopeToMap(&modelItem) + if err != nil { + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "(Data) ibm_config_aggregator_settings", "read", "additional_scope-to-map").GetDiag() + } + additionalScope = append(additionalScope, modelMap) + } + } + if err = d.Set("additional_scope", additionalScope); err != nil { + return flex.DiscriminatedTerraformErrorf(err, fmt.Sprintf("Error setting additional_scope: %s", err), "(Data) ibm_config_aggregator_settings", "read", "set-additional_scope").GetDiag() + } + + return nil +} + +// dataSourceIbmConfigAggregatorSettingsID returns a reasonable ID for the list. +func dataSourceIbmConfigAggregatorSettingsID(d *schema.ResourceData) string { + return time.Now().UTC().String() +} + +func DataSourceIbmConfigAggregatorSettingsAdditionalScopeToMap(model *configurationaggregatorv1.AdditionalScope) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Type != nil { + modelMap["type"] = *model.Type + } + if model.EnterpriseID != nil { + modelMap["enterprise_id"] = *model.EnterpriseID + } + if model.ProfileTemplate != nil { + profileTemplateMap, err := DataSourceIbmConfigAggregatorSettingsProfileTemplateToMap(model.ProfileTemplate) + if err != nil { + return modelMap, err + } + modelMap["profile_template"] = []map[string]interface{}{profileTemplateMap} + } + return modelMap, nil +} + +func DataSourceIbmConfigAggregatorSettingsProfileTemplateToMap(model *configurationaggregatorv1.ProfileTemplate) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ID != nil { + modelMap["id"] = *model.ID + } + if model.TrustedProfileID != nil { + modelMap["trusted_profile_id"] = *model.TrustedProfileID + } + return modelMap, nil +} diff --git a/ibm/service/configurationaggregator/data_source_ibm_config_aggregator_settings_test.go b/ibm/service/configurationaggregator/data_source_ibm_config_aggregator_settings_test.go new file mode 100644 index 0000000000..1ce3147628 --- /dev/null +++ b/ibm/service/configurationaggregator/data_source_ibm_config_aggregator_settings_test.go @@ -0,0 +1,90 @@ +// Copyright IBM Corp. 2024 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.92.0-af5c89a5-20240617-153232 + */ + +package configurationaggregator_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + "github.com/IBM/configuration-aggregator-go-sdk/configurationaggregatorv1" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/service/configurationaggregator" + "github.com/IBM/go-sdk-core/v5/core" + "github.com/stretchr/testify/assert" +) + +func TestAccIbmConfigAggregatorSettingsDataSourceBasic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmConfigAggregatorSettingsDataSourceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_config_aggregator_settings.config_aggregator_settings_instance", "id"), + ), + }, + }, + }) +} + +func testAccCheckIbmConfigAggregatorSettingsDataSourceConfigBasic() string { + return fmt.Sprintf(` + data "ibm_config_aggregator_settings" "config_aggregator_settings_instance" { + } + `) +} + +func TestDataSourceIbmConfigAggregatorSettingsAdditionalScopeToMap(t *testing.T) { + checkResult := func(result map[string]interface{}) { + profileTemplateModel := make(map[string]interface{}) + profileTemplateModel["id"] = "ProfileTemplate-adb55769-ae22-4c60-aead-bd1f84f93c57" + profileTemplateModel["trusted_profile_id"] = "Profile-6bb60124-8fc3-4d18-b63d-0b99560865d3" + + model := make(map[string]interface{}) + model["type"] = "Enterprise" + model["enterprise_id"] = "testString" + model["profile_template"] = []map[string]interface{}{profileTemplateModel} + + assert.Equal(t, result, model) + } + + profileTemplateModel := new(configurationaggregatorv1.ProfileTemplate) + profileTemplateModel.ID = core.StringPtr("ProfileTemplate-adb55769-ae22-4c60-aead-bd1f84f93c57") + profileTemplateModel.TrustedProfileID = core.StringPtr("Profile-6bb60124-8fc3-4d18-b63d-0b99560865d3") + + model := new(configurationaggregatorv1.AdditionalScope) + model.Type = core.StringPtr("Enterprise") + model.EnterpriseID = core.StringPtr("testString") + model.ProfileTemplate = profileTemplateModel + + result, err := configurationaggregator.DataSourceIbmConfigAggregatorSettingsAdditionalScopeToMap(model) + assert.Nil(t, err) + checkResult(result) +} + +func TestDataSourceIbmConfigAggregatorSettingsProfileTemplateToMap(t *testing.T) { + checkResult := func(result map[string]interface{}) { + model := make(map[string]interface{}) + model["id"] = "ProfileTemplate-adb55769-ae22-4c60-aead-bd1f84f93c57" + model["trusted_profile_id"] = "Profile-6bb60124-8fc3-4d18-b63d-0b99560865d3" + + assert.Equal(t, result, model) + } + + model := new(configurationaggregatorv1.ProfileTemplate) + model.ID = core.StringPtr("ProfileTemplate-adb55769-ae22-4c60-aead-bd1f84f93c57") + model.TrustedProfileID = core.StringPtr("Profile-6bb60124-8fc3-4d18-b63d-0b99560865d3") + + result, err := configurationaggregator.DataSourceIbmConfigAggregatorSettingsProfileTemplateToMap(model) + assert.Nil(t, err) + checkResult(result) +} diff --git a/ibm/service/configurationaggregator/resource_ibm_config_aggregator_settings.go b/ibm/service/configurationaggregator/resource_ibm_config_aggregator_settings.go new file mode 100644 index 0000000000..5f3ae83930 --- /dev/null +++ b/ibm/service/configurationaggregator/resource_ibm_config_aggregator_settings.go @@ -0,0 +1,285 @@ +// Copyright IBM Corp. 2024 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.92.0-af5c89a5-20240617-153232 + */ + +package configurationaggregator + +import ( + "context" + "fmt" + "log" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/IBM/configuration-aggregator-go-sdk/configurationaggregatorv1" + + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" + "github.com/IBM/go-sdk-core/v5/core" +) + +func ResourceIbmConfigAggregatorSettings() *schema.Resource { + return &schema.Resource{ + CreateContext: resourceIbmConfigAggregatorSettingsCreate, + ReadContext: resourceIbmConfigAggregatorSettingsRead, + DeleteContext: resourceIbmConfigAggregatorSettingsDelete, + Importer: &schema.ResourceImporter{}, + + Schema: map[string]*schema.Schema{ + "resource_collection_enabled": &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + ForceNew: true, + Description: "The field denoting if the resource collection is enabled.", + }, + "trusted_profile_id": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: validate.InvokeValidator("ibm_config_aggregator_settings", "trusted_profile_id"), + Description: "The trusted profile id that provides Reader access to the App Configuration instance to collect resource metadata.", + }, + "regions": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Description: "The list of regions across which the resource collection is enabled.", + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "additional_scope": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Description: "The additional scope that enables resource collection for Enterprise acccounts.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "type": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "The type of scope. Currently allowed value is Enterprise.", + }, + "enterprise_id": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "The Enterprise ID.", + }, + "profile_template": &schema.Schema{ + Type: schema.TypeList, + MaxItems: 1, + Optional: true, + Description: "The Profile Template details applied on the enterprise account.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "The Profile Template ID created in the enterprise account that provides access to App Configuration instance for resource collection.", + }, + "trusted_profile_id": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "The trusted profile ID that provides access to App Configuration instance to retrieve template information.", + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func ResourceIbmConfigAggregatorSettingsValidator() *validate.ResourceValidator { + validateSchema := make([]validate.ValidateSchema, 0) + validateSchema = append(validateSchema, + validate.ValidateSchema{ + Identifier: "trusted_profile_id", + ValidateFunctionIdentifier: validate.ValidateRegexpLen, + Type: validate.TypeString, + Optional: true, + Regexp: `^[a-zA-Z0-9-]*$`, + MinValueLength: 44, + MaxValueLength: 44, + }, + ) + + resourceValidator := validate.ResourceValidator{ResourceName: "ibm_config_aggregator_settings", Schema: validateSchema} + return &resourceValidator +} + +func resourceIbmConfigAggregatorSettingsCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + configurationAggregatorClient, err := meta.(conns.ClientSession).ConfigurationAggregatorV1() + if err != nil { + // Error is coming from SDK client, so it doesn't need to be discriminated. + tfErr := flex.TerraformErrorf(err, err.Error(), "ibm_config_aggregator_settings", "create") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + replaceSettingsOptions := &configurationaggregatorv1.ReplaceSettingsOptions{} + + if _, ok := d.GetOk("resource_collection_enabled"); ok { + replaceSettingsOptions.SetResourceCollectionEnabled(d.Get("resource_collection_enabled").(bool)) + } + if _, ok := d.GetOk("trusted_profile_id"); ok { + replaceSettingsOptions.SetTrustedProfileID(d.Get("trusted_profile_id").(string)) + } + if _, ok := d.GetOk("regions"); ok { + var regions []string + for _, v := range d.Get("regions").([]interface{}) { + regionsItem := v.(string) + regions = append(regions, regionsItem) + } + replaceSettingsOptions.SetRegions(regions) + } + if _, ok := d.GetOk("additional_scope"); ok { + var additionalScope []configurationaggregatorv1.AdditionalScope + for _, v := range d.Get("additional_scope").([]interface{}) { + value := v.(map[string]interface{}) + additionalScopeItem, err := ResourceIbmConfigAggregatorSettingsMapToAdditionalScope(value) + if err != nil { + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "ibm_config_aggregator_settings", "create", "parse-additional_scope").GetDiag() + } + additionalScope = append(additionalScope, *additionalScopeItem) + } + replaceSettingsOptions.SetAdditionalScope(additionalScope) + } + + settingsResponse, _, err := configurationAggregatorClient.ReplaceSettingsWithContext(context, replaceSettingsOptions) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("ReplaceSettingsWithContext failed: %s", err.Error()), "ibm_config_aggregator_settings", "create") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + d.SetId(*settingsResponse.TrustedProfileID) + + return resourceIbmConfigAggregatorSettingsRead(context, d, meta) +} + +func resourceIbmConfigAggregatorSettingsRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + configurationAggregatorClient, err := meta.(conns.ClientSession).ConfigurationAggregatorV1() + if err != nil { + tfErr := flex.TerraformErrorf(err, err.Error(), "ibm_config_aggregator_settings", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + getSettingsOptions := &configurationaggregatorv1.GetSettingsOptions{} + + settingsResponse, response, err := configurationAggregatorClient.GetSettingsWithContext(context, getSettingsOptions) + if err != nil { + if response != nil && response.StatusCode == 404 { + d.SetId("") + return nil + } + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSettingsWithContext failed: %s", err.Error()), "ibm_config_aggregator_settings", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + if !core.IsNil(settingsResponse.ResourceCollectionEnabled) { + if err = d.Set("resource_collection_enabled", settingsResponse.ResourceCollectionEnabled); err != nil { + err = fmt.Errorf("Error setting resource_collection_enabled: %s", err) + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "ibm_config_aggregator_settings", "read", "set-resource_collection_enabled").GetDiag() + } + } + if !core.IsNil(settingsResponse.TrustedProfileID) { + if err = d.Set("trusted_profile_id", settingsResponse.TrustedProfileID); err != nil { + err = fmt.Errorf("Error setting trusted_profile_id: %s", err) + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "ibm_config_aggregator_settings", "read", "set-trusted_profile_id").GetDiag() + } + } + if !core.IsNil(settingsResponse.Regions) { + if err = d.Set("regions", settingsResponse.Regions); err != nil { + err = fmt.Errorf("Error setting regions: %s", err) + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "ibm_config_aggregator_settings", "read", "set-regions").GetDiag() + } + } + if !core.IsNil(settingsResponse.AdditionalScope) { + additionalScope := []map[string]interface{}{} + for _, additionalScopeItem := range settingsResponse.AdditionalScope { + additionalScopeItemMap, err := ResourceIbmConfigAggregatorSettingsAdditionalScopeToMap(&additionalScopeItem) + if err != nil { + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "ibm_config_aggregator_settings", "read", "additional_scope-to-map").GetDiag() + } + additionalScope = append(additionalScope, additionalScopeItemMap) + } + if err = d.Set("additional_scope", additionalScope); err != nil { + err = fmt.Errorf("Error setting additional_scope: %s", err) + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "ibm_config_aggregator_settings", "read", "set-additional_scope").GetDiag() + } + } + + return nil +} + +func resourceIbmConfigAggregatorSettingsDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + // This resource does not support a "delete" operation. + d.SetId("") + return nil +} + +func ResourceIbmConfigAggregatorSettingsMapToAdditionalScope(modelMap map[string]interface{}) (*configurationaggregatorv1.AdditionalScope, error) { + model := &configurationaggregatorv1.AdditionalScope{} + if modelMap["type"] != nil && modelMap["type"].(string) != "" { + model.Type = core.StringPtr(modelMap["type"].(string)) + } + if modelMap["enterprise_id"] != nil && modelMap["enterprise_id"].(string) != "" { + model.EnterpriseID = core.StringPtr(modelMap["enterprise_id"].(string)) + } + if modelMap["profile_template"] != nil && len(modelMap["profile_template"].([]interface{})) > 0 { + ProfileTemplateModel, err := ResourceIbmConfigAggregatorSettingsMapToProfileTemplate(modelMap["profile_template"].([]interface{})[0].(map[string]interface{})) + if err != nil { + return model, err + } + model.ProfileTemplate = ProfileTemplateModel + } + return model, nil +} + +func ResourceIbmConfigAggregatorSettingsMapToProfileTemplate(modelMap map[string]interface{}) (*configurationaggregatorv1.ProfileTemplate, error) { + model := &configurationaggregatorv1.ProfileTemplate{} + if modelMap["id"] != nil && modelMap["id"].(string) != "" { + model.ID = core.StringPtr(modelMap["id"].(string)) + } + if modelMap["trusted_profile_id"] != nil && modelMap["trusted_profile_id"].(string) != "" { + model.TrustedProfileID = core.StringPtr(modelMap["trusted_profile_id"].(string)) + } + return model, nil +} + +func ResourceIbmConfigAggregatorSettingsAdditionalScopeToMap(model *configurationaggregatorv1.AdditionalScope) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Type != nil { + modelMap["type"] = *model.Type + } + if model.EnterpriseID != nil { + modelMap["enterprise_id"] = *model.EnterpriseID + } + if model.ProfileTemplate != nil { + profileTemplateMap, err := ResourceIbmConfigAggregatorSettingsProfileTemplateToMap(model.ProfileTemplate) + if err != nil { + return modelMap, err + } + modelMap["profile_template"] = []map[string]interface{}{profileTemplateMap} + } + return modelMap, nil +} + +func ResourceIbmConfigAggregatorSettingsProfileTemplateToMap(model *configurationaggregatorv1.ProfileTemplate) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ID != nil { + modelMap["id"] = *model.ID + } + if model.TrustedProfileID != nil { + modelMap["trusted_profile_id"] = *model.TrustedProfileID + } + return modelMap, nil +} diff --git a/ibm/service/configurationaggregator/resource_ibm_config_aggregator_settings_test.go b/ibm/service/configurationaggregator/resource_ibm_config_aggregator_settings_test.go new file mode 100644 index 0000000000..65d6b2b3bb --- /dev/null +++ b/ibm/service/configurationaggregator/resource_ibm_config_aggregator_settings_test.go @@ -0,0 +1,234 @@ +// Copyright IBM Corp. 2024 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package configurationaggregator_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + + "github.com/IBM/configuration-aggregator-go-sdk/configurationaggregatorv1" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/service/configurationaggregator" + "github.com/IBM/go-sdk-core/v5/core" + "github.com/stretchr/testify/assert" +) + +func TestAccIbmConfigAggregatorSettingsBasic(t *testing.T) { + var conf configurationaggregatorv1.SettingsResponse + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIbmConfigAggregatorSettingsDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmConfigAggregatorSettingsConfigBasic(), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIbmConfigAggregatorSettingsExists("ibm_config_aggregator_settings.config_aggregator_settings_instance", conf), + ), + }, + }, + }) +} + +func TestAccIbmConfigAggregatorSettingsAllArgs(t *testing.T) { + var conf configurationaggregatorv1.SettingsResponse + resourceCollectionEnabled := "false" + trustedProfileID := fmt.Sprintf("tf_trusted_profile_id_%d", acctest.RandIntRange(10, 100)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIbmConfigAggregatorSettingsDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmConfigAggregatorSettingsConfig(resourceCollectionEnabled, trustedProfileID), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIbmConfigAggregatorSettingsExists("ibm_config_aggregator_settings.config_aggregator_settings_instance", conf), + resource.TestCheckResourceAttr("ibm_config_aggregator_settings.config_aggregator_settings_instance", "resource_collection_enabled", resourceCollectionEnabled), + resource.TestCheckResourceAttr("ibm_config_aggregator_settings.config_aggregator_settings_instance", "trusted_profile_id", trustedProfileID), + ), + }, + resource.TestStep{ + ResourceName: "ibm_config_aggregator_settings.config_aggregator_settings", + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccCheckIbmConfigAggregatorSettingsConfigBasic() string { + return fmt.Sprintf(` + resource "ibm_config_aggregator_settings" "config_aggregator_settings_instance" { + } + `) +} + +func testAccCheckIbmConfigAggregatorSettingsConfig(resourceCollectionEnabled string, trustedProfileID string) string { + return fmt.Sprintf(` + + resource "ibm_config_aggregator_settings" "config_aggregator_settings_instance" { + resource_collection_enabled = %s + trusted_profile_id = "%s" + regions = "FIXME" + additional_scope { + type = "Enterprise" + enterprise_id = "enterprise_id" + profile_template { + id = "ProfileTemplate-adb55769-ae22-4c60-aead-bd1f84f93c57" + trusted_profile_id = "Profile-6bb60124-8fc3-4d18-b63d-0b99560865d3" + } + } + } + `, resourceCollectionEnabled, trustedProfileID) +} + +func testAccCheckIbmConfigAggregatorSettingsExists(n string, obj configurationaggregatorv1.SettingsResponse) resource.TestCheckFunc { + + return func(s *terraform.State) error { + _, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + configurationAggregatorClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).ConfigurationAggregatorV1() + if err != nil { + return err + } + + getSettingsOptions := &configurationaggregatorv1.GetSettingsOptions{} + + updateSettings, _, err := configurationAggregatorClient.GetSettings(getSettingsOptions) + if err != nil { + return err + } + + obj = *updateSettings + return nil + } +} + +func testAccCheckIbmConfigAggregatorSettingsDestroy(s *terraform.State) error { + configurationAggregatorClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).ConfigurationAggregatorV1() + if err != nil { + return err + } + for _, rs := range s.RootModule().Resources { + if rs.Type != "ibm_config_aggregator_settings" { + continue + } + + getSettingsOptions := &configurationaggregatorv1.GetSettingsOptions{} + + // Try to find the key + _, response, err := configurationAggregatorClient.GetSettings(getSettingsOptions) + + if err == nil { + return fmt.Errorf("config_aggregator_settings still exists: %s", rs.Primary.ID) + } else if response.StatusCode != 404 { + return fmt.Errorf("Error checking for config_aggregator_settings (%s) has been destroyed: %s", rs.Primary.ID, err) + } + } + + return nil +} + +func TestResourceIbmConfigAggregatorSettingsAdditionalScopeToMap(t *testing.T) { + checkResult := func(result map[string]interface{}) { + profileTemplateModel := make(map[string]interface{}) + profileTemplateModel["id"] = "ProfileTemplate-adb55769-ae22-4c60-aead-bd1f84f93c57" + profileTemplateModel["trusted_profile_id"] = "Profile-6bb60124-8fc3-4d18-b63d-0b99560865d3" + + model := make(map[string]interface{}) + model["type"] = "Enterprise" + model["enterprise_id"] = "testString" + model["profile_template"] = []map[string]interface{}{profileTemplateModel} + + assert.Equal(t, result, model) + } + + profileTemplateModel := new(configurationaggregatorv1.ProfileTemplate) + profileTemplateModel.ID = core.StringPtr("ProfileTemplate-adb55769-ae22-4c60-aead-bd1f84f93c57") + profileTemplateModel.TrustedProfileID = core.StringPtr("Profile-6bb60124-8fc3-4d18-b63d-0b99560865d3") + + model := new(configurationaggregatorv1.AdditionalScope) + model.Type = core.StringPtr("Enterprise") + model.EnterpriseID = core.StringPtr("testString") + model.ProfileTemplate = profileTemplateModel + + result, err := configurationaggregator.ResourceIbmConfigAggregatorSettingsAdditionalScopeToMap(model) + assert.Nil(t, err) + checkResult(result) +} + +func TestResourceIbmConfigAggregatorSettingsProfileTemplateToMap(t *testing.T) { + checkResult := func(result map[string]interface{}) { + model := make(map[string]interface{}) + model["id"] = "ProfileTemplate-adb55769-ae22-4c60-aead-bd1f84f93c57" + model["trusted_profile_id"] = "Profile-6bb60124-8fc3-4d18-b63d-0b99560865d3" + + assert.Equal(t, result, model) + } + + model := new(configurationaggregatorv1.ProfileTemplate) + model.ID = core.StringPtr("ProfileTemplate-adb55769-ae22-4c60-aead-bd1f84f93c57") + model.TrustedProfileID = core.StringPtr("Profile-6bb60124-8fc3-4d18-b63d-0b99560865d3") + + result, err := configurationaggregator.ResourceIbmConfigAggregatorSettingsProfileTemplateToMap(model) + assert.Nil(t, err) + checkResult(result) +} + +func TestResourceIbmConfigAggregatorSettingsMapToAdditionalScope(t *testing.T) { + checkResult := func(result *configurationaggregatorv1.AdditionalScope) { + profileTemplateModel := new(configurationaggregatorv1.ProfileTemplate) + profileTemplateModel.ID = core.StringPtr("ProfileTemplate-adb55769-ae22-4c60-aead-bd1f84f93c57") + profileTemplateModel.TrustedProfileID = core.StringPtr("Profile-6bb60124-8fc3-4d18-b63d-0b99560865d3") + + model := new(configurationaggregatorv1.AdditionalScope) + model.Type = core.StringPtr("Enterprise") + model.EnterpriseID = core.StringPtr("testString") + model.ProfileTemplate = profileTemplateModel + + assert.Equal(t, result, model) + } + + profileTemplateModel := make(map[string]interface{}) + profileTemplateModel["id"] = "ProfileTemplate-adb55769-ae22-4c60-aead-bd1f84f93c57" + profileTemplateModel["trusted_profile_id"] = "Profile-6bb60124-8fc3-4d18-b63d-0b99560865d3" + + model := make(map[string]interface{}) + model["type"] = "Enterprise" + model["enterprise_id"] = "testString" + model["profile_template"] = []interface{}{profileTemplateModel} + + result, err := configurationaggregator.ResourceIbmConfigAggregatorSettingsMapToAdditionalScope(model) + assert.Nil(t, err) + checkResult(result) +} + +func TestResourceIbmConfigAggregatorSettingsMapToProfileTemplate(t *testing.T) { + checkResult := func(result *configurationaggregatorv1.ProfileTemplate) { + model := new(configurationaggregatorv1.ProfileTemplate) + model.ID = core.StringPtr("ProfileTemplate-adb55769-ae22-4c60-aead-bd1f84f93c57") + model.TrustedProfileID = core.StringPtr("Profile-6bb60124-8fc3-4d18-b63d-0b99560865d3") + + assert.Equal(t, result, model) + } + + model := make(map[string]interface{}) + model["id"] = "ProfileTemplate-adb55769-ae22-4c60-aead-bd1f84f93c57" + model["trusted_profile_id"] = "Profile-6bb60124-8fc3-4d18-b63d-0b99560865d3" + + result, err := configurationaggregator.ResourceIbmConfigAggregatorSettingsMapToProfileTemplate(model) + assert.Nil(t, err) + checkResult(result) +} diff --git a/ibm/service/cos/data_source_ibm_cos_bucket.go b/ibm/service/cos/data_source_ibm_cos_bucket.go index 24e7c74ad9..653fe61390 100644 --- a/ibm/service/cos/data_source_ibm_cos_bucket.go +++ b/ibm/service/cos/data_source_ibm_cos_bucket.go @@ -556,6 +556,99 @@ func DataSourceIBMCosBucket() *schema.Resource { Type: schema.TypeString, Computed: true, }, + "lifecycle_rule": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "abort_incomplete_multipart_upload": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "days_after_initiation": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "expiration": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "date": { + Type: schema.TypeString, + Computed: true, + }, + "days": { + Type: schema.TypeInt, + Computed: true, + }, + "expired_object_delete_marker": { + Type: schema.TypeBool, + Computed: true, // API returns false; conflicts with date and days + }, + }, + }, + }, + "filter": { + Type: schema.TypeList, + Computed: true, + // IBM has filter a required parameter + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "prefix": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "rule_id": { + Type: schema.TypeString, + Computed: true, + }, + "noncurrent_version_expiration": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "noncurrent_days": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "status": { + Type: schema.TypeString, + Computed: true, + }, + "transition": { + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "date": { + Type: schema.TypeString, + Computed: true, + }, + "days": { + Type: schema.TypeInt, + Computed: true, + }, + "storag_class": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + }, + }, + }, }, } } @@ -621,7 +714,7 @@ func dataSourceIBMCosBucketRead(d *schema.ResourceData, meta interface{}) error apiEndpoint = SelectSatlocCosApi(bucketType, serviceID, satlc_id) } else { - apiEndpoint, apiEndpointPrivate, directApiEndpoint = SelectCosApi(bucketLocationConvert(bucketType), bucketRegion) + apiEndpoint, apiEndpointPrivate, directApiEndpoint = SelectCosApi(bucketLocationConvert(bucketType), bucketRegion, false) visibility = endpointType if endpointType == "private" { apiEndpoint = apiEndpointPrivate @@ -718,6 +811,7 @@ func dataSourceIBMCosBucketRead(d *schema.ResourceData, meta interface{}) error bucketCRN := fmt.Sprintf("%s:%s:%s", strings.Replace(serviceID, "::", "", -1), "bucket", bucketName) d.Set("crn", bucketCRN) d.Set("resource_instance_id", serviceID) + apiEndpoint, apiEndpointPrivate, directApiEndpoint = SelectCosApi(bucketLocationConvert(bucketType), bucketRegion, strings.Contains(apiEndpoint, "test")) d.Set("s3_endpoint_public", apiEndpoint) d.Set("s3_endpoint_private", apiEndpointPrivate) d.Set("s3_endpoint_direct", directApiEndpoint) @@ -796,6 +890,24 @@ func dataSourceIBMCosBucketRead(d *schema.ResourceData, meta interface{}) error } } + //lifecycle configuration new resource read + getLifecycleConfigurationInput := &s3.GetBucketLifecycleConfigurationInput{ + Bucket: aws.String(bucketName), + } + var outputLifecycleConfig *s3.GetBucketLifecycleConfigurationOutput + outputLifecycleConfig, err = s3Client.GetBucketLifecycleConfiguration(getLifecycleConfigurationInput) + var outputLifecycleConfigptr *s3.LifecycleConfiguration + outputLifecycleConfigptr = (*s3.LifecycleConfiguration)(outputLifecycleConfig) + if (err != nil && !strings.Contains(err.Error(), "NoSuchLifecycleConfiguration: The lifecycle configuration does not exist")) && (err != nil && bucketPtr != nil && bucketPtr.Firewall != nil && !strings.Contains(err.Error(), "AccessDenied: Access Denied")) { + return err + } + if outputLifecycleConfigptr.Rules != nil { + lifecycleConfiguration := flex.LifecylceRuleGet(outputLifecycleConfigptr.Rules) + if len(lifecycleConfiguration) > 0 { + d.Set("lifecycle_rule", lifecycleConfiguration) + } + } + // Read the retention policy retentionInput := &s3.GetBucketProtectionConfigurationInput{ Bucket: aws.String(bucketName), diff --git a/ibm/service/cos/resource_ibm_cos_bucket.go b/ibm/service/cos/resource_ibm_cos_bucket.go index 32850cd514..912f2b51dd 100644 --- a/ibm/service/cos/resource_ibm_cos_bucket.go +++ b/ibm/service/cos/resource_ibm_cos_bucket.go @@ -244,7 +244,8 @@ func ResourceIBMCOSBucket() *schema.Resource { "abort_incomplete_multipart_upload_days": { Type: schema.TypeList, Optional: true, - MaxItems: 1, + MaxItems: 1000, + Deprecated: "Use the ibm_cos_bucket_lifecycle_configuration resource instead", Description: "Enable abort incomplete multipart upload to COS Bucket after a defined period of time", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ @@ -278,6 +279,7 @@ func ResourceIBMCOSBucket() *schema.Resource { Type: schema.TypeList, Optional: true, MaxItems: 1, + Deprecated: "Use the ibm_cos_bucket_lifecycle_configuration resource instead", Description: "Enable configuration archive_rule (glacier/accelerated) to COS Bucket after a defined period of time", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ @@ -312,6 +314,7 @@ func ResourceIBMCOSBucket() *schema.Resource { Type: schema.TypeList, Optional: true, MaxItems: 1000, + Deprecated: "Use the ibm_cos_bucket_lifecycle_configuration resource instead", Description: "Enable configuration expire_rule to COS Bucket after a defined period of time", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ @@ -759,7 +762,7 @@ func resourceIBMCOSBucketUpdate(d *schema.ResourceData, meta interface{}) error if apiType == "sl" { apiEndpoint = SelectSatlocCosApi(apiType, serviceID, bLocation) } else { - apiEndpoint, apiEndpointPrivate, directApiEndpoint = SelectCosApi(apiType, bLocation) + apiEndpoint, apiEndpointPrivate, directApiEndpoint = SelectCosApi(apiType, bLocation, false) visibility = endpointType if endpointType == "private" { apiEndpoint = apiEndpointPrivate @@ -1085,6 +1088,7 @@ func resourceIBMCOSBucketUpdate(d *schema.ResourceData, meta interface{}) error func resourceIBMCOSBucketRead(d *schema.ResourceData, meta interface{}) error { var s3Conf *aws.Config var keyProtectFlag bool + var archiveFlag, expireFlag, abortFlag, ncFlag bool rsConClient, err := meta.(conns.ClientSession).BluemixSession() if err != nil { return err @@ -1101,6 +1105,18 @@ func resourceIBMCOSBucketRead(d *schema.ResourceData, meta interface{}) error { if _, ok := d.GetOk("key_protect"); ok { keyProtectFlag = true } + if _, ok := d.GetOk("expire_rule"); ok { + expireFlag = true + } + if _, ok := d.GetOk("archive_rule"); ok { + archiveFlag = true + } + if _, ok := d.GetOk("noncurrent_version_expiration"); ok { + archiveFlag = true + } + if _, ok := d.GetOk("abort_incomplete_multipart_upload_days"); ok { + abortFlag = true + } //split satellite resource instance id to get the 1st value if apiType == "sl" { @@ -1108,13 +1124,12 @@ func resourceIBMCOSBucketRead(d *schema.ResourceData, meta interface{}) error { bucketsatcrn := satloc_guid[0] serviceID = bucketsatcrn } - var apiEndpoint, apiEndpointPublic, apiEndpointPrivate, directApiEndpoint, visibility string visibility = endpointType if apiType == "sl" { apiEndpoint = SelectSatlocCosApi(apiType, serviceID, bLocation) } else { - apiEndpointPublic, apiEndpointPrivate, directApiEndpoint = SelectCosApi(apiType, bLocation) + apiEndpointPublic, apiEndpointPrivate, directApiEndpoint = SelectCosApi(apiType, bLocation, false) apiEndpoint = apiEndpointPublic if endpointType == "private" { apiEndpoint = apiEndpointPrivate @@ -1202,6 +1217,8 @@ func resourceIBMCOSBucketRead(d *schema.ResourceData, meta interface{}) error { d.Set("crn", bucketCRN) d.Set("resource_instance_id", serviceID) d.Set("bucket_name", bucketName) + + apiEndpointPublic, apiEndpointPrivate, directApiEndpoint = SelectCosApi(apiType, bLocation, strings.Contains(apiEndpoint, "test")) d.Set("s3_endpoint_public", apiEndpointPublic) d.Set("s3_endpoint_private", apiEndpointPrivate) d.Set("s3_endpoint_direct", directApiEndpoint) @@ -1286,23 +1303,27 @@ func resourceIBMCOSBucketRead(d *schema.ResourceData, meta interface{}) error { if (err != nil && !strings.Contains(err.Error(), "NoSuchLifecycleConfiguration: The lifecycle configuration does not exist")) && (err != nil && bucketPtr != nil && bucketPtr.Firewall != nil && !strings.Contains(err.Error(), "AccessDenied: Access Denied")) { return err } - if lifecycleptr != nil { + + if lifecycleptr.Rules != nil { archiveRules := flex.ArchiveRuleGet(lifecycleptr.Rules) expireRules := flex.ExpireRuleGet(lifecycleptr.Rules) nc_expRules := flex.Nc_exp_RuleGet(lifecycleptr.Rules) abort_mpuRules := flex.Abort_mpu_RuleGet(lifecycleptr.Rules) - if len(archiveRules) > 0 { + if len(archiveRules) > 0 && archiveFlag == true { + d.Set("archive_rule", archiveRules) } - if len(expireRules) > 0 { + if len(expireRules) > 0 && expireFlag == true { d.Set("expire_rule", expireRules) } - if len(nc_expRules) > 0 { + if len(nc_expRules) > 0 && ncFlag == true { d.Set("noncurrent_version_expiration", nc_expRules) } - if len(abort_mpuRules) > 0 { + if len(abort_mpuRules) > 0 && abortFlag == true { d.Set("abort_incomplete_multipart_upload_days", abort_mpuRules) } + } else { + fmt.Println("There is no lifecycle configuration on the bucket") } // Read retention rule @@ -1401,13 +1422,12 @@ func resourceIBMCOSBucketCreate(d *schema.ResourceData, meta interface{}) error lConstraint := fmt.Sprintf("%s-%s", bLocation, storageClass) var endpointType = d.Get("endpoint_type").(string) - var apiEndpoint, privateApiEndpoint, directApiEndpoint, visibility string if apiType == "sl" { apiEndpoint = SelectSatlocCosApi(apiType, serviceID, bLocation) } else { - apiEndpoint, privateApiEndpoint, directApiEndpoint = SelectCosApi(apiType, bLocation) + apiEndpoint, privateApiEndpoint, directApiEndpoint = SelectCosApi(apiType, bLocation, false) visibility = endpointType if endpointType == "private" { apiEndpoint = privateApiEndpoint @@ -1527,13 +1547,12 @@ func resourceIBMCOSBucketDelete(d *schema.ResourceData, meta interface{}) error endpointType = d.Get("endpoint_type").(string) } var apiEndpoint, apiEndpointPrivate, directApiEndpoint, visibility string - if apiType == "sl" { apiEndpoint = SelectSatlocCosApi(apiType, serviceID, bLocation) } else { - apiEndpoint, apiEndpointPrivate, directApiEndpoint = SelectCosApi(apiType, bLocation) + apiEndpoint, apiEndpointPrivate, directApiEndpoint = SelectCosApi(apiType, bLocation, false) visibility = endpointType if endpointType == "private" { apiEndpoint = apiEndpointPrivate @@ -1662,13 +1681,12 @@ func resourceIBMCOSBucketExists(d *schema.ResourceData, meta interface{}) (bool, } var apiEndpoint, apiEndpointPrivate, directApiEndpoint string - if apiType == "sl" { apiEndpoint = SelectSatlocCosApi(apiType, serviceID, bLocation) } else { - apiEndpoint, apiEndpointPrivate, directApiEndpoint = SelectCosApi(apiType, bLocation) + apiEndpoint, apiEndpointPrivate, directApiEndpoint = SelectCosApi(apiType, bLocation, false) if endpointType == "private" { apiEndpoint = apiEndpointPrivate } @@ -1722,15 +1740,19 @@ func resourceIBMCOSBucketExists(d *schema.ResourceData, meta interface{}) (bool, return false, nil } -func SelectCosApi(apiType string, bLocation string) (string, string, string) { +func SelectCosApi(apiType string, bLocation string, test bool) (string, string, string) { + hostUrl := "cloud-object-storage.appdomain.cloud" + if test { + hostUrl = "cloud-object-storage.test.appdomain.cloud" + } if apiType == "crl" { - return fmt.Sprintf("s3.%s.cloud-object-storage.appdomain.cloud", bLocation), fmt.Sprintf("s3.private.%s.cloud-object-storage.appdomain.cloud", bLocation), fmt.Sprintf("s3.direct.%s.cloud-object-storage.appdomain.cloud", bLocation) + return fmt.Sprintf("s3.%s.%s", bLocation, hostUrl), fmt.Sprintf("s3.private.%s.%s", bLocation, hostUrl), fmt.Sprintf("s3.direct.%s.%s", bLocation, hostUrl) } if apiType == "rl" { - return fmt.Sprintf("s3.%s.cloud-object-storage.appdomain.cloud", bLocation), fmt.Sprintf("s3.private.%s.cloud-object-storage.appdomain.cloud", bLocation), fmt.Sprintf("s3.direct.%s.cloud-object-storage.appdomain.cloud", bLocation) + return fmt.Sprintf("s3.%s.%s", bLocation, hostUrl), fmt.Sprintf("s3.private.%s.%s", bLocation, hostUrl), fmt.Sprintf("s3.direct.%s.%s", bLocation, hostUrl) } if apiType == "ssl" { - return fmt.Sprintf("s3.%s.cloud-object-storage.appdomain.cloud", bLocation), fmt.Sprintf("s3.private.%s.cloud-object-storage.appdomain.cloud", bLocation), fmt.Sprintf("s3.direct.%s.cloud-object-storage.appdomain.cloud", bLocation) + return fmt.Sprintf("s3.%s.%s", bLocation, hostUrl), fmt.Sprintf("s3.private.%s.%s", bLocation, hostUrl), fmt.Sprintf("s3.direct.%s.%s", bLocation, hostUrl) } return "", "", "" } diff --git a/ibm/service/cos/resource_ibm_cos_bucket_lifecycle_configuration.go b/ibm/service/cos/resource_ibm_cos_bucket_lifecycle_configuration.go new file mode 100644 index 0000000000..7237b7b2f3 --- /dev/null +++ b/ibm/service/cos/resource_ibm_cos_bucket_lifecycle_configuration.go @@ -0,0 +1,548 @@ +package cos + +import ( + // "encoding/json" + "context" + "fmt" + "strings" + "time" + + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" + "github.com/IBM/ibm-cos-sdk-go/aws" + "github.com/IBM/ibm-cos-sdk-go/service/s3" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + validation "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" +) + +func ResourceIBMCOSBucketLifecycleConfiguration() *schema.Resource { + return &schema.Resource{ + CreateContext: resourceIBMCOSBucketLifecycleConfigurationCreate, + ReadContext: resourceIBMCOSBucketLifecycleConfigurationRead, + UpdateContext: resourceIBMCOSBucketLifecycleConfigurationUpdate, + DeleteContext: resourceIBMCOSBucketLifecycleConfigurationDelete, + Importer: &schema.ResourceImporter{}, + CustomizeDiff: customdiff.Sequence( + func(_ context.Context, diff *schema.ResourceDiff, v interface{}) error { + return resourceValidateLifecycleRule(diff) + }, + ), + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(60 * time.Minute), + Update: schema.DefaultTimeout(20 * time.Minute), + Delete: schema.DefaultTimeout(10 * time.Minute), + }, + Schema: map[string]*schema.Schema{ + "bucket_crn": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: "COS bucket CRN", + }, + "bucket_location": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: "COS bucket location", + }, + "endpoint_type": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.ValidateAllowedStringValues([]string{"public", "private", "direct"}), + Description: "COS endpoint type: public, private, direct", + Default: "public", + }, + "lifecycle_rule": { + Type: schema.TypeList, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "abort_incomplete_multipart_upload": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "days_after_initiation": { + Type: schema.TypeInt, + ValidateFunc: validate.ValidateAllowedRangeInt(1, 3650), + Optional: true, + }, + }, + }, + }, + "expiration": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "date": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.ValidateUTCFormat, + }, + "days": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validate.ValidateAllowedRangeInt(1, 3650), + Default: 0, // API returns 0 + }, + "expired_object_delete_marker": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + }, + }, + }, + }, + "filter": { + Type: schema.TypeList, + Required: true, + DiffSuppressFunc: suppressMissingFilterConfigurationBlock, + // IBM has filter as required parameter + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "prefix": { + Type: schema.TypeString, + Optional: true, + }, + }, + }, + }, + "rule_id": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 255), + }, + "noncurrent_version_expiration": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "noncurrent_days": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validation.IntAtLeast(1), + }, + }, + }, + }, + "status": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validate.ValidateAllowedStringValues([]string{"enable", "disable"}), + }, + "transition": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "date": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.ValidateUTCFormat, + }, + "days": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validate.ValidateAllowedRangeInt(0, 3650), + }, + "storage_class": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validate.ValidateAllowedStringValues([]string{"GLACIER", + "ACCELERATED"}), + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func abortIncompleteMultipartUploadSet(abortIncompleteMultipartUpload map[string]interface{}) *s3.AbortIncompleteMultipartUpload { + var abort_incomplete_multipart_upload *s3.AbortIncompleteMultipartUpload + abortIncompleteMultipartUploadValue := s3.AbortIncompleteMultipartUpload{} + if len(abortIncompleteMultipartUpload) != 0 { + if daysSet, exists := abortIncompleteMultipartUpload["days_after_initiation"]; exists { + days := int64(daysSet.(int)) + abortIncompleteMultipartUploadValue.DaysAfterInitiation = aws.Int64(days) + } + abort_incomplete_multipart_upload = &abortIncompleteMultipartUploadValue + return abort_incomplete_multipart_upload + } else { + return nil + } +} + +func lifecycleExpirationSet(expiration []interface{}) *s3.LifecycleExpiration { + if len(expiration) == 0 { + return nil + } + + var result *s3.LifecycleExpiration + + resultValue := s3.LifecycleExpiration{} + + if expiration[0] == nil { + return result + } + + expirationMap := expiration[0].(map[string]interface{}) + if v, ok := expirationMap["date"].(string); ok && v != "" { + t, _ := time.Parse(time.RFC3339, v) + resultValue.Date = aws.Time(t) + } + + if v, ok := expirationMap["days"]; ok { + daysSet := int64(v.(int)) + if daysSet > 0 { + days := daysSet + resultValue.Days = aws.Int64(days) + } + } + + // This cannot be specified with Days or Date + if v, exist := expirationMap["expired_object_delete_marker"]; exist && resultValue.Date == nil && resultValue.Days == nil { + resultValue.ExpiredObjectDeleteMarker = aws.Bool(v.(bool)) + } + + result = &resultValue + + return result +} + +func lifecycleRuleFilterSet(filter []interface{}) *s3.LifecycleRuleFilter { + var result *s3.LifecycleRuleFilter + resultValue := s3.LifecycleRuleFilter{} + if filter[0] == nil { + resultValue.Prefix = aws.String("") + result = &resultValue + return result + } + filterMap := filter[0].(map[string]interface{}) + if v, ok := filterMap["prefix"].(string); ok { + resultValue.Prefix = aws.String(v) + } + result = &resultValue + return result +} + +func noncurrentVersionExpirationSet(noncurrentVersionExpiration map[string]interface{}) *s3.NoncurrentVersionExpiration { + var result *s3.NoncurrentVersionExpiration + resultValue := s3.NoncurrentVersionExpiration{} + if v, ok := noncurrentVersionExpiration["noncurrent_days"]; ok { + resultValue.NoncurrentDays = aws.Int64(int64(v.(int))) + } + result = &resultValue + return result +} + +func transitionsSet(transitions []interface{}) []*s3.Transition { + if len(transitions) == 0 { + return nil + } + var results []*s3.Transition + var transition = s3.Transition{} + if transitions[0] == nil { + return results + } + transitionMap := transitions[0].(map[string]interface{}) + if v, ok := transitionMap["date"].(string); ok && v != "" { + t, _ := time.Parse(time.RFC3339, v) + transition.Date = aws.Time(t) + } + + // Only one of "date" and "days" can be configured + // so only set the transition.Days value when transition.Date is nil + // By default, transitionMap["days"] = 0 if not explicitly configured in terraform. + if v, ok := transitionMap["days"]; ok && v.(int) >= 0 && transition.Date == nil { + transition.Days = aws.Int64(int64(v.(int))) + } + if v, ok := transitionMap["storage_class"].(string); ok && v != "" { + transition.StorageClass = aws.String(v) + } + results = append(results, &transition) + + return results +} + +func lifecycleConfigurationSet(lifecycleConfigurationList []interface{}) []*s3.LifecycleRule { + var lifecycleRules []*s3.LifecycleRule + for _, lifecycleRuleMapRaw := range lifecycleConfigurationList { + lifecycleRuleMap, ok := lifecycleRuleMapRaw.(map[string]interface{}) + if !ok { + continue + } + lifecycleRule := s3.LifecycleRule{} // single rule to be appended to the list of lifecycle rules + // check for abort incomplete multipart + if v, ok := lifecycleRuleMap["abort_incomplete_multipart_upload"].([]interface{}); ok && len(v) > 0 && v[0] != nil { + lifecycleRule.AbortIncompleteMultipartUpload = abortIncompleteMultipartUploadSet(v[0].(map[string]interface{})) + } + // check for expiration + if v, ok := lifecycleRuleMap["expiration"].([]interface{}); ok && len(v) > 0 { + lifecycleRule.Expiration = lifecycleExpirationSet(v) + } + // check for filter (required) + if v, ok := lifecycleRuleMap["filter"].([]interface{}); ok && len(v) > 0 { + lifecycleRule.Filter = lifecycleRuleFilterSet(v) + } + // check for rule id (required) + if v, ok := lifecycleRuleMap["rule_id"].(string); ok { + lifecycleRule.ID = aws.String(v) + } + // check for noncurrent version expiration + if v, ok := lifecycleRuleMap["noncurrent_version_expiration"].([]interface{}); ok && len(v) > 0 && v[0] != nil { + lifecycleRule.NoncurrentVersionExpiration = noncurrentVersionExpirationSet(v[0].(map[string]interface{})) + } + // check for status + if v, ok := lifecycleRuleMap["status"].(string); ok && v != "" { + if v == "enable" { + lifecycleRule.Status = aws.String("Enabled") + } else if v == "disable" { + lifecycleRule.Status = aws.String("Disabled") + } + + } + + // check for transition + if v, ok := lifecycleRuleMap["transition"].([]interface{}); ok && len(v) > 0 { + lifecycleRule.Transitions = transitionsSet(v) + } + + lifecycleRules = append(lifecycleRules, &lifecycleRule) + } + + return lifecycleRules +} + +func resourceIBMCOSBucketLifecycleConfigurationCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + bucketCRN := d.Get("bucket_crn").(string) + bucketName := strings.Split(bucketCRN, ":bucket:")[1] + instanceCRN := fmt.Sprintf("%s::", strings.Split(bucketCRN, ":bucket:")[0]) + bucketLocation := d.Get("bucket_location").(string) + endpointType := d.Get("endpoint_type").(string) + bxSession, err := meta.(conns.ClientSession).BluemixSession() + if err != nil { + return diag.Errorf("%v", err) + } + s3Client, err := getS3ClientSession(bxSession, bucketLocation, endpointType, instanceCRN) + lifecycleRule := d.Get("lifecycle_rule") + rules := lifecycleConfigurationSet(lifecycleRule.([]interface{})) // setting each lifecycle rule + if err != nil { + return diag.Errorf("Failed to read lifecycle configuration for COS bucket %s, %v", bucketName, err) + } + putBucketLifecycleConfigurationInput := s3.PutBucketLifecycleConfigurationInput{ + Bucket: aws.String(bucketName), + LifecycleConfiguration: &s3.LifecycleConfiguration{ + Rules: rules, + }, + } + _, err = s3Client.PutBucketLifecycleConfiguration(&putBucketLifecycleConfigurationInput) + if err != nil { + return diag.Errorf("Failed to put Lifecycle configuration on the COS bucket %s, %v", bucketName, err) + } + bktID := fmt.Sprintf("%s:%s:%s:meta:%s:%s", strings.Replace(instanceCRN, "::", "", -1), "bucket", bucketName, bucketLocation, endpointType) + d.SetId(bktID) + return resourceIBMCOSBucketLifecycleConfigurationUpdate(ctx, d, meta) +} + +func resourceIBMCOSBucketLifecycleConfigurationUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + bucketCRN := d.Get("bucket_crn").(string) + bucketName := strings.Split(bucketCRN, ":bucket:")[1] + instanceCRN := fmt.Sprintf("%s::", strings.Split(bucketCRN, ":bucket:")[0]) + bucketLocation := d.Get("bucket_location").(string) + endpointType := d.Get("endpoint_type").(string) + bxSession, err := meta.(conns.ClientSession).BluemixSession() + if err != nil { + return diag.Errorf("%v", err) + } + s3Client, err := getS3ClientSession(bxSession, bucketLocation, endpointType, instanceCRN) + if d.HasChange("lifecycle_rule") { + lifecycleRule := d.Get("lifecycle_rule") + rules := lifecycleConfigurationSet(lifecycleRule.([]interface{})) + if err != nil { + return diag.Errorf("Failed to read lifecycle configuration for COS bucket %s, %v", bucketName, err) + } + putBucketLifecycleConfigurationInput := s3.PutBucketLifecycleConfigurationInput{ + Bucket: aws.String(bucketName), + LifecycleConfiguration: &s3.LifecycleConfiguration{ + Rules: rules, + }, + } + _, err = s3Client.PutBucketLifecycleConfiguration(&putBucketLifecycleConfigurationInput) + if err != nil { + return diag.Errorf("Failed to put Lifecycle configuration on the COS bucket %s, %v", bucketName, err) + } + } + return resourceIBMCOSBucketLifecycleConfigurationRead(ctx, d, meta) +} + +func resourceIBMCOSBucketLifecycleConfigurationRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + bucketCRN := parseWebsiteId(d.Id(), "bucketCRN") + bucketName := parseWebsiteId(d.Id(), "bucketName") + bucketLocation := parseWebsiteId(d.Id(), "bucketLocation") + instanceCRN := parseWebsiteId(d.Id(), "instanceCRN") + endpointType := parseWebsiteId(d.Id(), "endpointType") + d.Set("bucket_crn", bucketCRN) + d.Set("bucket_location", bucketLocation) + if endpointType != "" { + d.Set("endpoint_type", endpointType) + } + bxSession, err := meta.(conns.ClientSession).BluemixSession() + if err != nil { + return diag.Errorf("%v", err) + } + s3Client, err := getS3ClientSession(bxSession, bucketLocation, endpointType, instanceCRN) + if err != nil { + return diag.Errorf("%v", err) + } + //getBucketConfiguration + const ( + lifecycleConfigurationRulesSteadyTimeout = 2 * time.Minute + ) + getLifecycleConfigurationInput := &s3.GetBucketLifecycleConfigurationInput{ + Bucket: aws.String(bucketName), + } + var output *s3.GetBucketLifecycleConfigurationOutput + + // Adding a retry to overcome the NoSuchLifecycleConfiguration error as it takes time for the lifecycle rules to get applied. + err = resource.Retry(lifecycleConfigurationRulesSteadyTimeout, func() *resource.RetryError { + var err error + output, err = s3Client.GetBucketLifecycleConfiguration(getLifecycleConfigurationInput) + + if d.IsNewResource() && err != nil && strings.Contains(err.Error(), "NoSuchLifecycleConfiguration: The lifecycle configuration does not exist") { + + return resource.RetryableError(err) + } + if err != nil { + return resource.NonRetryableError(err) + } + return nil + }) + if conns.IsResourceTimeoutError(err) { + output, err = s3Client.GetBucketLifecycleConfiguration(getLifecycleConfigurationInput) + } + if err != nil { + return diag.Errorf("[ERROR] Error getting Lifecycle Configuration for the bucket %s", bucketName) + } + var outputptr *s3.LifecycleConfiguration + outputptr = (*s3.LifecycleConfiguration)(output) + if err != nil && !strings.Contains(err.Error(), "AccessDenied: Access Denied") { + return diag.Errorf("%v", err) + } + if outputptr.Rules != nil { + lifecycleConfiguration := flex.LifecylceRuleGet(outputptr.Rules) + if len(lifecycleConfiguration) > 0 { + d.Set("lifecycle_rule", lifecycleConfiguration) + } + } else { + d.SetId("") + } + return nil +} + +func resourceIBMCOSBucketLifecycleConfigurationDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + bucketName := parseWebsiteId(d.Id(), "bucketName") + bucketLocation := parseWebsiteId(d.Id(), "bucketLocation") + instanceCRN := parseWebsiteId(d.Id(), "instanceCRN") + endpointType := parseWebsiteId(d.Id(), "endpointType") + bxSession, err := meta.(conns.ClientSession).BluemixSession() + if err != nil { + return diag.Errorf("%v", err) + } + s3Client, err := getS3ClientSession(bxSession, bucketLocation, endpointType, instanceCRN) + if err != nil { + return diag.Errorf("%v", err) + } + deleteBucketLifecycleInput := &s3.DeleteBucketLifecycleInput{ + Bucket: aws.String(bucketName), + } + _, err = s3Client.DeleteBucketLifecycle(deleteBucketLifecycleInput) + if err != nil { + return diag.Errorf("failed to delete the Lifecycle configuration on the COS bucket %s, %v", bucketName, err) + } + return nil +} + +func parseLifecycleId(id string, info string) string { + bucketCRN := strings.Split(id, ":meta:")[0] + meta := strings.Split(id, ":meta:")[1] + if info == "bucketName" { + return strings.Split(bucketCRN, ":bucket:")[1] + } + if info == "instanceCRN" { + return fmt.Sprintf("%s::", strings.Split(bucketCRN, ":bucket:")[0]) + } + if info == "bucketCRN" { + return bucketCRN + } + if info == "bucketLocation" { + return strings.Split(meta, ":")[0] + } + if info == "endpointType" { + return strings.Split(meta, ":")[1] + } + if info == "keyName" { + return strings.Split(meta, ":key:")[1] + } + return parseBucketId(bucketCRN, info) +} + +func resourceValidateLifecycleRule(diff *schema.ResourceDiff) error { + if lifecycle, ok := diff.GetOk("lifecycle_rule"); ok { + lifecycle_list := lifecycle.([]interface{}) + for _, l := range lifecycle_list { + lifecycleMap, _ := l.(map[string]interface{}) + expiration := lifecycleMap["expiration"] + expirationParameterCounter := 0 + if expiration != nil { + expirationList, _ := expiration.([]interface{}) + for _, e := range expirationList { + expirationMap, _ := e.(map[string]interface{}) + if val, days_exist := expirationMap["days"]; days_exist && val.(int) != 0 { + expirationParameterCounter++ + } + if val, date_exist := expirationMap["date"]; date_exist && val != "" { + expirationParameterCounter++ + } + if val, expired_object_delete_marker_exist := expirationMap["expired_object_delete_marker"]; expired_object_delete_marker_exist && val.(bool) != false { + expirationParameterCounter++ + } + if expirationParameterCounter > 1 { + return fmt.Errorf("[ERROR] The expiry 3 action elements (Days, Date, ExpiredObjectDeleteMarker) are all mutually exclusive. These can not be used with each other. Please set one expiry element on the same rule of expiration.") + } + } + } + + } + } + return nil +} + +func suppressMissingFilterConfigurationBlock(k, old, new string, d *schema.ResourceData) bool { + if strings.HasSuffix(k, "filter.#") { + oraw, nraw := d.GetChange(k) + o, n := oraw.(int), nraw.(int) + if o == 1 && n == 0 { + return true + } + if o == 1 && n == 1 { + return old == "1" && new == "0" + } + return false + } + return false +} diff --git a/ibm/service/cos/resource_ibm_cos_bucket_lifecycle_configuration_test.go b/ibm/service/cos/resource_ibm_cos_bucket_lifecycle_configuration_test.go new file mode 100644 index 0000000000..671b55870e --- /dev/null +++ b/ibm/service/cos/resource_ibm_cos_bucket_lifecycle_configuration_test.go @@ -0,0 +1,1255 @@ +package cos_test + +import ( + "fmt" + "regexp" + "testing" + // "time" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func TestAccIBMCosBucket_Lifecycle_Configuration_Expiration_With_Days(t *testing.T) { + serviceName := fmt.Sprintf("terraform_%d", acctest.RandIntRange(10, 100)) + bucketName := fmt.Sprintf("terraform-lifecycle-configuration%d", acctest.RandIntRange(10, 100)) + bucketRegion := "us-south" + bucketClass := "standard" + bucketRegionType := "region_location" + expirationDays := 1 + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIBMCosBucketDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCosBucket_Lifecycle_Configuration_Expiration_With_Days(serviceName, bucketName, bucketRegionType, bucketRegion, bucketClass, expirationDays), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIBMCosBucketExists("ibm_resource_instance.instance", "ibm_cos_bucket.bucket", bucketRegionType, bucketRegion, bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "bucket_name", bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "storage_class", bucketClass), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "region_location", bucketRegion), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.#", "1"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.expiration.0.days", "1"), + ), + }, + }, + }) +} + +func TestAccIBMCosBucket_Lifecycle_Configuration_Expiration_With_Date(t *testing.T) { + serviceName := fmt.Sprintf("terraform_%d", acctest.RandIntRange(10, 100)) + bucketName := fmt.Sprintf("terraform-lifecycle-configuration%d", acctest.RandIntRange(10, 100)) + bucketRegion := "us-south" + bucketClass := "standard" + bucketRegionType := "region_location" + expirationDate := "2024-09-05T00:00:00Z" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIBMCosBucketDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCosBucket_Lifecycle_Configuration_Expiration_With_Date(serviceName, bucketName, bucketRegionType, bucketRegion, bucketClass, expirationDate), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIBMCosBucketExists("ibm_resource_instance.instance", "ibm_cos_bucket.bucket", bucketRegionType, bucketRegion, bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "bucket_name", bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "storage_class", bucketClass), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "region_location", bucketRegion), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.#", "1"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.expiration.0.date", expirationDate), + ), + }, + }, + }) +} + +func TestAccIBMCosBucket_Lifecycle_Configuration_Transition_With_Days_Glacier(t *testing.T) { + serviceName := fmt.Sprintf("terraform_%d", acctest.RandIntRange(10, 100)) + bucketName := fmt.Sprintf("terraform-lifecycle-configuration%d", acctest.RandIntRange(10, 100)) + bucketRegion := "us-south" + bucketClass := "standard" + bucketRegionType := "region_location" + transitionDays := 1 + tStorageclass := "GLACIER" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIBMCosBucketDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCosBucket_Lifecycle_Configuration_Transition_With_Days(serviceName, bucketName, bucketRegionType, bucketRegion, bucketClass, transitionDays, tStorageclass), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIBMCosBucketExists("ibm_resource_instance.instance", "ibm_cos_bucket.bucket", bucketRegionType, bucketRegion, bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "bucket_name", bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "storage_class", bucketClass), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "region_location", bucketRegion), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.#", "1"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.transition.0.days", "1"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.transition.0.storage_class", "GLACIER"), + ), + }, + }, + }) +} + +func TestAccIBMCosBucket_Lifecycle_Configuration_Transition_With_Date_Glacier(t *testing.T) { + serviceName := fmt.Sprintf("terraform_%d", acctest.RandIntRange(10, 100)) + bucketName := fmt.Sprintf("terraform-lifecycle-configuration%d", acctest.RandIntRange(10, 100)) + bucketRegion := "us-south" + bucketClass := "standard" + bucketRegionType := "region_location" + transitionDate := "2024-09-05T00:00:00Z" + tStorageclass := "GLACIER" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIBMCosBucketDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCosBucket_Lifecycle_Configuration_Transition_With_Date(serviceName, bucketName, bucketRegionType, bucketRegion, bucketClass, transitionDate, tStorageclass), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIBMCosBucketExists("ibm_resource_instance.instance", "ibm_cos_bucket.bucket", bucketRegionType, bucketRegion, bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "bucket_name", bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "storage_class", bucketClass), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "region_location", bucketRegion), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.#", "1"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.transition.0.date", transitionDate), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.transition.0.storage_class", "GLACIER"), + ), + }, + }, + }) +} + +func TestAccIBMCosBucket_Lifecycle_Configuration_Transition_With_Days_Accelerated(t *testing.T) { + serviceName := fmt.Sprintf("terraform_%d", acctest.RandIntRange(10, 100)) + bucketName := fmt.Sprintf("terraform-lifecycle-configuration%d", acctest.RandIntRange(10, 100)) + bucketRegion := "us-south" + bucketClass := "standard" + bucketRegionType := "region_location" + transitionDays := 1 + tStorageclass := "ACCELERATED" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIBMCosBucketDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCosBucket_Lifecycle_Configuration_Transition_With_Days(serviceName, bucketName, bucketRegionType, bucketRegion, bucketClass, transitionDays, tStorageclass), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIBMCosBucketExists("ibm_resource_instance.instance", "ibm_cos_bucket.bucket", bucketRegionType, bucketRegion, bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "bucket_name", bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "storage_class", bucketClass), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "region_location", bucketRegion), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.#", "1"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.transition.0.days", "1"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.transition.0.storage_class", "ACCELERATED"), + ), + }, + }, + }) +} + +func TestAccIBMCosBucket_Lifecycle_Configuration_Expiration_With_Abort_Incomplete_Multipart_Upload(t *testing.T) { + serviceName := fmt.Sprintf("terraform_%d", acctest.RandIntRange(10, 100)) + bucketName := fmt.Sprintf("terraform-lifecycle-configuration%d", acctest.RandIntRange(10, 100)) + bucketRegion := "us-south" + bucketClass := "standard" + bucketRegionType := "region_location" + expirationDays := 2 + daysAfterInitiation := 1 + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIBMCosBucketDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCosBucket_Lifecycle_Configuration_Expiration_With_Abort_Incomplete_Multipart_Upload(serviceName, bucketName, bucketRegionType, bucketRegion, bucketClass, expirationDays, daysAfterInitiation), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIBMCosBucketExists("ibm_resource_instance.instance", "ibm_cos_bucket.bucket", bucketRegionType, bucketRegion, bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "bucket_name", bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "storage_class", bucketClass), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "region_location", bucketRegion), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.#", "1"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.expiration.0.days", "2"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.abort_incomplete_multipart_upload.0.days_after_initiation", "1"), + ), + }, + }, + }) +} + +func TestAccIBMCosBucket_Lifecycle_Configuration_Abort_Incomplete_Multipart_Upload(t *testing.T) { + serviceName := fmt.Sprintf("terraform_%d", acctest.RandIntRange(10, 100)) + bucketName := fmt.Sprintf("terraform-lifecycle-configuration%d", acctest.RandIntRange(10, 100)) + bucketRegion := "us-south" + bucketClass := "standard" + bucketRegionType := "region_location" + daysAfterInitiation := 1 + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIBMCosBucketDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCosBucket_Lifecycle_Configuration_Abort_Incomplete_Multipart_Upload(serviceName, bucketName, bucketRegionType, bucketRegion, bucketClass, daysAfterInitiation), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIBMCosBucketExists("ibm_resource_instance.instance", "ibm_cos_bucket.bucket", bucketRegionType, bucketRegion, bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "bucket_name", bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "storage_class", bucketClass), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "region_location", bucketRegion), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.#", "1"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.abort_incomplete_multipart_upload.0.days_after_initiation", "1"), + ), + }, + }, + }) +} + +func TestAccIBMCosBucket_Lifecycle_Configuration_Transition_With_Date_Accelerated(t *testing.T) { + serviceName := fmt.Sprintf("terraform_%d", acctest.RandIntRange(10, 100)) + bucketName := fmt.Sprintf("terraform-lifecycle-configuration%d", acctest.RandIntRange(10, 100)) + bucketRegion := "us-south" + bucketClass := "standard" + bucketRegionType := "region_location" + transitionDate := "2024-09-05T00:00:00Z" + tStorageclass := "ACCELERATED" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIBMCosBucketDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCosBucket_Lifecycle_Configuration_Transition_With_Date(serviceName, bucketName, bucketRegionType, bucketRegion, bucketClass, transitionDate, tStorageclass), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIBMCosBucketExists("ibm_resource_instance.instance", "ibm_cos_bucket.bucket", bucketRegionType, bucketRegion, bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "bucket_name", bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "storage_class", bucketClass), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "region_location", bucketRegion), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.#", "1"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.transition.0.date", transitionDate), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.transition.0.storage_class", "ACCELERATED"), + ), + }, + }, + }) +} + +func TestAccIBMCosBucket_Lifecycle_Configuration_Expiration_With_Transition(t *testing.T) { + serviceName := fmt.Sprintf("terraform_%d", acctest.RandIntRange(10, 100)) + bucketName := fmt.Sprintf("terraform-lifecycle-configuration%d", acctest.RandIntRange(10, 100)) + bucketRegion := "us-south" + bucketClass := "standard" + bucketRegionType := "region_location" + expirationDays := 2 + transitionDays := 1 + tStorageClass := "GLACIER" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIBMCosBucketDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCosBucket_Lifecycle_Configuration_Expiration_With_Transition(serviceName, bucketName, bucketRegionType, bucketRegion, bucketClass, expirationDays, transitionDays, tStorageClass), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIBMCosBucketExists("ibm_resource_instance.instance", "ibm_cos_bucket.bucket", bucketRegionType, bucketRegion, bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "bucket_name", bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "storage_class", bucketClass), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "region_location", bucketRegion), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.#", "1"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.expiration.0.days", "2"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.transition.0.days", "1"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.transition.0.storage_class", "GLACIER"), + ), + }, + }, + }) +} + +func TestAccIBMCosBucket_Lifecycle_Configuration_Transition_With_Abort_Incomplete_Multipart_Upload(t *testing.T) { + serviceName := fmt.Sprintf("terraform_%d", acctest.RandIntRange(10, 100)) + bucketName := fmt.Sprintf("terraform-lifecycle-configuration%d", acctest.RandIntRange(10, 100)) + bucketRegion := "us-south" + bucketClass := "standard" + bucketRegionType := "region_location" + transitionDays := 2 + tStorageClass := "GLACIER" + initiationDays := 1 + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIBMCosBucketDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCosBucket_Lifecycle_Configuration_Transition_With_Abort_Incomplete_Multipart_Upload(serviceName, bucketName, bucketRegionType, bucketRegion, bucketClass, transitionDays, tStorageClass, initiationDays), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIBMCosBucketExists("ibm_resource_instance.instance", "ibm_cos_bucket.bucket", bucketRegionType, bucketRegion, bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "bucket_name", bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "storage_class", bucketClass), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "region_location", bucketRegion), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.#", "1"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.transition.0.days", "2"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.transition.0.storage_class", "GLACIER"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.abort_incomplete_multipart_upload.0.days_after_initiation", "1"), + ), + }, + }, + }) +} + +func TestAccIBMCosBucket_Lifecycle_Configuration_Expiration_With_Noncurrent_Version_Expiration(t *testing.T) { + serviceName := fmt.Sprintf("terraform_%d", acctest.RandIntRange(10, 100)) + bucketName := fmt.Sprintf("terraform-lifecycle-configuration%d", acctest.RandIntRange(10, 100)) + bucketRegion := "us-south" + bucketClass := "standard" + bucketRegionType := "region_location" + expirationDays := 2 + nonCurrentDays := 1 + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIBMCosBucketDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCosBucket_Lifecycle_Configuration_Expiration_With_Noncurrent_Version_Expiration(serviceName, bucketName, bucketRegionType, bucketRegion, bucketClass, expirationDays, nonCurrentDays), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIBMCosBucketExists("ibm_resource_instance.instance", "ibm_cos_bucket.bucket", bucketRegionType, bucketRegion, bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "bucket_name", bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "storage_class", bucketClass), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "region_location", bucketRegion), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.#", "1"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.expiration.0.days", "2"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.noncurrent_version_expiration.0.noncurrent_days", "1"), + ), + }, + }, + }) +} + +func TestAccIBMCosBucket_Lifecycle_Configuration_Expiration_With_Expired_Object_Delete_Marker(t *testing.T) { + serviceName := fmt.Sprintf("terraform_%d", acctest.RandIntRange(10, 100)) + bucketName := fmt.Sprintf("terraform-lifecycle-configuration%d", acctest.RandIntRange(10, 100)) + bucketRegion := "us-south" + bucketClass := "standard" + bucketRegionType := "region_location" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIBMCosBucketDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCosBucket_Lifecycle_Configuration_Expiration_With_Expired_Object_Delete_Marker(serviceName, bucketName, bucketRegionType, bucketRegion, bucketClass), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIBMCosBucketExists("ibm_resource_instance.instance", "ibm_cos_bucket.bucket", bucketRegionType, bucketRegion, bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "bucket_name", bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "storage_class", bucketClass), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "region_location", bucketRegion), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.#", "1"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.expiration.0.expired_object_delete_marker", "true"), + ), + }, + }, + }) +} + +func TestAccIBMCosBucket_Lifecycle_Configuration_Expiration_With_Expired_Object_Delete_Marker_On_Versioning_enable_Bucket(t *testing.T) { + serviceName := fmt.Sprintf("terraform_%d", acctest.RandIntRange(10, 100)) + bucketName := fmt.Sprintf("terraform-lifecycle-configuration%d", acctest.RandIntRange(10, 100)) + bucketRegion := "us-south" + bucketClass := "standard" + bucketRegionType := "region_location" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIBMCosBucketDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCosBucket_Lifecycle_Configuration_Expiration_With_Expired_Object_Delete_Marker_On_Versioning_Bucket(serviceName, bucketName, bucketRegionType, bucketRegion, bucketClass), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIBMCosBucketExists("ibm_resource_instance.instance", "ibm_cos_bucket.bucket", bucketRegionType, bucketRegion, bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "bucket_name", bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "storage_class", bucketClass), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "region_location", bucketRegion), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.#", "1"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.expiration.0.expired_object_delete_marker", "true"), + ), + }, + }, + }) +} + +func TestAccIBMCosBucket_Lifecycle_Configuration_Expiration_Transition_Abort_Incomplete_Multipart_Upload_All(t *testing.T) { + serviceName := fmt.Sprintf("terraform_%d", acctest.RandIntRange(10, 100)) + bucketName := fmt.Sprintf("terraform-lifecycle-configuration%d", acctest.RandIntRange(10, 100)) + bucketRegion := "us-south" + bucketClass := "standard" + bucketRegionType := "region_location" + expirationDays := 3 + transitionDays := 2 + tStorageclass := "GLACIER" + daysAfterInitiation := 1 + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIBMCosBucketDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCosBucket_Lifecycle_Configuration_Expiration_Transition_Abort_Incomplete_Multipart_Upload(serviceName, bucketName, bucketRegionType, bucketRegion, bucketClass, expirationDays, transitionDays, tStorageclass, daysAfterInitiation), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIBMCosBucketExists("ibm_resource_instance.instance", "ibm_cos_bucket.bucket", bucketRegionType, bucketRegion, bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "bucket_name", bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "storage_class", bucketClass), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "region_location", bucketRegion), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.#", "1"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.expiration.0.days", "3"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.transition.0.days", "2"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.transition.0.storage_class", "GLACIER"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.abort_incomplete_multipart_upload.0.days_after_initiation", "1"), + ), + }, + }, + }) +} + +func TestAccIBMCosBucket_Lifecycle_Configuration_With_No_Filter(t *testing.T) { + serviceName := fmt.Sprintf("terraform_%d", acctest.RandIntRange(10, 100)) + bucketName := fmt.Sprintf("terraform-lifecycle-configuration%d", acctest.RandIntRange(10, 100)) + bucketRegion := "us-south" + bucketClass := "standard" + bucketRegionType := "region_location" + expirationDays := 1 + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIBMCosBucketDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCosBucket_Lifecycle_Configuration_With_No_Filter(serviceName, bucketName, bucketRegionType, bucketRegion, bucketClass, expirationDays), + ExpectError: regexp.MustCompile("Error: Insufficient filter blocks"), + }, + }, + }) +} + +func TestAccIBMCosBucket_Lifecycle_Configuration_Status_Disabled(t *testing.T) { + serviceName := fmt.Sprintf("terraform_%d", acctest.RandIntRange(10, 100)) + bucketName := fmt.Sprintf("terraform-lifecycle-configuration%d", acctest.RandIntRange(10, 100)) + bucketRegion := "us-south" + bucketClass := "standard" + bucketRegionType := "region_location" + expirationDays := 1 + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIBMCosBucketDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCosBucket_Lifecycle_Configuration_Status_disable(serviceName, bucketName, bucketRegionType, bucketRegion, bucketClass, expirationDays), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIBMCosBucketExists("ibm_resource_instance.instance", "ibm_cos_bucket.bucket", bucketRegionType, bucketRegion, bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "bucket_name", bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "storage_class", bucketClass), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "region_location", bucketRegion), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.#", "1"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.expiration.0.days", "1"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.status", "disable"), + ), + }, + }, + }) +} + +func TestAccIBMCosBucket_Lifecycle_Configuration_Multiple_Rules(t *testing.T) { + serviceName := fmt.Sprintf("terraform_%d", acctest.RandIntRange(10, 100)) + bucketName := fmt.Sprintf("terraform-lifecycle-configuration%d", acctest.RandIntRange(10, 100)) + bucketRegion := "us-south" + bucketClass := "standard" + bucketRegionType := "region_location" + expirationDays1 := 2 + daysAfterInitiation1 := 1 + expirationDays2 := 4 + daysAfterInitiation2 := 3 + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIBMCosBucketDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCosBucket_Lifecycle_Configuration_Multiple_Rules(serviceName, bucketName, bucketRegionType, bucketRegion, bucketClass, expirationDays1, daysAfterInitiation1, expirationDays2, daysAfterInitiation2), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIBMCosBucketExists("ibm_resource_instance.instance", "ibm_cos_bucket.bucket", bucketRegionType, bucketRegion, bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "bucket_name", bucketName), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "storage_class", bucketClass), + resource.TestCheckResourceAttr("ibm_cos_bucket.bucket", "region_location", bucketRegion), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.#", "2"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.expiration.0.days", "2"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.0.abort_incomplete_multipart_upload.0.days_after_initiation", "1"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.1.expiration.0.days", "4"), + resource.TestCheckResourceAttr("ibm_cos_bucket_lifecycle_configuration.lifecycle", "lifecycle_rule.1.abort_incomplete_multipart_upload.0.days_after_initiation", "3"), + ), + }, + }, + }) +} + +func TestAccIBMCosBucket_Lifecycle_Configuration_Expiration_With_Invalid_Days(t *testing.T) { + serviceName := fmt.Sprintf("terraform_%d", acctest.RandIntRange(10, 100)) + bucketName := fmt.Sprintf("terraform-lifecycle-configuration%d", acctest.RandIntRange(10, 100)) + bucketRegion := "us-south" + bucketClass := "standard" + bucketRegionType := "region_location" + expirationDays := -1 + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIBMCosBucketDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCosBucket_Lifecycle_Configuration_Expiration_With_Days(serviceName, bucketName, bucketRegionType, bucketRegion, bucketClass, expirationDays), + ExpectError: regexp.MustCompile(`"lifecycle_rule.0.expiration.0.days" must contain a valid int value should be in range\(1, 3650\), got -1`), + }, + }, + }) +} + +func TestAccIBMCosBucket_Lifecycle_Configuration_Transition_With_Invalid_Days(t *testing.T) { + serviceName := fmt.Sprintf("terraform_%d", acctest.RandIntRange(10, 100)) + bucketName := fmt.Sprintf("terraform-lifecycle-configuration%d", acctest.RandIntRange(10, 100)) + bucketRegion := "us-south" + bucketClass := "standard" + bucketRegionType := "region_location" + transitionDays := -1 + tStorageclass := "GLACIER" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIBMCosBucketDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCosBucket_Lifecycle_Configuration_Transition_With_Days(serviceName, bucketName, bucketRegionType, bucketRegion, bucketClass, transitionDays, tStorageclass), + ExpectError: regexp.MustCompile(`"lifecycle_rule.0.transition.0.days" must contain a valid int value should be in range\(0, 3650\), got -1`), + }, + }, + }) +} + +func TestAccIBMCosBucket_Lifecycle_Configuration_Transition_With_Invalid_Storage_Class(t *testing.T) { + serviceName := fmt.Sprintf("terraform_%d", acctest.RandIntRange(10, 100)) + bucketName := fmt.Sprintf("terraform-lifecycle-configuration%d", acctest.RandIntRange(10, 100)) + bucketRegion := "us-south" + bucketClass := "standard" + bucketRegionType := "region_location" + transitionDays := 1 + tStorageclass := "Invalid" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIBMCosBucketDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCosBucket_Lifecycle_Configuration_Transition_With_Days(serviceName, bucketName, bucketRegionType, bucketRegion, bucketClass, transitionDays, tStorageclass), + ExpectError: regexp.MustCompile(`"lifecycle_rule.0.transition.0.storage_class" must contain a value from \[\]string\{"GLACIER", "ACCELERATED"\}, got "Invalid`), + }, + }, + }) +} +func TestAccIBMCosBucket_Lifecycle_Configuration_Transition_Multiple_Rules(t *testing.T) { + serviceName := fmt.Sprintf("terraform_%d", acctest.RandIntRange(10, 100)) + bucketName := fmt.Sprintf("terraform-lifecycle-configuration%d", acctest.RandIntRange(10, 100)) + bucketRegion := "us-south" + bucketClass := "standard" + bucketRegionType := "region_location" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIBMCosBucketDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMCosBucket_Lifecycle_Configuration_Transition_With_Multiple_Rules(serviceName, bucketName, bucketRegionType, bucketRegion, bucketClass), + ExpectError: regexp.MustCompile("MalformedXML: The XML you provided was not well-formed or did not validate against our published schema."), + }, + }, + }) +} + +func testAccCheckIBMCosBucket_Lifecycle_Configuration_Expiration_With_Days(cosServiceName string, bucketName string, regiontype string, region string, storageClass string, days int) string { + + return fmt.Sprintf(` + data "ibm_resource_group" "cos_group" { + name = "Default" + } + + resource "ibm_resource_instance" "instance" { + name = "%s" + service = "cloud-object-storage" + plan = "standard" + location = "global" + resource_group_id = data.ibm_resource_group.cos_group.id + } + resource "ibm_cos_bucket" "bucket" { + bucket_name = "%s" + resource_instance_id = ibm_resource_instance.instance.id + region_location = "%s" + storage_class = "%s" + } + resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.bucket.crn + bucket_location = ibm_cos_bucket.bucket.region_location + lifecycle_rule { + expiration{ + days = "%d" + } + filter { + prefix = "foo" + } + rule_id = "id" + status = "enable" + + } + } + `, cosServiceName, bucketName, region, storageClass, days) +} + +func testAccCheckIBMCosBucket_Lifecycle_Configuration_Expiration_With_Date(cosServiceName string, bucketName string, regiontype string, region string, storageClass string, date string) string { + + return fmt.Sprintf(` + data "ibm_resource_group" "cos_group" { + name = "Default" + } + + resource "ibm_resource_instance" "instance" { + name = "%s" + service = "cloud-object-storage" + plan = "standard" + location = "global" + resource_group_id = data.ibm_resource_group.cos_group.id + } + resource "ibm_cos_bucket" "bucket" { + bucket_name = "%s" + resource_instance_id = ibm_resource_instance.instance.id + region_location = "%s" + storage_class = "%s" + } + resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.bucket.crn + bucket_location = ibm_cos_bucket.bucket.region_location + lifecycle_rule { + expiration{ + date = "%s" + } + filter { + prefix = "foo" + } + rule_id = "id" + status = "enable" + + } + } + `, cosServiceName, bucketName, region, storageClass, date) +} + +func testAccCheckIBMCosBucket_Lifecycle_Configuration_Transition_With_Days(cosServiceName string, bucketName string, regiontype string, region string, storageClass string, days int, tStorageclass string) string { + + return fmt.Sprintf(` + data "ibm_resource_group" "cos_group" { + name = "Default" + } + + resource "ibm_resource_instance" "instance" { + name = "%s" + service = "cloud-object-storage" + plan = "standard" + location = "global" + resource_group_id = data.ibm_resource_group.cos_group.id + } + resource "ibm_cos_bucket" "bucket" { + bucket_name = "%s" + resource_instance_id = ibm_resource_instance.instance.id + region_location = "%s" + storage_class = "%s" + } + resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.bucket.crn + bucket_location = ibm_cos_bucket.bucket.region_location + lifecycle_rule { + transition{ + days = "%d" + storage_class = "%s" + } + filter { + prefix = "" + } + rule_id = "id" + status = "enable" + + } + } + `, cosServiceName, bucketName, region, storageClass, days, tStorageclass) +} + +func testAccCheckIBMCosBucket_Lifecycle_Configuration_Transition_With_Date(cosServiceName string, bucketName string, regiontype string, region string, storageClass string, date string, tStorageclass string) string { + + return fmt.Sprintf(` + data "ibm_resource_group" "cos_group" { + name = "Default" + } + + resource "ibm_resource_instance" "instance" { + name = "%s" + service = "cloud-object-storage" + plan = "standard" + location = "global" + resource_group_id = data.ibm_resource_group.cos_group.id + } + resource "ibm_cos_bucket" "bucket" { + bucket_name = "%s" + resource_instance_id = ibm_resource_instance.instance.id + region_location = "%s" + storage_class = "%s" + } + resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.bucket.crn + bucket_location = ibm_cos_bucket.bucket.region_location + lifecycle_rule { + transition{ + date = "%s" + storage_class = "%s" + } + filter { + prefix = "" + } + rule_id = "id" + status = "enable" + + } + } + `, cosServiceName, bucketName, region, storageClass, date, tStorageclass) +} + +func testAccCheckIBMCosBucket_Lifecycle_Configuration_Expiration_With_Abort_Incomplete_Multipart_Upload(cosServiceName string, bucketName string, regiontype string, region string, storageClass string, days int, initiationDays int) string { + + return fmt.Sprintf(` + data "ibm_resource_group" "cos_group" { + name = "Default" + } + + resource "ibm_resource_instance" "instance" { + name = "%s" + service = "cloud-object-storage" + plan = "standard" + location = "global" + resource_group_id = data.ibm_resource_group.cos_group.id + } + resource "ibm_cos_bucket" "bucket" { + bucket_name = "%s" + resource_instance_id = ibm_resource_instance.instance.id + region_location = "%s" + storage_class = "%s" + } + resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.bucket.crn + bucket_location = ibm_cos_bucket.bucket.region_location + lifecycle_rule { + expiration{ + days = "%d" + } + abort_incomplete_multipart_upload{ + days_after_initiation = "%d" + } + filter { + prefix = "foo" + } + rule_id = "id" + status = "enable" + + } + } + `, cosServiceName, bucketName, region, storageClass, days, initiationDays) +} + +func testAccCheckIBMCosBucket_Lifecycle_Configuration_Abort_Incomplete_Multipart_Upload(cosServiceName string, bucketName string, regiontype string, region string, storageClass string, initiationDays int) string { + + return fmt.Sprintf(` + data "ibm_resource_group" "cos_group" { + name = "Default" + } + + resource "ibm_resource_instance" "instance" { + name = "%s" + service = "cloud-object-storage" + plan = "standard" + location = "global" + resource_group_id = data.ibm_resource_group.cos_group.id + } + resource "ibm_cos_bucket" "bucket" { + bucket_name = "%s" + resource_instance_id = ibm_resource_instance.instance.id + region_location = "%s" + storage_class = "%s" + } + resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.bucket.crn + bucket_location = ibm_cos_bucket.bucket.region_location + lifecycle_rule { + abort_incomplete_multipart_upload{ + days_after_initiation = "%d" + } + filter { + prefix = "foo" + } + rule_id = "id" + status = "enable" + + } + } + `, cosServiceName, bucketName, region, storageClass, initiationDays) +} + +func testAccCheckIBMCosBucket_Lifecycle_Configuration_Expiration_With_Transition(cosServiceName string, bucketName string, regiontype string, region string, storageClass string, days int, tDays int, tStorageClass string) string { + + return fmt.Sprintf(` + data "ibm_resource_group" "cos_group" { + name = "Default" + } + + resource "ibm_resource_instance" "instance" { + name = "%s" + service = "cloud-object-storage" + plan = "standard" + location = "global" + resource_group_id = data.ibm_resource_group.cos_group.id + } + resource "ibm_cos_bucket" "bucket" { + bucket_name = "%s" + resource_instance_id = ibm_resource_instance.instance.id + region_location = "%s" + storage_class = "%s" + } + resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.bucket.crn + bucket_location = ibm_cos_bucket.bucket.region_location + lifecycle_rule { + expiration{ + days = "%d" + } + transition{ + days = "%d" + storage_class = "%s" + } + filter { + prefix = "" + } + rule_id = "id" + status = "enable" + + } + } + `, cosServiceName, bucketName, region, storageClass, days, tDays, tStorageClass) +} + +func testAccCheckIBMCosBucket_Lifecycle_Configuration_Transition_With_Abort_Incomplete_Multipart_Upload(cosServiceName string, bucketName string, regiontype string, region string, storageClass string, tDays int, tStorageClass string, initiationDays int) string { + + return fmt.Sprintf(` + data "ibm_resource_group" "cos_group" { + name = "Default" + } + + resource "ibm_resource_instance" "instance" { + name = "%s" + service = "cloud-object-storage" + plan = "standard" + location = "global" + resource_group_id = data.ibm_resource_group.cos_group.id + } + resource "ibm_cos_bucket" "bucket" { + bucket_name = "%s" + resource_instance_id = ibm_resource_instance.instance.id + region_location = "%s" + storage_class = "%s" + } + resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.bucket.crn + bucket_location = ibm_cos_bucket.bucket.region_location + lifecycle_rule { + transition{ + days = "%d" + storage_class = "%s" + } + abort_incomplete_multipart_upload{ + days_after_initiation = "%d" + } + filter { + prefix = "" + } + rule_id = "id" + status = "enable" + + } + } + `, cosServiceName, bucketName, region, storageClass, tDays, tStorageClass, initiationDays) +} + +func testAccCheckIBMCosBucket_Lifecycle_Configuration_Expiration_With_Noncurrent_Version_Expiration(cosServiceName string, bucketName string, regiontype string, region string, storageClass string, days int, ncDays int) string { + + return fmt.Sprintf(` + data "ibm_resource_group" "cos_group" { + name = "Default" + } + + resource "ibm_resource_instance" "instance" { + name = "%s" + service = "cloud-object-storage" + plan = "standard" + location = "global" + resource_group_id = data.ibm_resource_group.cos_group.id + } + resource "ibm_cos_bucket" "bucket" { + bucket_name = "%s" + resource_instance_id = ibm_resource_instance.instance.id + region_location = "%s" + storage_class = "%s" + } + resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.bucket.crn + bucket_location = ibm_cos_bucket.bucket.region_location + lifecycle_rule { + expiration{ + days = "%d" + } + noncurrent_version_expiration{ + noncurrent_days = "%d" + } + filter { + prefix = "foo" + } + rule_id = "id" + status = "enable" + + } + } + `, cosServiceName, bucketName, region, storageClass, days, ncDays) +} +func testAccCheckIBMCosBucket_Lifecycle_Configuration_Expiration_With_Expired_Object_Delete_Marker(cosServiceName string, bucketName string, regiontype string, region string, storageClass string) string { + + return fmt.Sprintf(` + data "ibm_resource_group" "cos_group" { + name = "Default" + } + + resource "ibm_resource_instance" "instance" { + name = "%s" + service = "cloud-object-storage" + plan = "standard" + location = "global" + resource_group_id = data.ibm_resource_group.cos_group.id + } + resource "ibm_cos_bucket" "bucket" { + bucket_name = "%s" + resource_instance_id = ibm_resource_instance.instance.id + region_location = "%s" + storage_class = "%s" + } + resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.bucket.crn + bucket_location = ibm_cos_bucket.bucket.region_location + lifecycle_rule { + expiration{ + expired_object_delete_marker = true + } + filter { + prefix = "foo" + } + rule_id = "id" + status = "enable" + + } + } + `, cosServiceName, bucketName, region, storageClass) +} + +func testAccCheckIBMCosBucket_Lifecycle_Configuration_Expiration_With_Expired_Object_Delete_Marker_On_Versioning_Bucket(cosServiceName string, bucketName string, regiontype string, region string, storageClass string) string { + + return fmt.Sprintf(` + data "ibm_resource_group" "cos_group" { + name = "Default" + } + + resource "ibm_resource_instance" "instance" { + name = "%s" + service = "cloud-object-storage" + plan = "standard" + location = "global" + resource_group_id = data.ibm_resource_group.cos_group.id + } + resource "ibm_cos_bucket" "bucket" { + bucket_name = "%s" + resource_instance_id = ibm_resource_instance.instance.id + region_location = "%s" + storage_class = "%s" + object_versioning { + enable = true + } + } + resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.bucket.crn + bucket_location = ibm_cos_bucket.bucket.region_location + lifecycle_rule { + expiration{ + expired_object_delete_marker = true + } + filter { + prefix = "foo" + } + rule_id = "id" + status = "enable" + + } + } + `, cosServiceName, bucketName, region, storageClass) +} + +func testAccCheckIBMCosBucket_Lifecycle_Configuration_Expiration_Transition_Abort_Incomplete_Multipart_Upload(cosServiceName string, bucketName string, regiontype string, region string, storageClass string, days int, tDays int, tStorageClass string, initiationDays int) string { + + return fmt.Sprintf(` + data "ibm_resource_group" "cos_group" { + name = "Default" + } + + resource "ibm_resource_instance" "instance" { + name = "%s" + service = "cloud-object-storage" + plan = "standard" + location = "global" + resource_group_id = data.ibm_resource_group.cos_group.id + } + resource "ibm_cos_bucket" "bucket" { + bucket_name = "%s" + resource_instance_id = ibm_resource_instance.instance.id + region_location = "%s" + storage_class = "%s" + } + resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.bucket.crn + bucket_location = ibm_cos_bucket.bucket.region_location + lifecycle_rule { + expiration{ + days = "%d" + } + transition{ + days = "%d" + storage_class = "%s" + } + abort_incomplete_multipart_upload{ + days_after_initiation = "%d" + } + filter { + prefix = "" + } + rule_id = "id" + status = "enable" + + } + } + `, cosServiceName, bucketName, region, storageClass, days, tDays, tStorageClass, initiationDays) +} + +func testAccCheckIBMCosBucket_Lifecycle_Configuration_With_No_Filter(cosServiceName string, bucketName string, regiontype string, region string, storageClass string, days int) string { + + return fmt.Sprintf(` + data "ibm_resource_group" "cos_group" { + name = "Default" + } + + resource "ibm_resource_instance" "instance" { + name = "%s" + service = "cloud-object-storage" + plan = "standard" + location = "global" + resource_group_id = data.ibm_resource_group.cos_group.id + } + resource "ibm_cos_bucket" "bucket" { + bucket_name = "%s" + resource_instance_id = ibm_resource_instance.instance.id + region_location = "%s" + storage_class = "%s" + } + resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.bucket.crn + bucket_location = ibm_cos_bucket.bucket.region_location + lifecycle_rule { + expiration{ + days = "%d" + } + rule_id = "id" + status = "enable" + + } + } + `, cosServiceName, bucketName, region, storageClass, days) +} + +func testAccCheckIBMCosBucket_Lifecycle_Configuration_Status_disable(cosServiceName string, bucketName string, regiontype string, region string, storageClass string, days int) string { + + return fmt.Sprintf(` + data "ibm_resource_group" "cos_group" { + name = "Default" + } + + resource "ibm_resource_instance" "instance" { + name = "%s" + service = "cloud-object-storage" + plan = "standard" + location = "global" + resource_group_id = data.ibm_resource_group.cos_group.id + } + resource "ibm_cos_bucket" "bucket" { + bucket_name = "%s" + resource_instance_id = ibm_resource_instance.instance.id + region_location = "%s" + storage_class = "%s" + } + resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.bucket.crn + bucket_location = ibm_cos_bucket.bucket.region_location + lifecycle_rule { + expiration{ + days = "%d" + } + filter { + prefix = "foo" + } + rule_id = "id" + status = "disable" + + } + } + `, cosServiceName, bucketName, region, storageClass, days) +} + +func testAccCheckIBMCosBucket_Lifecycle_Configuration_Multiple_Rules(cosServiceName string, bucketName string, regiontype string, region string, storageClass string, days1 int, initiationDays1 int, days2 int, initiationDays2 int) string { + + return fmt.Sprintf(` + data "ibm_resource_group" "cos_group" { + name = "Default" + } + + resource "ibm_resource_instance" "instance" { + name = "%s" + service = "cloud-object-storage" + plan = "standard" + location = "global" + resource_group_id = data.ibm_resource_group.cos_group.id + } + resource "ibm_cos_bucket" "bucket" { + bucket_name = "%s" + resource_instance_id = ibm_resource_instance.instance.id + region_location = "%s" + storage_class = "%s" + } + resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.bucket.crn + bucket_location = ibm_cos_bucket.bucket.region_location + lifecycle_rule { + expiration{ + days = "%d" + } + abort_incomplete_multipart_upload{ + days_after_initiation = "%d" + } + filter { + prefix = "foo" + } + rule_id = "id1" + status = "enable" + + } + lifecycle_rule { + expiration{ + days = "%d" + } + abort_incomplete_multipart_upload{ + days_after_initiation = "%d" + } + filter { + prefix = "bar" + } + rule_id = "id2" + status = "enable" + + } + } + `, cosServiceName, bucketName, region, storageClass, days1, initiationDays1, days2, initiationDays2) +} + +func testAccCheckIBMCosBucket_Lifecycle_Configuration_Transition_With_Multiple_Rules(cosServiceName string, bucketName string, regiontype string, region string, storageClass string) string { + + return fmt.Sprintf(` + data "ibm_resource_group" "cos_group" { + name = "Default" + } + + resource "ibm_resource_instance" "instance" { + name = "%s" + service = "cloud-object-storage" + plan = "standard" + location = "global" + resource_group_id = data.ibm_resource_group.cos_group.id + } + resource "ibm_cos_bucket" "bucket" { + bucket_name = "%s" + resource_instance_id = ibm_resource_instance.instance.id + region_location = "%s" + storage_class = "%s" + } + resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.bucket.crn + bucket_location = ibm_cos_bucket.bucket.region_location + lifecycle_rule { + transition{ + days = 1 + storage_class = "GLACIER" + } + filter { + prefix = "" + } + rule_id = "id" + status = "enable" + } + lifecycle_rule { + transition{ + days = 3 + storage_class = "ACCELERATED" + } + filter { + prefix = "" + } + rule_id = "id2" + status = "enable" + + } + } + `, cosServiceName, bucketName, region, storageClass) +} diff --git a/ibm/service/cos/resource_ibm_cos_bucket_object.go b/ibm/service/cos/resource_ibm_cos_bucket_object.go index e907534138..4868e74064 100644 --- a/ibm/service/cos/resource_ibm_cos_bucket_object.go +++ b/ibm/service/cos/resource_ibm_cos_bucket_object.go @@ -476,17 +476,21 @@ func resourceIBMCOSBucketObjectDelete(ctx context.Context, d *schema.ResourceDat return nil } -func getCosEndpoint(bucketLocation string, endpointType string) string { +func getCosEndpoint(bucketLocation string, endpointType string, test bool) string { if bucketLocation != "" { + hostUrl := "cloud-object-storage.appdomain.cloud" + if test { + hostUrl = "cloud-object-storage.test.appdomain.cloud" + } switch endpointType { case "public": - return fmt.Sprintf("s3.%s.cloud-object-storage.appdomain.cloud", bucketLocation) + return fmt.Sprintf("s3.%s.%s", bucketLocation, hostUrl) case "private": - return fmt.Sprintf("s3.private.%s.cloud-object-storage.appdomain.cloud", bucketLocation) + return fmt.Sprintf("s3.private.%s.%s", bucketLocation, hostUrl) case "direct": - return fmt.Sprintf("s3.direct.%s.cloud-object-storage.appdomain.cloud", bucketLocation) + return fmt.Sprintf("s3.direct.%s.%s", bucketLocation, hostUrl) default: - return fmt.Sprintf("s3.%s.cloud-object-storage.appdomain.cloud", bucketLocation) + return fmt.Sprintf("s3.%s.%s", bucketLocation, hostUrl) } } return "" @@ -498,8 +502,7 @@ func getS3Client(bxSession *bxsession.Session, bucketLocation string, endpointTy if endpointType == "direct" { visibility = "private" } - - apiEndpoint := getCosEndpoint(bucketLocation, endpointType) + apiEndpoint := getCosEndpoint(bucketLocation, endpointType, false) apiEndpoint = conns.FileFallBack(bxSession.Config.EndpointsFile, visibility, "IBMCLOUD_COS_ENDPOINT", bucketLocation, apiEndpoint) apiEndpoint = conns.EnvFallBack([]string{"IBMCLOUD_COS_ENDPOINT"}, apiEndpoint) if apiEndpoint == "" { diff --git a/ibm/service/cos/resource_ibm_cos_bucket_test.go b/ibm/service/cos/resource_ibm_cos_bucket_test.go index 8cc51802de..1a27c0ba49 100644 --- a/ibm/service/cos/resource_ibm_cos_bucket_test.go +++ b/ibm/service/cos/resource_ibm_cos_bucket_test.go @@ -2242,7 +2242,7 @@ func testAccCheckIBMCosBucketExists(resource string, bucket string, regiontype s rt = "crl" } - apiEndpoint, _, _ := cos.SelectCosApi(rt, region) + apiEndpoint, _, _ := cos.SelectCosApi(rt, region, false) rsContClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).BluemixSession() if err != nil { diff --git a/ibm/service/cos/resource_ibm_cos_replication_configuration.go b/ibm/service/cos/resource_ibm_cos_replication_configuration.go index f805ace41f..fbd461d899 100644 --- a/ibm/service/cos/resource_ibm_cos_replication_configuration.go +++ b/ibm/service/cos/resource_ibm_cos_replication_configuration.go @@ -334,19 +334,25 @@ func parseBucketReplId(id string, info string) string { return parseBucketId(bucketCRN, info) } -func getCosEndpointType(bucketLocation string, endpointType string) string { +func getCosEndpointType(bucketLocation string, endpointType string, test bool) string { + if bucketLocation != "" { + hostUrl := "cloud-object-storage.appdomain.cloud" + if test { + hostUrl = "cloud-object-storage.test.appdomain.cloud" + } switch endpointType { case "public": - return fmt.Sprintf("s3.%s.cloud-object-storage.appdomain.cloud", bucketLocation) + return fmt.Sprintf("s3.%s.%s", bucketLocation, hostUrl) case "private": - return fmt.Sprintf("s3.private.%s.cloud-object-storage.appdomain.cloud", bucketLocation) + return fmt.Sprintf("s3.private.%s.%s", bucketLocation, hostUrl) case "direct": - return fmt.Sprintf("s3.direct.%s.cloud-object-storage.appdomain.cloud", bucketLocation) + return fmt.Sprintf("s3.direct.%s.%s", bucketLocation, hostUrl) default: - return fmt.Sprintf("s3.%s.cloud-object-storage.appdomain.cloud", bucketLocation) + return fmt.Sprintf("s3.%s.%s", bucketLocation, hostUrl) } } + return "" } @@ -357,8 +363,7 @@ func getS3ClientSession(bxSession *bxsession.Session, bucketLocation string, end if endpointType == "direct" { visibility = "private" } - - apiEndpoint := getCosEndpointType(bucketLocation, endpointType) + apiEndpoint := getCosEndpointType(bucketLocation, endpointType, false) apiEndpoint = conns.FileFallBack(bxSession.Config.EndpointsFile, visibility, "IBMCLOUD_COS_ENDPOINT", bucketLocation, apiEndpoint) apiEndpoint = conns.EnvFallBack([]string{"IBMCLOUD_COS_ENDPOINT"}, apiEndpoint) if apiEndpoint == "" { diff --git a/ibm/service/database/data_source_ibm_database_connection_test.go b/ibm/service/database/data_source_ibm_database_connection_test.go index fca45cc452..b06e3d2405 100644 --- a/ibm/service/database/data_source_ibm_database_connection_test.go +++ b/ibm/service/database/data_source_ibm_database_connection_test.go @@ -52,6 +52,7 @@ func testAccCheckIBMDatabaseDataSourceConfig2(name string) string { plan = "standard" location = "%[2]s" tags = ["one:two"] + service_endpoints = "public" } `, name, acc.Region()) diff --git a/ibm/service/database/data_source_ibm_database_test.go b/ibm/service/database/data_source_ibm_database_test.go index 950d9fc14b..e7feef9a48 100644 --- a/ibm/service/database/data_source_ibm_database_test.go +++ b/ibm/service/database/data_source_ibm_database_test.go @@ -64,6 +64,7 @@ func testAccCheckIBMDatabaseDataSourceConfig(databaseResourceGroup string, name plan = "standard" location = "%[3]s" tags = ["one:two"] + service_endpoints = "public" } `, databaseResourceGroup, name, acc.Region()) diff --git a/ibm/service/database/resource_ibm_database.go b/ibm/service/database/resource_ibm_database.go index 1ce2a8ce34..50198a8145 100644 --- a/ibm/service/database/resource_ibm_database.go +++ b/ibm/service/database/resource_ibm_database.go @@ -249,14 +249,8 @@ func ResourceIBMDatabaseInstance() *schema.Resource { "service_endpoints": { Description: "Types of the service endpoints. Possible values are 'public', 'private', 'public-and-private'.", Type: schema.TypeString, - Optional: true, + Required: true, ValidateFunc: validate.InvokeValidator("ibm_database", "service_endpoints"), - DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool { - if new == "" { - return true - } - return false - }, }, "backup_id": { Description: "The CRN of backup source database", @@ -808,6 +802,13 @@ func ResourceIBMDatabaseInstance() *schema.Resource { }, }, }, + flex.DeletionProtection: { + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "Whether Terraform will be prevented from destroying the instance", + }, + flex.ResourceName: { Type: schema.TypeString, Computed: true, @@ -1722,6 +1723,11 @@ func resourceIBMDatabaseInstanceRead(context context.Context, d *schema.Resource return appendSwitchoverWarning() } + endpoint, _ := instance.Parameters["service-endpoints"] + if endpoint == "public" || endpoint == "public-and-private" { + return publicServiceEndpointsWarning() + } + return nil } @@ -2742,6 +2748,19 @@ func appendSwitchoverWarning() diag.Diagnostics { return diags } +func publicServiceEndpointsWarning() diag.Diagnostics { + var diags diag.Diagnostics + + warning := diag.Diagnostic{ + Severity: diag.Warning, + Summary: "IBM recommends using private endpoints only to improve security by restricting access to your database to the IBM Cloud private network. For more information, please refer to our security best practices, https://cloud.ibm.com/docs/cloud-databases?topic=cloud-databases-manage-security-compliance.", + } + + diags = append(diags, warning) + + return diags +} + func validateGroupsDiff(_ context.Context, diff *schema.ResourceDiff, meta interface{}) (err error) { instanceID := diff.Id() service := diff.Get("service").(string) diff --git a/ibm/service/database/resource_ibm_database_edb_test.go b/ibm/service/database/resource_ibm_database_edb_test.go index 00f2ee1904..7936460bf4 100644 --- a/ibm/service/database/resource_ibm_database_edb_test.go +++ b/ibm/service/database/resource_ibm_database_edb_test.go @@ -107,6 +107,7 @@ func testAccCheckIBMDatabaseInstanceEDBBasic(databaseResourceGroup string, name allocation_mb = 20480 } } + service_endpoints = "public-and-private" tags = ["one:two"] users { name = "user123" diff --git a/ibm/service/database/resource_ibm_database_elasticsearch_platinum_test.go b/ibm/service/database/resource_ibm_database_elasticsearch_platinum_test.go index 51d1802ef2..6d9e3e655b 100644 --- a/ibm/service/database/resource_ibm_database_elasticsearch_platinum_test.go +++ b/ibm/service/database/resource_ibm_database_elasticsearch_platinum_test.go @@ -296,6 +296,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchPlatinumBasic(databaseResourceG plan = "platinum" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public-and-private" group { group_id = "member" @@ -338,6 +339,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchPlatinumFullyspecified(database plan = "platinum" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public-and-private" group { group_id = "member" @@ -386,6 +388,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchPlatinumReduced(databaseResourc plan = "platinum" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public-and-private" group { group_id = "member" @@ -417,6 +420,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchPlatinumGroupMigration(database plan = "platinum" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public-and-private" group { group_id = "member" @@ -452,6 +456,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchPlatinumNodeBasic(databaseResou plan = "platinum" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public-and-private" group { group_id = "member" members { @@ -497,6 +502,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchPlatinumNodeFullyspecified(data plan = "platinum" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public-and-private" group { group_id = "member" members { @@ -549,6 +555,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchPlatinumNodeReduced(databaseRes plan = "platinum" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public-and-private" group { group_id = "member" members { @@ -585,6 +592,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchPlatinumNodeScaleOut(databaseRe plan = "platinum" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public-and-private" group { group_id = "member" members { @@ -621,6 +629,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchPlatinumGroupBasic(databaseReso plan = "platinum" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public-and-private" group { group_id = "member" @@ -667,6 +676,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchPlatinumGroupFullyspecified(dat plan = "platinum" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public-and-private" group { group_id = "member" @@ -721,6 +731,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchPlatinumGroupReduced(databaseRe plan = "platinum" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public-and-private" group { group_id = "member" @@ -758,6 +769,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchPlatinumGroupScaleOut(databaseR plan = "platinum" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public-and-private" group { group_id = "member" @@ -793,6 +805,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchPlatinumImport(databaseResource service = "databases-for-elasticsearch" plan = "platinum" location = "%[3]s" + service_endpoints = "public-and-private" timeouts { create = "120m" diff --git a/ibm/service/database/resource_ibm_database_elasticsearch_test.go b/ibm/service/database/resource_ibm_database_elasticsearch_test.go index e27f778876..763f450be7 100644 --- a/ibm/service/database/resource_ibm_database_elasticsearch_test.go +++ b/ibm/service/database/resource_ibm_database_elasticsearch_test.go @@ -293,6 +293,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchBasic(databaseResourceGroup str plan = "standard" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public" users { name = "user123" password = "password12345678" @@ -335,6 +336,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchFullyspecified(databaseResource plan = "standard" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public" users { name = "user123" password = "password12345678" @@ -386,6 +388,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchReduced(databaseResourceGroup s plan = "standard" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public" group { group_id = "member" @@ -420,6 +423,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchGroupMigration(databaseResource plan = "standard" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public" group { group_id = "member" @@ -458,6 +462,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchNodeBasic(databaseResourceGroup plan = "standard" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public" group { group_id = "member" @@ -509,6 +514,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchNodeFullyspecified(databaseReso plan = "standard" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public" group { group_id = "member" members { @@ -567,6 +573,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchNodeReduced(databaseResourceGro plan = "standard" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public" group { group_id = "member" members { @@ -609,6 +616,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchNodeScaleOut(databaseResourceGr plan = "standard" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public" group { group_id = "member" members { @@ -651,6 +659,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchGroupBasic(databaseResourceGrou plan = "standard" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public" group { group_id = "member" @@ -703,6 +712,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchGroupFullyspecified(databaseRes plan = "standard" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public" group { group_id = "member" @@ -763,6 +773,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchGroupReduced(databaseResourceGr plan = "standard" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public" group { group_id = "member" @@ -806,6 +817,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchGroupScaleOut(databaseResourceG plan = "standard" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public" group { group_id = "member" @@ -847,6 +859,7 @@ func testAccCheckIBMDatabaseInstanceElasticsearchImport(databaseResourceGroup st service = "databases-for-elasticsearch" plan = "standard" location = "%[3]s" + service_endpoints = "public" timeouts { create = "120m" diff --git a/ibm/service/database/resource_ibm_database_etcd_test.go b/ibm/service/database/resource_ibm_database_etcd_test.go index 91cff8d6fc..236dc8811e 100644 --- a/ibm/service/database/resource_ibm_database_etcd_test.go +++ b/ibm/service/database/resource_ibm_database_etcd_test.go @@ -123,6 +123,7 @@ func testAccCheckIBMDatabaseInstanceEtcdBasic(databaseResourceGroup string, name plan = "standard" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public-and-private" group { group_id = "member" memory { @@ -161,6 +162,7 @@ func testAccCheckIBMDatabaseInstanceEtcdFullyspecified(databaseResourceGroup str plan = "standard" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public-and-private" group { group_id = "member" host_flavor { @@ -205,6 +207,7 @@ func testAccCheckIBMDatabaseInstanceEtcdReduced(databaseResourceGroup string, na plan = "standard" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public-and-private" group { group_id = "member" memory { @@ -234,6 +237,7 @@ func testAccCheckIBMDatabaseInstanceEtcdImport(databaseResourceGroup string, nam service = "databases-for-etcd" plan = "standard" location = "%[3]s" + service_endpoints = "public-and-private" } `, databaseResourceGroup, name, acc.Region()) } diff --git a/ibm/service/database/resource_ibm_database_mongodb_enterprise_test.go b/ibm/service/database/resource_ibm_database_mongodb_enterprise_test.go index 1ac55ec575..866ab9530e 100644 --- a/ibm/service/database/resource_ibm_database_mongodb_enterprise_test.go +++ b/ibm/service/database/resource_ibm_database_mongodb_enterprise_test.go @@ -233,6 +233,7 @@ func testAccCheckIBMDatabaseInstanceMongoDBEnterpriseFullyspecified(databaseReso location = "%[3]s" adminpassword = "password12345678" tags = ["one:two"] + service_endpoints = "public" group { group_id = "member" host_flavor { @@ -316,6 +317,7 @@ func testAccCheckIBMDatabaseInstanceMongoDBEnterpriseGroupBasic(databaseResource location = "%[3]s" adminpassword = "password12345678" tags = ["one:two"] + service_endpoints = "public" group { group_id = "member" @@ -365,6 +367,7 @@ func testAccCheckIBMDatabaseInstanceMongoDBEnterpriseMinimal(databaseResourceGro service = "databases-for-mongodb" plan = "enterprise" location = "%[3]s" + service_endpoints = "public" group { group_id = "member" @@ -401,6 +404,7 @@ func testAccCheckIBMDatabaseInstanceMongoDBEnterpriseMinimal_PITR(databaseResour point_in_time_recovery_deployment_id = ibm_database.%[2]s.id point_in_time_recovery_time = "" offline_restore = true + service_endpoints = "public" group { group_id = "member" diff --git a/ibm/service/database/resource_ibm_database_mongodb_sharding_test.go b/ibm/service/database/resource_ibm_database_mongodb_sharding_test.go index 42d8de0be0..7ccbd24a66 100644 --- a/ibm/service/database/resource_ibm_database_mongodb_sharding_test.go +++ b/ibm/service/database/resource_ibm_database_mongodb_sharding_test.go @@ -95,6 +95,7 @@ func testAccCheckIBMDatabaseInstanceMongoDBShardingBasic(databaseResourceGroup s allocation_mb = 20480 } } + service_endpoints = "public" users { name = "user123" password = "password12345678" @@ -135,6 +136,7 @@ func testAccCheckIBMDatabaseInstanceMongoDBShardingFullyspecified(databaseResour allocation_mb = 40960 } } + service_endpoints = "public" users { name = "user123" password = "password12345678" diff --git a/ibm/service/database/resource_ibm_database_mongodb_test.go b/ibm/service/database/resource_ibm_database_mongodb_test.go index d753670559..70c43725bb 100644 --- a/ibm/service/database/resource_ibm_database_mongodb_test.go +++ b/ibm/service/database/resource_ibm_database_mongodb_test.go @@ -127,6 +127,7 @@ func testAccCheckIBMDatabaseInstanceMongodbBasic(databaseResourceGroup string, n plan = "standard" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public" group { group_id = "member" memory { @@ -164,6 +165,7 @@ func testAccCheckIBMDatabaseInstanceMongodbFullyspecified(databaseResourceGroup plan = "standard" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public" group { group_id = "member" memory { @@ -209,6 +211,7 @@ func testAccCheckIBMDatabaseInstanceMongodbReduced(databaseResourceGroup string, plan = "standard" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public" group { group_id = "member" memory { @@ -239,6 +242,7 @@ func testAccCheckIBMDatabaseInstanceMongodbImport(databaseResourceGroup string, service = "databases-for-mongodb" plan = "standard" location = "%[3]s" + service_endpoints = "public" } `, databaseResourceGroup, name, acc.Region()) diff --git a/ibm/service/database/resource_ibm_database_mysql_test.go b/ibm/service/database/resource_ibm_database_mysql_test.go index 7a10a1c06c..301ca3570c 100644 --- a/ibm/service/database/resource_ibm_database_mysql_test.go +++ b/ibm/service/database/resource_ibm_database_mysql_test.go @@ -87,6 +87,7 @@ func testAccCheckIBMDatabaseInstanceMysqlBasic(databaseResourceGroup string, nam allocation_mb = 20480 } } + service_endpoints = "public" tags = ["one:two"] users { name = "user123" diff --git a/ibm/service/database/resource_ibm_database_postgresql_test.go b/ibm/service/database/resource_ibm_database_postgresql_test.go index f0ac0f50aa..8d7ce0890f 100644 --- a/ibm/service/database/resource_ibm_database_postgresql_test.go +++ b/ibm/service/database/resource_ibm_database_postgresql_test.go @@ -532,6 +532,7 @@ func testAccCheckIBMDatabaseInstancePostgresGroupBasic(databaseResourceGroup str id = "multitenant" } } + service_endpoints = "public" users { name = "user123" password = "password12345678" @@ -684,6 +685,7 @@ func testAccCheckIBMDatabaseInstancePostgresImport(databaseResourceGroup string, service = "databases-for-postgresql" plan = "standard" location = "%[3]s" + service_endpoints = "public-and-private" } `, databaseResourceGroup, name, acc.Region()) } @@ -701,6 +703,7 @@ func testAccCheckIBMDatabaseInstancePostgresMinimal(databaseResourceGroup string service = "databases-for-postgresql" plan = "standard" location = "%[3]s" + service_endpoints = "public-and-private" } `, databaseResourceGroup, name, acc.Region()) } @@ -718,6 +721,7 @@ func testAccCheckIBMDatabaseInstancePostgresMinimal_PITR(databaseResourceGroup s service = "databases-for-postgresql" plan = "standard" location = "%[3]s" + service_endpoints = "public-and-private" } resource "ibm_database" "%[2]s-pitr" { @@ -728,6 +732,7 @@ func testAccCheckIBMDatabaseInstancePostgresMinimal_PITR(databaseResourceGroup s location = "%[3]s" point_in_time_recovery_deployment_id = ibm_database.%[2]s.id point_in_time_recovery_time = "" + service_endpoints = "public-and-private" } `, databaseResourceGroup, name, acc.Region()) } diff --git a/ibm/service/database/resource_ibm_database_rabbitmq_test.go b/ibm/service/database/resource_ibm_database_rabbitmq_test.go index 0a5ca0befa..1ac4e88cca 100644 --- a/ibm/service/database/resource_ibm_database_rabbitmq_test.go +++ b/ibm/service/database/resource_ibm_database_rabbitmq_test.go @@ -130,6 +130,7 @@ func testAccCheckIBMDatabaseInstanceRabbitmqBasic(databaseResourceGroup string, plan = "standard" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public" group { group_id = "member" memory { @@ -173,6 +174,7 @@ func testAccCheckIBMDatabaseInstanceRabbitmqFullyspecified(databaseResourceGroup plan = "standard" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public" group { group_id = "member" memory { @@ -220,6 +222,7 @@ func testAccCheckIBMDatabaseInstanceRabbitmqReduced(databaseResourceGroup string plan = "standard" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public" group { group_id = "member" memory { @@ -249,6 +252,7 @@ func testAccCheckIBMDatabaseInstanceRabbitmqImport(databaseResourceGroup string, service = "messages-for-rabbitmq" plan = "standard" location = "%[3]s" + service_endpoints = "public" } `, databaseResourceGroup, name, acc.Region()) } diff --git a/ibm/service/database/resource_ibm_database_redis_test.go b/ibm/service/database/resource_ibm_database_redis_test.go index 47ffa86081..26307c74d9 100644 --- a/ibm/service/database/resource_ibm_database_redis_test.go +++ b/ibm/service/database/resource_ibm_database_redis_test.go @@ -165,6 +165,7 @@ func testAccCheckIBMDatabaseInstanceRedisBasic(databaseResourceGroup string, nam plan = "standard" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public" group { group_id = "member" memory { @@ -208,6 +209,7 @@ func testAccCheckIBMDatabaseInstanceRedisFullyspecified(databaseResourceGroup st plan = "standard" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public" group { group_id = "member" memory { @@ -246,6 +248,7 @@ func testAccCheckIBMDatabaseInstanceRedisReduced(databaseResourceGroup string, n plan = "standard" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public" group { group_id = "member" memory { @@ -275,6 +278,7 @@ func testAccCheckIBMDatabaseInstanceRedisUserRole(databaseResourceGroup string, plan = "standard" location = "%[3]s" adminpassword = "password12345678" + service_endpoints = "public" group { group_id = "member" @@ -312,6 +316,7 @@ func testAccCheckIBMDatabaseInstanceRedisImport(databaseResourceGroup string, na service = "databases-for-redis" plan = "standard" location = "%[3]s" + service_endpoints = "public" auto_scaling { disk { capacity_enabled = true @@ -368,6 +373,7 @@ func testAccCheckIBMDatabaseInstanceRedisKPEncrypt(databaseResourceGroup string, key_protect_instance = ibm_resource_instance.kp_instance.guid key_protect_key = ibm_kp_key.test.id backup_encryption_key_crn = ibm_kp_key.test1.id + service_endpoints = "public" timeouts { create = "480m" update = "480m" diff --git a/ibm/service/database/resource_ibm_database_test.go b/ibm/service/database/resource_ibm_database_test.go index 81090ce690..d4d5ab9c46 100644 --- a/ibm/service/database/resource_ibm_database_test.go +++ b/ibm/service/database/resource_ibm_database_test.go @@ -212,3 +212,20 @@ func TestAppendSwitchoverWarning(t *testing.T) { t.Errorf("expected summary %v, got %v", warningNote, diags[0].Summary) } } + +func TestPublicServiceEndpointsWarning(t *testing.T) { + diags := publicServiceEndpointsWarning() + warningNote := "IBM recommends using private endpoints only to improve security by restricting access to your database to the IBM Cloud private network. For more information, please refer to our security best practices, https://cloud.ibm.com/docs/cloud-databases?topic=cloud-databases-manage-security-compliance." + + if len(diags) != 1 { + t.Fatalf("expected 1 diagnostic, got %d", len(diags)) + } + + if diags[0].Severity != diag.Warning { + t.Errorf("expected severity %v, got %v", diag.Warning, diags[0].Severity) + } + + if diags[0].Summary != warningNote { + t.Errorf("expected summary %v, got %v", warningNote, diags[0].Summary) + } +} diff --git a/ibm/service/eventnotification/data_source_ibm_en_destination_cf.go b/ibm/service/eventnotification/data_source_ibm_en_destination_cf.go index cda70209db..7f96913681 100644 --- a/ibm/service/eventnotification/data_source_ibm_en_destination_cf.go +++ b/ibm/service/eventnotification/data_source_ibm_en_destination_cf.go @@ -96,7 +96,7 @@ func DataSourceIBMEnCFDestination() *schema.Resource { }, }, }, - DeprecationMessage: "The IBM Cloud Function destination has been deprectated", + DeprecationMessage: "datasource is depreacted due to cloud function servie depreaction", } } diff --git a/ibm/service/eventnotification/data_source_ibm_en_destination_slack.go b/ibm/service/eventnotification/data_source_ibm_en_destination_slack.go index faaedcc8b2..8ea1b7ba7e 100644 --- a/ibm/service/eventnotification/data_source_ibm_en_destination_slack.go +++ b/ibm/service/eventnotification/data_source_ibm_en_destination_slack.go @@ -66,6 +66,16 @@ func DataSourceIBMEnSlackDestination() *schema.Resource { Computed: true, Description: "Slack webhook url", }, + "type": { + Type: schema.TypeString, + Computed: true, + Description: "The Slack Destination type incoming_webhook/direct_message", + }, + "token": { + Type: schema.TypeString, + Computed: true, + Description: "Slack Bot token. Required in case of type is direct_message", + }, }, }, }, @@ -184,5 +194,13 @@ func enSlackDestinationConfigParamsToMap(paramsItem en.DestinationConfigOneOfInt if params.URL != nil { paramsMap["url"] = params.URL } + + if params.Type != nil { + paramsMap["type"] = params.Type + } + + if params.Token != nil { + paramsMap["token"] = params.Token + } return paramsMap } diff --git a/ibm/service/eventnotification/data_source_ibm_en_destination_slack_test.go b/ibm/service/eventnotification/data_source_ibm_en_destination_slack_test.go index c759511bde..68b74da139 100644 --- a/ibm/service/eventnotification/data_source_ibm_en_destination_slack_test.go +++ b/ibm/service/eventnotification/data_source_ibm_en_destination_slack_test.go @@ -54,6 +54,7 @@ func testAccCheckIBMEnSlackDestinationDataSourceConfigBasic(instanceName, name, description = "%s" config { params { + type = "incoming_webhook" url = "https://hooks.slack.com/services/G0gyhsush/TYodsjhs/GHTbfidsimkk" } } diff --git a/ibm/service/eventnotification/data_source_ibm_en_slack_subscription.go b/ibm/service/eventnotification/data_source_ibm_en_slack_subscription.go index 33ca714ace..1d30d62d93 100644 --- a/ibm/service/eventnotification/data_source_ibm_en_slack_subscription.go +++ b/ibm/service/eventnotification/data_source_ibm_en_slack_subscription.go @@ -59,6 +59,20 @@ func DataSourceIBMEnSlackSubscription() *schema.Resource { Optional: true, Description: "attachment color code", }, + "channels": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "List of channels.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "channel id.", + }, + }, + }, + }, }, }, }, @@ -137,5 +151,23 @@ func enSlackSubscriptionToMap(attributeItem *en.SubscriptionAttributes) (attribu attributeMap["attachment_color"] = attributeItem.AttachmentColor } + if attributeItem.Channels != nil { + channels := []map[string]interface{}{} + for _, channelsItem := range attributeItem.Channels { + channelsItemMap, err := dataSourceIBMEnSubscriptionChannelCreateAttributesToMap(&channelsItem) + if err != nil { + return attributeMap + } + channels = append(channels, channelsItemMap) + } + attributeMap["channels"] = channels + } + return attributeMap } + +func dataSourceIBMEnSubscriptionChannelCreateAttributesToMap(model *en.ChannelCreateAttributes) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + modelMap["id"] = model.ID + return modelMap, nil +} diff --git a/ibm/service/eventnotification/data_source_ibm_en_slack_subscription_test.go b/ibm/service/eventnotification/data_source_ibm_en_slack_subscription_test.go index 391665174f..973db6aab1 100644 --- a/ibm/service/eventnotification/data_source_ibm_en_slack_subscription_test.go +++ b/ibm/service/eventnotification/data_source_ibm_en_slack_subscription_test.go @@ -64,7 +64,8 @@ func testAccCheckIBMEnSlackSubscriptionDataSourceConfig(instanceName, name, desc description = "tf_destinatios_description_0364" config { params { - url = "https://hooks.slack.com/services/G0gyhsush/TYodsjhs/GHTbfidsimkk" + type = "direct_message" + token = "dsgdewgfpwfgpewweeffewsgcvsaksdksff" } } } @@ -76,7 +77,10 @@ func testAccCheckIBMEnSlackSubscriptionDataSourceConfig(instanceName, name, desc topic_id = ibm_en_topic.en_topic_resource_4.topic_id destination_id = ibm_en_destination_slack.en_destination_resource_4.destination_id attributes { - attachment_color = "#0000FF" + channels { + id = "GFDRTUIIOBVD" + } + } } diff --git a/ibm/service/eventnotification/resource_ibm_en_destination_slack.go b/ibm/service/eventnotification/resource_ibm_en_destination_slack.go index 49fb2ba4ef..4e6b5c87ca 100644 --- a/ibm/service/eventnotification/resource_ibm_en_destination_slack.go +++ b/ibm/service/eventnotification/resource_ibm_en_destination_slack.go @@ -65,9 +65,19 @@ func ResourceIBMEnSlackDestination() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "url": { + Type: schema.TypeString, + Optional: true, + Description: "Slack webhook url. Required in case of type is incoming_webhook", + }, + "type": { Type: schema.TypeString, Required: true, - Description: "Slack webhook url.", + Description: "The Slack Destination type incoming_webhook/direct_message", + }, + "token": { + Type: schema.TypeString, + Optional: true, + Description: "Slack Bot token. Required in case of type is direct_message", }, }, }, @@ -182,7 +192,7 @@ func resourceIBMEnSlackDestinationRead(context context.Context, d *schema.Resour } if result.Config != nil { - err = d.Set("config", enWebhookDestinationFlattenConfig(*result.Config)) + err = d.Set("config", enSlackDestinationFlattenConfig(*result.Config)) if err != nil { return diag.FromErr(fmt.Errorf("[ERROR] Error setting config %s", err)) } @@ -279,8 +289,28 @@ func resourceIBMEnSlackDestinationDelete(context context.Context, d *schema.Reso func SlackdestinationConfigMapToDestinationConfig(configParams map[string]interface{}, destinationtype string) en.DestinationConfig { params := new(en.DestinationConfigOneOf) - if configParams["url"] != nil { - params.URL = core.StringPtr(configParams["url"].(string)) + + params.Type = core.StringPtr(configParams["type"].(string)) + + if *params.Type == "incoming_webhook" { + + if configParams["url"] != nil { + params.URL = core.StringPtr(configParams["url"].(string)) + } + + if configParams["type"] != nil { + params.Type = core.StringPtr(configParams["type"].(string)) + } + + } else { + + if configParams["token"] != nil { + params.Token = core.StringPtr(configParams["token"].(string)) + } + + if configParams["type"] != nil { + params.Type = core.StringPtr(configParams["type"].(string)) + } } destinationConfig := new(en.DestinationConfig) diff --git a/ibm/service/eventnotification/resource_ibm_en_destination_slack_test.go b/ibm/service/eventnotification/resource_ibm_en_destination_slack_test.go index 4ca12d7483..8cf00610f2 100644 --- a/ibm/service/eventnotification/resource_ibm_en_destination_slack_test.go +++ b/ibm/service/eventnotification/resource_ibm_en_destination_slack_test.go @@ -75,6 +75,7 @@ func testAccCheckIBMEnSlackDestinationConfig(instanceName, name, description str description = "%s" config { params { + type = "incoming_webhook" url = "https://hooks.slack.com/services/G0gyhsush/TYodsjhs/GHTbfidsimkk" } } diff --git a/ibm/service/eventnotification/resource_ibm_en_subscription_slack.go b/ibm/service/eventnotification/resource_ibm_en_subscription_slack.go index dfed133ac0..52e6fe7703 100644 --- a/ibm/service/eventnotification/resource_ibm_en_subscription_slack.go +++ b/ibm/service/eventnotification/resource_ibm_en_subscription_slack.go @@ -69,6 +69,25 @@ func ResourceIBMEnSlackSubscription() *schema.Resource { Optional: true, Description: "The templete id for notification", }, + "channels": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "List of channels.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "channel id.", + }, + "operation": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "The channel operation type. The values are add/remove", + }, + }, + }, + }, }, }, }, @@ -235,7 +254,10 @@ func resourceIBMEnSlackSubscriptionUpdate(context context.Context, d *schema.Res options.SetDescription(d.Get("description").(string)) } - _, attributes := slackattributesMapToAttributes(d.Get("attributes.0").(map[string]interface{})) + attributes, err := resourceIBMEnSubscriptionMapToSubscriptionUpdateAttributes(d.Get("attributes.0").(map[string]interface{})) + if err != nil { + return diag.FromErr(err) + } options.SetAttributes(&attributes) _, response, err := enClient.UpdateSubscriptionWithContext(context, options) @@ -279,19 +301,72 @@ func resourceIBMEnSlackSubscriptionDelete(context context.Context, d *schema.Res return nil } -func slackattributesMapToAttributes(attributeMap map[string]interface{}) (en.SubscriptionCreateAttributes, en.SubscriptionUpdateAttributesSlackAttributes) { - attributesCreate := en.SubscriptionCreateAttributes{} - attributesUpdate := en.SubscriptionUpdateAttributesSlackAttributes{} +func slackattributesMapToAttributes(modelMap map[string]interface{}) (en.SubscriptionCreateAttributes, error) { + model := en.SubscriptionCreateAttributes{} + + if modelMap["template_id_notification"] != nil && modelMap["template_id_notification"].(string) != "" { + model.TemplateIDNotification = core.StringPtr(modelMap["template_id_notification"].(string)) + } + if modelMap["template_id_invitation"] != nil && modelMap["template_id_invitation"].(string) != "" { + model.TemplateIDInvitation = core.StringPtr(modelMap["template_id_invitation"].(string)) + } + + if modelMap["attachment_color"] != nil && modelMap["attachment_color"].(string) != "" { + model.AttachmentColor = core.StringPtr(modelMap["attachment_color"].(string)) + } + if modelMap["channels"] != nil { + channels := []en.ChannelCreateAttributes{} + for _, channelsItem := range modelMap["channels"].([]interface{}) { + channelsItemModel, err := resourceIBMEnSubscriptionMapToChannelCreateAttributes(channelsItem.(map[string]interface{})) + if err != nil { + return model, err + } + channels = append(channels, *channelsItemModel) + } + model.Channels = channels + } + return model, nil +} + +func resourceIBMEnSubscriptionMapToChannelCreateAttributes(modelMap map[string]interface{}) (*en.ChannelCreateAttributes, error) { + model := &en.ChannelCreateAttributes{} + model.ID = core.StringPtr(modelMap["id"].(string)) + return model, nil +} + +func resourceIBMEnSubscriptionMapToSubscriptionUpdateAttributes(modelMap map[string]interface{}) (en.SubscriptionUpdateAttributes, error) { + model := en.SubscriptionUpdateAttributes{} - if attributeMap["attachment_color"] != nil { - attributesCreate.AttachmentColor = core.StringPtr(attributeMap["attachment_color"].(string)) - attributesUpdate.AttachmentColor = core.StringPtr(attributeMap["attachment_color"].(string)) + if modelMap["template_id_notification"] != nil && modelMap["template_id_notification"].(string) != "" { + model.TemplateIDNotification = core.StringPtr(modelMap["template_id_notification"].(string)) } - if attributeMap["template_id_notification"] != nil { - attributesCreate.TemplateIDNotification = core.StringPtr(attributeMap["template_id_notification"].(string)) - attributesUpdate.TemplateIDNotification = core.StringPtr(attributeMap["template_id_notification"].(string)) + if modelMap["attachment_color"] != nil && modelMap["attachment_color"].(string) != "" { + model.AttachmentColor = core.StringPtr(modelMap["attachment_color"].(string)) } + if modelMap["channels"] != nil { + channels := []en.ChannelUpdateAttributes{} + for _, channelsItem := range modelMap["channels"].([]interface{}) { + channelsItemModel, err := resourceIBMEnSubscriptionMapToChannelUpdateAttributes(channelsItem.(map[string]interface{})) + if err != nil { + return model, err + } + channels = append(channels, *channelsItemModel) + } + model.Channels = channels + } + return model, nil +} + +func resourceIBMEnSubscriptionChannelCreateAttributesToMap(model *en.ChannelCreateAttributes) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + modelMap["id"] = model.ID + return modelMap, nil +} - return attributesCreate, attributesUpdate +func resourceIBMEnSubscriptionMapToChannelUpdateAttributes(modelMap map[string]interface{}) (*en.ChannelUpdateAttributes, error) { + model := &en.ChannelUpdateAttributes{} + model.ID = core.StringPtr(modelMap["id"].(string)) + model.Operation = core.StringPtr(modelMap["operation"].(string)) + return model, nil } diff --git a/ibm/service/eventnotification/resource_ibm_en_subscription_slack_test.go b/ibm/service/eventnotification/resource_ibm_en_subscription_slack_test.go index 56275ad5a5..6cb77dbf2b 100644 --- a/ibm/service/eventnotification/resource_ibm_en_subscription_slack_test.go +++ b/ibm/service/eventnotification/resource_ibm_en_subscription_slack_test.go @@ -85,7 +85,8 @@ func testAccCheckIBMEnSlackSubscriptionConfig(instanceName, name, description st description = "tf_destinatios_description_0364" config { params { - "url = "https://hooks.slack.com/services/G0gyhsush/TYodsjhs/GHTbfidsimkk"" + type = "incoming_webhook" + url = "https://hooks.slack.com/services/G0gyhsush/TYodsjhs/GHTbfidsimkk" } } } diff --git a/ibm/service/eventstreams/data_source_ibm_event_streams_schema.go b/ibm/service/eventstreams/data_source_ibm_event_streams_schema.go index efc9aa7f97..15f7075c15 100644 --- a/ibm/service/eventstreams/data_source_ibm_event_streams_schema.go +++ b/ibm/service/eventstreams/data_source_ibm_event_streams_schema.go @@ -9,6 +9,7 @@ import ( "log" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM/eventstreams-go-sdk/pkg/schemaregistryv1" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -41,14 +42,16 @@ func DataSourceIBMEventStreamsSchema() *schema.Resource { func dataSourceIBMEventStreamsSchemaRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { schemaregistryClient, err := meta.(conns.ClientSession).ESschemaRegistrySession() if err != nil { - log.Printf("[DEBUG] dataSourceIBMEventStreamsSchemaRead schemaregistryClient err %s", err) - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("dataSourceIBMEventStreamsSchemaRead schemaregistryClient: %s", err), "ibm_event_streams_schema", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } adminURL, instanceCRN, err := getInstanceURL(d, meta) if err != nil { - log.Printf("[DEBUG] dataSourceIBMEventStreamsSchemaRead getInstanceURL err %s", err) - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("dataSourceIBMEventStreamsSchemaRead getInstanceURL: %s", err), "ibm_event_streams_schema", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } schemaregistryClient.SetServiceURL(adminURL) @@ -59,8 +62,9 @@ func dataSourceIBMEventStreamsSchemaRead(context context.Context, d *schema.Reso schema, response, err := schemaregistryClient.GetLatestSchemaWithContext(context, getLatestSchemaOptions) if err != nil || schema == nil { - log.Printf("[DEBUG] GetLatestSchemaWithContext failed with error: %s and response:\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetLatestSchemaWithContext failed with error: %s\n and response:%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("dataSourceIBMEventStreamsSchemaRead GetLatestSchemaWithContext failed with error: %s and response:\n%s", err, response), "ibm_event_streams_schema", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } uniqueID := getUniqueSchemaID(instanceCRN, schemaID) diff --git a/ibm/service/eventstreams/data_source_ibm_event_streams_topic.go b/ibm/service/eventstreams/data_source_ibm_event_streams_topic.go index a12133a9da..f588337a4b 100644 --- a/ibm/service/eventstreams/data_source_ibm_event_streams_topic.go +++ b/ibm/service/eventstreams/data_source_ibm_event_streams_topic.go @@ -8,6 +8,7 @@ import ( "fmt" "log" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) @@ -54,13 +55,15 @@ func DataSourceIBMEventStreamsTopic() *schema.Resource { func dataSourceIBMEventStreamsTopicRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { adminClient, instanceCRN, err := createSaramaAdminClient(d, meta) if err != nil { - log.Printf("[DEBUG]dataSourceIBMEventStreamsTopicRead createSaramaAdminClient err %s", err) - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("dataSourceIBMEventStreamsTopicRead createSaramaAdminClient: %s", err), "ibm_event_streams_topic", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } topics, err := adminClient.ListTopics() if err != nil { - log.Printf("[DEBUG]dataSourceIBMEventStreamsTopicRead ListTopics err %s", err) - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("dataSourceIBMEventStreamsTopicRead ListTopics: %s", err), "ibm_event_streams_topic", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } topicName := d.Get("name").(string) for name := range topics { @@ -72,6 +75,8 @@ func dataSourceIBMEventStreamsTopicRead(context context.Context, d *schema.Resou return nil } } - log.Printf("[DEBUG]dataSourceIBMEventStreamsTopicRead topic %s does not exist", topicName) - return diag.FromErr(fmt.Errorf("topic %s does not exist", topicName)) + tfErr := flex.TerraformErrorf(fmt.Errorf("topic %s does not exist", topicName), + fmt.Sprintf("dataSourceIBMEventStreamsTopicRead topic %s does not exist", topicName), "ibm_event_streams_topic", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } diff --git a/ibm/service/eventstreams/resource_ibm_event_streams_schema.go b/ibm/service/eventstreams/resource_ibm_event_streams_schema.go index bc4a0d7125..63a4ccd37c 100644 --- a/ibm/service/eventstreams/resource_ibm_event_streams_schema.go +++ b/ibm/service/eventstreams/resource_ibm_event_streams_schema.go @@ -175,11 +175,15 @@ func validateName(s map[string]interface{}, t string) error { func resourceIBMEventStreamsSchemaCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { schemaregistryClient, err := meta.(conns.ClientSession).ESschemaRegistrySession() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("resourceIBMEventStreamsSchemaCreate schemaregistryClient: %s", err), "ibm_event_streams_schema", "create") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } adminURL, instanceCRN, err := getInstanceURL(d, meta) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("resourceIBMEventStreamsSchemaCreate getInstanceURL: %s", err), "ibm_event_streams_schema", "create") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } schemaregistryClient.SetServiceURL(adminURL) createSchemaOptions := &schemaregistryv1.CreateSchemaOptions{} @@ -195,8 +199,9 @@ func resourceIBMEventStreamsSchemaCreate(context context.Context, d *schema.Reso schemaMetadata, response, err := schemaregistryClient.CreateSchemaWithContext(context, createSchemaOptions) if err != nil || schemaMetadata == nil { - log.Printf("[DEBUG] CreateSchemaWithContext failed with error: %s and response: \n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateSchemaWithContext failed with eror: %s and response: \n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("resourceIBMEventStreamsSchemaCreate CreateSchemaWithContext failed with error: %s and response:\n%s", err, response), "ibm_event_streams_schema", "create") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } uniqueID := getUniqueSchemaID(instanceCRN, *schemaMetadata.ID) d.SetId(uniqueID) @@ -207,12 +212,16 @@ func resourceIBMEventStreamsSchemaCreate(context context.Context, d *schema.Reso func resourceIBMEventStreamsSchemaRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { schemaregistryClient, err := meta.(conns.ClientSession).ESschemaRegistrySession() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("resourceIBMEventStreamsSchemaRead schemaregistryClient: %s", err), "ibm_event_streams_schema", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } adminURL, instanceCRN, err := getInstanceURL(d, meta) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("resourceIBMEventStreamsSchemaRead getInstanceURL: %s", err), "ibm_event_streams_schema", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } schemaregistryClient.SetServiceURL(adminURL) @@ -223,21 +232,27 @@ func resourceIBMEventStreamsSchemaRead(context context.Context, d *schema.Resour avroSchema, response, err := schemaregistryClient.GetLatestSchemaWithContext(context, getSchemaOptions) if err != nil || avroSchema == nil { - log.Printf("[DEBUG] GetSchemaWithContext failed with error: %s and response: \n%s", err, response) if response != nil && response.StatusCode == 404 { + log.Printf("[DEBUG] GetSchemaWithContext failed with 404 Not Found error and response: \n%s", response) d.SetId("") return nil } - return diag.FromErr(fmt.Errorf("GetSchemaWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("resourceIBMEventStreamsSchemaRead GetLatestSchemaWithContext failed with error: %s and response:\n%s", err, response), "ibm_event_streams_schema", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } s, err := json.Marshal(avroSchema) if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error marshalling the created schema: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("resourceIBMEventStreamsSchemaRead marshalling the schema failed with error: %s", err), "ibm_event_streams_schema", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } if err = d.Set("schema", string(s)); err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error setting the schema: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("resourceIBMEventStreamsSchemaRead setting the schema failed error: %s", err), "ibm_event_streams_schema", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } d.Set("resource_instance_id", instanceCRN) d.Set("schema_id", schemaID) @@ -248,12 +263,16 @@ func resourceIBMEventStreamsSchemaRead(context context.Context, d *schema.Resour func resourceIBMEventStreamsSchemaUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { schemaregistryClient, err := meta.(conns.ClientSession).ESschemaRegistrySession() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("resourceIBMEventStreamsSchemaUpdate schemaregistryClient: %s", err), "ibm_event_streams_schema", "update") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } adminURL, _, err := getInstanceURL(d, meta) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("resourceIBMEventStreamsSchemaUpdate getInstanceURL: %s", err), "ibm_event_streams_schema", "update") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } schemaregistryClient.SetServiceURL(adminURL) @@ -269,8 +288,9 @@ func resourceIBMEventStreamsSchemaUpdate(context context.Context, d *schema.Reso } schemaMetadata, response, err := schemaregistryClient.UpdateSchemaWithContext(context, updateSchemaOptions) if err != nil || schemaMetadata == nil { - log.Printf("[DEBUG] UpdateSchemaWithContext failed with error: %s\n and response: %s", err, response) - return diag.FromErr(fmt.Errorf("UpdateSchemaWithContext failed with error: %s and response: \n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("resourceIBMEventStreamsSchemaUpdate UpdateSchema failed with error: %s and response:\n%s", err, response), "ibm_event_streams_schema", "update") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } } @@ -280,12 +300,16 @@ func resourceIBMEventStreamsSchemaUpdate(context context.Context, d *schema.Reso func resourceIBMEventStreamsSchemaDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { schemaregistryClient, err := meta.(conns.ClientSession).ESschemaRegistrySession() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("resourceIBMEventStreamsSchemaDelete schemaregistryClient: %s", err), "ibm_event_streams_schema", "delete") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } adminURL, _, err := getInstanceURL(d, meta) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("resourceIBMEventStreamsSchemaDelete getInstanceURL: %s", err), "ibm_event_streams_schema", "delete") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } schemaregistryClient.SetServiceURL(adminURL) @@ -300,13 +324,16 @@ func resourceIBMEventStreamsSchemaDelete(context context.Context, d *schema.Reso // set schema state to disabled before deleting response, err := schemaregistryClient.SetSchemaStateWithContext(context, setSchemaOptions) if err != nil { - log.Printf("[DEBUG] SetSchemaStateWithContext failed %s\n%s", err, response) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("resourceIBMEventStreamsSchemaDelete SetSchemaState failed with error: %s and response:\n%s", err, response), "ibm_event_streams_schema", "delete") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } response, err = schemaregistryClient.DeleteSchemaWithContext(context, deleteSchemaOptions) if err != nil { - log.Printf("[DEBUG] DeleteSchemaWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("DeleteSchemaWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("resourceIBMEventStreamsSchemaDelete DeleteSchema failed with error: %s and response:\n%s", err, response), "ibm_event_streams_schema", "delete") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } d.SetId("") diff --git a/ibm/service/eventstreams/resource_ibm_event_streams_topic.go b/ibm/service/eventstreams/resource_ibm_event_streams_topic.go index bc59c8f770..5b001533c9 100644 --- a/ibm/service/eventstreams/resource_ibm_event_streams_topic.go +++ b/ibm/service/eventstreams/resource_ibm_event_streams_topic.go @@ -127,8 +127,9 @@ func resourceIBMEventStreamsTopicCreate(context context.Context, d *schema.Resou log.Printf("[DEBUG] resourceIBMEventStreamsTopicCreate") adminClient, instanceCRN, err := createSaramaAdminClient(d, meta) if err != nil { - log.Printf("[DEBUG] resourceIBMEventStreamsTopicCreate createSaramaAdminClient err %s", err) - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("resourceIBMEventStreamsTopicCreate createSaramaAdminClient: %s", err), "ibm_event_streams_topic", "create") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } topicName := d.Get("name").(string) partitions := d.Get("partitions").(int) @@ -144,8 +145,9 @@ func resourceIBMEventStreamsTopicCreate(context context.Context, d *schema.Resou if kafkaErr != nil && kafkaErr.Err == sarama.ErrTopicAlreadyExists { exists, err := resourceIBMEventStreamsTopicExists(context, d, meta) if err != nil { - log.Printf("[DEBUG] resourceIBMEventStreamsTopicCreate resourceIBMEventStreamsTopicExists: %s, err %s", topicName, err) - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("resourceIBMEventStreamsTopicCreate resourceIBMEventStreamsTopicExists %s: %s", topicName, err), "ibm_event_streams_topic", "create") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } if exists { d.SetId(getTopicID(instanceCRN, topicName)) @@ -153,8 +155,9 @@ func resourceIBMEventStreamsTopicCreate(context context.Context, d *schema.Resou } } } - log.Printf("[ERROR] resourceIBMEventStreamsTopicCreate CreateTopic: %s, err %s", topicName, err) - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("resourceIBMEventStreamsTopicCreate CreateTopic %s: %s", topicName, err), "ibm_event_streams_topic", "create") + log.Printf("[ERROR]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } log.Printf("[INFO] resourceIBMEventStreamsTopicCreate CreateTopic: topic is %s, detail is %v", topicName, topicDetail) d.SetId(getTopicID(instanceCRN, topicName)) @@ -165,15 +168,17 @@ func resourceIBMEventStreamsTopicRead(context context.Context, d *schema.Resourc log.Printf("[DEBUG] resourceIBMEventStreamsTopicRead") adminClient, instanceCRN, err := createSaramaAdminClient(d, meta) if err != nil { - log.Printf("[DEBUG] resourceIBMEventStreamsTopicRead createSaramaAdminClient err %s", err) - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("resourceIBMEventStreamsTopicRead createSaramaAdminClient: %s", err), "ibm_event_streams_topic", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } topicID := d.Id() topicName := getTopicName(topicID) topics, err := adminClient.ListTopics() if err != nil { - log.Printf("[DEBUG] resourceIBMEventStreamsTopicRead ListTopics err %s", err) - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("resourceIBMEventStreamsTopicRead ListTopics: %s", err), "ibm_event_streams_topic", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } for name, detail := range topics { if name == topicName { @@ -201,8 +206,9 @@ func resourceIBMEventStreamsTopicUpdate(context context.Context, d *schema.Resou log.Printf("[DEBUG] resourceIBMEventStreamsTopicUpdate") adminClient, _, err := createSaramaAdminClient(d, meta) if err != nil { - log.Printf("[DEBUG] resourceIBMEventStreamsTopicUpdate createSaramaAdminClient err %s", err) - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("resourceIBMEventStreamsTopicUpdate createSaramaAdminClient: %s", err), "ibm_event_streams_topic", "update") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } topicName := d.Get("name").(string) if d.HasChange("partitions") { @@ -212,8 +218,9 @@ func resourceIBMEventStreamsTopicUpdate(context context.Context, d *schema.Resou log.Printf("[INFO]resourceIBMEventStreamsTopicUpdate Updating partitions from %d to %d", oldPartitions, newPartitions) err = adminClient.CreatePartitions(topicName, int32(newPartitions), nil, false) if err != nil { - log.Printf("[DEBUG]resourceIBMEventStreamsTopicUpdate CreatePartitions err %s", err) - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("resourceIBMEventStreamsTopicUpdate CreatePartitions: %s", err), "ibm_event_streams_topic", "update") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } d.Set("partitions", int32(newPartitions)) log.Printf("[INFO]resourceIBMEventStreamsTopicUpdate partitions is set to %d", newPartitions) @@ -223,8 +230,9 @@ func resourceIBMEventStreamsTopicUpdate(context context.Context, d *schema.Resou configEntries := config2TopicDetail(config) err = adminClient.AlterConfig(sarama.TopicResource, topicName, configEntries, false) if err != nil { - log.Printf("[DEBUG]resourceIBMEventStreamsTopicUpdate AlterConfig err %s", err) - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("resourceIBMEventStreamsTopicUpdate AlterConfig: %s", err), "ibm_event_streams_topic", "update") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } d.Set("config", topicDetail2Config(configEntries)) log.Printf("[INFO]resourceIBMEventStreamsTopicUpdate config is set to %v", topicDetail2Config(configEntries)) @@ -236,8 +244,9 @@ func resourceIBMEventStreamsTopicDelete(context context.Context, d *schema.Resou log.Printf("[DEBUG] resourceIBMEventStreamsTopicDelete") adminClient, _, err := createSaramaAdminClient(d, meta) if err != nil { - log.Printf("[DEBUG] resourceIBMEventStreamsTopicDelete createSaramaAdminClient err %s", err) - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("resourceIBMEventStreamsTopicDelete createSaramaAdminClient: %s", err), "ibm_event_streams_topic", "delete") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } topicName := d.Get("name").(string) err = adminClient.DeleteTopic(topicName) @@ -249,8 +258,9 @@ func resourceIBMEventStreamsTopicDelete(context context.Context, d *schema.Resou return nil } } - log.Printf("[DEBUG] resourceIBMEventStreamsTopicDelete DeleteTopic err %s", err) - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("resourceIBMEventStreamsTopicDelete DeleteClient: %s", err), "ibm_event_streams_topic", "delete") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } d.SetId("") log.Printf("[INFO]resourceIBMEventStreamsTopicDelete topic %s deleted", topicName) diff --git a/ibm/service/globaltagging/resource_ibm_iam_access_tag.go b/ibm/service/globaltagging/resource_ibm_iam_access_tag.go new file mode 100644 index 0000000000..a1844c8fc3 --- /dev/null +++ b/ibm/service/globaltagging/resource_ibm_iam_access_tag.go @@ -0,0 +1,173 @@ +// Copyright IBM Corp. 2017, 2024 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package globaltagging + +import ( + "context" + "encoding/json" + "fmt" + "log" + + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" + "github.com/IBM/platform-services-go-sdk/globaltaggingv1" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func ResourceIBMIamAccessTag() *schema.Resource { + return &schema.Resource{ + CreateContext: resourceIBMIamAccessTagCreate, + ReadContext: resourceIBMIamAccessTagRead, + DeleteContext: resourceIBMIamAccessTagDelete, + Importer: &schema.ResourceImporter{}, + + Schema: map[string]*schema.Schema{ + + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validate.InvokeValidator("ibm_iam_access_tag", "name"), + Set: flex.ResourceIBMVPCHash, + Description: "Name of the access tag", + }, + tagType: { + Type: schema.TypeString, + Computed: true, + Description: "Type of the tag(access)", + }, + }, + } +} + +func ResourceIBMIamAccessTagValidator() *validate.ResourceValidator { + + validateSchema := make([]validate.ValidateSchema, 0) + + validateSchema = append(validateSchema, + validate.ValidateSchema{ + Identifier: "name", + ValidateFunctionIdentifier: validate.ValidateRegexpLen, + Type: validate.TypeString, + Required: true, + Regexp: `^([A-Za-z0-9_.-]|[A-Za-z0-9_.-][A-Za-z0-9_ .-]*[A-Za-z0-9_.-]):([A-Za-z0-9_.-]|[A-Za-z0-9_.-][A-Za-z0-9_ .-]*[A-Za-z0-9_.-])$`, + MinValueLength: 1, + MaxValueLength: 128}) + + ibmIamAccessTagValidator := validate.ResourceValidator{ResourceName: "ibm_iam_access_tag", Schema: validateSchema} + return &ibmIamAccessTagValidator +} + +func resourceIBMIamAccessTagCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + + gtClient, err := meta.(conns.ClientSession).GlobalTaggingAPIv1() + if err != nil { + tfErr := flex.TerraformErrorf(err, err.Error(), "ibm_iam_access_tag", "create") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + tagName := d.Get("name").(string) + add := make([]string, 0) + add = append(add, tagName) + accessTagType := "access" + createTagOptions := &globaltaggingv1.CreateTagOptions{ + TagType: &accessTagType, + TagNames: add, + } + results, _, err := gtClient.CreateTagWithContext(context, createTagOptions) + if err != nil { + tfErr := flex.TerraformErrorf(err, err.Error(), "ibm_iam_access_tag", "create") + return tfErr.GetDiag() + } + if results != nil { + errMap := make([]globaltaggingv1.CreateTagResultsResultsItem, 0) + for _, res := range results.Results { + if res.IsError != nil && *res.IsError { + errMap = append(errMap, res) + } + } + if len(errMap) > 0 { + output, _ := json.MarshalIndent(errMap, "", " ") + return diag.FromErr(fmt.Errorf("Error while creating access tag(%s) : %s", tagName, string(output))) + } + } + + d.SetId(tagName) + d.Set(tagType, accessTagType) + + return nil +} + +func resourceIBMIamAccessTagRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + tagName := d.Id() + gtClient, err := meta.(conns.ClientSession).GlobalTaggingAPIv1() + if err != nil { + tfErr := flex.TerraformErrorf(err, err.Error(), "ibm_iam_access_tag", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + accessTagType := "access" + listTagsOptions := &globaltaggingv1.ListTagsOptions{ + TagType: &accessTagType, + } + taggingResult, _, err := gtClient.ListTagsWithContext(context, listTagsOptions) + if err != nil { + tfErr := flex.TerraformErrorf(err, err.Error(), "ibm_iam_access_tag", "read") + return tfErr.GetDiag() + } + + var taglist []string + for _, item := range taggingResult.Items { + taglist = append(taglist, *item.Name) + } + existingAccessTags := flex.NewStringSet(flex.ResourceIBMVPCHash, taglist) + if !existingAccessTags.Contains(tagName) { + d.SetId("") + return nil + } + d.Set("name", tagName) + d.Set(tagType, accessTagType) + return nil +} + +func resourceIBMIamAccessTagDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + + gtClient, err := meta.(conns.ClientSession).GlobalTaggingAPIv1() + if err != nil { + tfErr := flex.TerraformErrorf(err, err.Error(), "ibm_iam_access_tag", "update") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + tagName := d.Get("name").(string) + accessTagType := "access" + + deleteTagOptions := &globaltaggingv1.DeleteTagOptions{ + TagName: &tagName, + TagType: &accessTagType, + } + + results, resp, err := gtClient.DeleteTagWithContext(context, deleteTagOptions) + + if err != nil { + return diag.FromErr(fmt.Errorf("Error while deleting access tag calling api (%s) : %v\n%v", tagName, err, resp)) + } + if results != nil { + errMap := make([]globaltaggingv1.DeleteTagResultsItem, 0) + for _, res := range results.Results { + if res.IsError != nil && *res.IsError { + errMap = append(errMap, res) + } + } + if len(errMap) > 0 { + output, _ := json.MarshalIndent(errMap, "", " ") + return diag.FromErr(fmt.Errorf("Error while deleting access tag in results (%s) : %s", tagName, string(output))) + } + } + + d.SetId("") + return nil +} diff --git a/ibm/service/globaltagging/resource_ibm_iam_access_tag_test.go b/ibm/service/globaltagging/resource_ibm_iam_access_tag_test.go new file mode 100644 index 0000000000..e4a4f2362c --- /dev/null +++ b/ibm/service/globaltagging/resource_ibm_iam_access_tag_test.go @@ -0,0 +1,147 @@ +// Copyright IBM Corp. 2017, 2024 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package globaltagging_test + +import ( + "fmt" + "regexp" + "testing" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" + "github.com/IBM/platform-services-go-sdk/globaltaggingv1" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +const ( + iamAccessTagRegex = "^([A-Za-z0-9_.-]|[A-Za-z0-9_.-][A-Za-z0-9_ .-]*[A-Za-z0-9_.-]):([A-Za-z0-9_.-]|[A-Za-z0-9_.-][A-Za-z0-9_ .-]*[A-Za-z0-9_.-])$" +) + +func TestAccIamAccessTag_Basic(t *testing.T) { + name := fmt.Sprintf("tf%d:iam-access%d", acctest.RandIntRange(10, 100), acctest.RandIntRange(10, 100)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + + resource.TestStep{ + Config: testAccCheckIamAccessTagCreate(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIamAccessTagExists("ibm_iam_access_tag.tag"), + resource.TestCheckResourceAttr("ibm_iam_access_tag.tag", "id", name), + resource.TestCheckResourceAttr("ibm_iam_access_tag.tag", "name", name), + resource.TestCheckResourceAttr("ibm_iam_access_tag.tag", "tag_type", "access"), + ), + }, + }, + }) +} +func TestAccIamAccessTag_Usage(t *testing.T) { + name := fmt.Sprintf("tf%d:iam-access%d", acctest.RandIntRange(10, 100), acctest.RandIntRange(10, 100)) + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + + resource.TestStep{ + Config: testAccCheckIamAccessTagCreate(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIamAccessTagExists("ibm_iam_access_tag.tag"), + resource.TestCheckResourceAttr("ibm_iam_access_tag.tag", "id", name), + resource.TestCheckResourceAttr("ibm_iam_access_tag.tag", "name", name), + resource.TestCheckResourceAttr("ibm_iam_access_tag.tag", "tag_type", "access"), + ), + }, + resource.TestStep{ + Config: testAccCheckIamAccessTagUsage(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIamAccessTagExists("ibm_iam_access_tag.tag"), + resource.TestCheckResourceAttr("ibm_iam_access_tag.tag", "id", name), + resource.TestCheckResourceAttr("ibm_iam_access_tag.tag", "name", name), + resource.TestCheckResourceAttr("ibm_iam_access_tag.tag", "tag_type", "access"), + testAccCheckResourceTagExists("ibm_resource_tag.tag"), + resource.TestCheckResourceAttr("ibm_resource_tag.tag", "tags.#", "1"), + resource.TestCheckResourceAttr("ibm_resource_tag.tag", "tags.0", name), + resource.TestCheckResourceAttr("ibm_resource_tag.tag", "tag_type", "access"), + ), + }, + }, + }) +} + +func testAccCheckIamAccessTagExists(n string) resource.TestCheckFunc { + return func(s *terraform.State) error { + var tagName string + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + iamAccessTagRegex, err := regexp.Compile(iamAccessTagRegex) + if err != nil { + return err + } + + if iamAccessTagRegex.MatchString(rs.Primary.ID) { + tagName = rs.Primary.ID + } + + gtClient, err := acc.TestAccProvider.Meta().(conns.ClientSession).GlobalTaggingAPIv1() + if err != nil { + return fmt.Errorf("Error getting global tagging client settings: %s", err) + } + accessTagType := "access" + listTagsOptions := &globaltaggingv1.ListTagsOptions{ + TagType: &accessTagType, + } + taggingResult, _, err := gtClient.ListTags(listTagsOptions) + if err != nil { + return err + } + + var taglist []string + for _, item := range taggingResult.Items { + taglist = append(taglist, *item.Name) + } + existingAccessTags := flex.NewStringSet(flex.ResourceIBMVPCHash, taglist) + if !existingAccessTags.Contains(tagName) { + return fmt.Errorf( + "Error on get of resource tags (%s) : %s", tagName, err) + } + return nil + } +} + +func testAccCheckIamAccessTagCreate(name string) string { + return fmt.Sprintf(` + resource "ibm_iam_access_tag" "tag" { + name = "%s" + } +`, name) +} +func testAccCheckIamAccessTagUsage(name string) string { + resource_group_name := fmt.Sprintf("tf%d-iam-access%d", acctest.RandIntRange(10, 100), acctest.RandIntRange(10, 100)) + return fmt.Sprintf(` + data "ibm_resource_group" "group" { + name = "Default" + } + resource "ibm_iam_access_tag" "tag" { + name = "%s" + } + resource "ibm_cd_toolchain" "cd_toolchain_instance" { + description = "Terraform test" + name = "%s-toolchain" + resource_group_id = data.ibm_resource_group.group.id + } + resource "ibm_resource_tag" "tag" { + resource_id = ibm_cd_toolchain.cd_toolchain_instance.crn + tags = [ibm_iam_access_tag.tag.name] + tag_type = "access" + } +`, name, resource_group_name) +} diff --git a/ibm/service/globaltagging/resource_ibm_resource_access_tag.go b/ibm/service/globaltagging/resource_ibm_resource_access_tag.go index f4d1d5b9d2..ad5d3d39a1 100644 --- a/ibm/service/globaltagging/resource_ibm_resource_access_tag.go +++ b/ibm/service/globaltagging/resource_ibm_resource_access_tag.go @@ -38,6 +38,7 @@ func ResourceIBMResourceAccessTag() *schema.Resource { Description: "Type of the tag(access)", }, }, + DeprecationMessage: "ibm_resource_access_tag has been deprecated. Use ibm_iam_access_tag instead.", } } diff --git a/ibm/service/globaltagging/resource_ibm_resource_tag.go b/ibm/service/globaltagging/resource_ibm_resource_tag.go index 4db41d51b1..aa23bd1f73 100644 --- a/ibm/service/globaltagging/resource_ibm_resource_tag.go +++ b/ibm/service/globaltagging/resource_ibm_resource_tag.go @@ -5,6 +5,7 @@ package globaltagging import ( "context" + "encoding/json" "fmt" "log" "os" @@ -18,6 +19,7 @@ import ( "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" ) const ( @@ -32,11 +34,11 @@ const ( func ResourceIBMResourceTag() *schema.Resource { return &schema.Resource{ - Create: resourceIBMResourceTagCreate, - Read: resourceIBMResourceTagRead, - Update: resourceIBMResourceTagUpdate, - Delete: resourceIBMResourceTagDelete, - Importer: &schema.ResourceImporter{}, + CreateContext: resourceIBMResourceTagCreate, + ReadContext: resourceIBMResourceTagRead, + UpdateContext: resourceIBMResourceTagUpdate, + DeleteContext: resourceIBMResourceTagDelete, + Importer: &schema.ResourceImporter{}, CustomizeDiff: customdiff.Sequence( func(_ context.Context, diff *schema.ResourceDiff, v interface{}) error { @@ -125,19 +127,23 @@ func ResourceIBMResourceTagValidator() *validate.ResourceValidator { return &ibmResourceTagValidator } -func resourceIBMResourceTagCreate(d *schema.ResourceData, meta interface{}) error { +func resourceIBMResourceTagCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var rType, tType string resources := []globaltaggingv1.Resource{} userDetails, err := meta.(conns.ClientSession).BluemixUserDetails() if err != nil { - return err + tfErr := flex.TerraformErrorf(err, err.Error(), "ibm_resource_tag", "create") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } accountID := userDetails.UserAccount gtClient, err := meta.(conns.ClientSession).GlobalTaggingAPIv1() if err != nil { - return fmt.Errorf("[ERROR] Error getting global tagging client settings: %s", err) + tfErr := flex.TerraformErrorf(err, err.Error(), "ibm_resource_tag", "create") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } resourceID := d.Get(resourceID).(string) @@ -187,9 +193,24 @@ func resourceIBMResourceTagCreate(d *schema.ResourceData, meta interface{}) erro } if len(add) > 0 { - _, resp, err := gtClient.AttachTag(AttachTagOptions) + results, fullResponse, err := gtClient.AttachTagWithContext(context, AttachTagOptions) if err != nil { - return fmt.Errorf("[ERROR] Error attaching resource tags : %v\n%s", resp, err) + tfErr := flex.TerraformErrorf(err, err.Error(), "ibm_resource_tag", "create") + return tfErr.GetDiag() + } + + // Check if there are errors on the attach internal response + if results != nil { + errMap := make([]globaltaggingv1.TagResultsItem, 0) + for _, res := range results.Results { + if res.IsError != nil && *res.IsError { + errMap = append(errMap, res) + } + } + if len(errMap) > 0 { + output, _ := json.MarshalIndent(errMap, "", " ") + return diag.FromErr(fmt.Errorf("Error while creating tag: %s - Full response: %s", string(output), fullResponse)) + } } response, errored := flex.WaitForTagsAvailable(meta, resourceID, resourceType, tagType, news, d.Timeout(schema.TimeoutCreate)) if errored != nil { @@ -204,15 +225,17 @@ func resourceIBMResourceTagCreate(d *schema.ResourceData, meta interface{}) erro d.SetId(fmt.Sprintf("%s/%s", resourceID, rType)) } - return resourceIBMResourceTagRead(d, meta) + return resourceIBMResourceTagRead(context, d, meta) } -func resourceIBMResourceTagRead(d *schema.ResourceData, meta interface{}) error { +func resourceIBMResourceTagRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var rID, rType, tType string userDetails, err := meta.(conns.ClientSession).BluemixUserDetails() if err != nil { - return err + tfErr := flex.TerraformErrorf(err, err.Error(), "ibm_resource_tag", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } acctID := userDetails.UserAccount @@ -221,10 +244,12 @@ func resourceIBMResourceTagRead(d *schema.ResourceData, meta interface{}) error } else { parts, err := flex.VmIdParts(d.Id()) if err != nil { - return err + tfErr := flex.TerraformErrorf(err, err.Error(), "ibm_resource_tag", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } if len(parts) < 2 { - return fmt.Errorf("[ERROR] Incorrect ID %s: Id should be a combination of resourceID/resourceType", d.Id()) + return diag.FromErr(fmt.Errorf("Incorrect ID %s: Id should be a combination of resourceID/resourceType", d.Id())) } rID = parts[0] rType = parts[1] @@ -240,7 +265,7 @@ func resourceIBMResourceTagRead(d *schema.ResourceData, meta interface{}) error tagList, err := flex.GetGlobalTagsUsingSearchAPI(meta, rID, rType, tType) if err != nil { - return fmt.Errorf("[ERROR] Error getting resource tags for: %s with error : %s", rID, err) + return diag.FromErr(fmt.Errorf("Error getting resource tags for: %s with error : %s", rID, err)) } d.Set(resourceID, rID) @@ -250,7 +275,7 @@ func resourceIBMResourceTagRead(d *schema.ResourceData, meta interface{}) error return nil } -func resourceIBMResourceTagUpdate(d *schema.ResourceData, meta interface{}) error { +func resourceIBMResourceTagUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var rID, rType, tType string if strings.HasPrefix(d.Id(), "crn:") { @@ -258,7 +283,9 @@ func resourceIBMResourceTagUpdate(d *schema.ResourceData, meta interface{}) erro } else { parts, err := flex.VmIdParts(d.Id()) if err != nil { - return err + tfErr := flex.TerraformErrorf(err, err.Error(), "ibm_resource_tag", "update") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } rID = parts[0] rType = parts[1] @@ -272,61 +299,38 @@ func resourceIBMResourceTagUpdate(d *schema.ResourceData, meta interface{}) erro oldList, newList := d.GetChange(tags) err := flex.UpdateGlobalTagsUsingCRN(oldList, newList, meta, rID, rType, tType) if err != nil { - return fmt.Errorf("[ERROR] Error on create of resource tags: %s", err) + return diag.FromErr(fmt.Errorf("Error on create of resource tags: %s", err)) } } - return resourceIBMResourceTagRead(d, meta) + return resourceIBMResourceTagRead(context, d, meta) } -func resourceIBMResourceTagDelete(d *schema.ResourceData, meta interface{}) error { +func resourceIBMResourceTagDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var rID, rType string - if strings.HasPrefix(d.Id(), "crn:") { rID = d.Id() } else { parts, err := flex.VmIdParts(d.Id()) if err != nil { - return err + tfErr := flex.TerraformErrorf(err, err.Error(), "ibm_resource_tag", "delete") + log.Printf("[ERROR] Error in deleting.\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() } rID = parts[0] rType = parts[1] } - - gtClient, err := meta.(conns.ClientSession).GlobalTaggingAPIv1() - if err != nil { - return fmt.Errorf("[ERROR] Error getting global tagging client settings: %s", err) - } - - var remove []string removeTags := d.Get(tags).(*schema.Set) - remove = make([]string, len(removeTags.List())) - for i, v := range removeTags.List() { - remove[i] = fmt.Sprint(v) + var tType string + if v, ok := d.GetOk(tagType); ok && v != nil { + tType = v.(string) + } else { + tType = "user" } - - if len(remove) > 0 { - resources := []globaltaggingv1.Resource{} - r := globaltaggingv1.Resource{ResourceID: flex.PtrToString(rID), ResourceType: flex.PtrToString(rType)} - resources = append(resources, r) - - detachTagOptions := &globaltaggingv1.DetachTagOptions{ - Resources: resources, - TagNames: remove, - } - - _, resp, err := gtClient.DetachTag(detachTagOptions) + if len(removeTags.List()) > 0 { + err := flex.UpdateGlobalTagsUsingCRN(removeTags, nil, meta, rID, rType, tType) if err != nil { - return fmt.Errorf("[ERROR] Error detaching resource tags %v: %s\n%s", remove, err, resp) - } - for _, v := range remove { - delTagOptions := &globaltaggingv1.DeleteTagOptions{ - TagName: flex.PtrToString(v), - } - _, resp, err := gtClient.DeleteTag(delTagOptions) - if err != nil { - return fmt.Errorf("[ERROR] Error deleting resource tag %v: %s\n%s", v, err, resp) - } + return diag.FromErr(fmt.Errorf("Error on deleting tags: %s", err)) } } return nil diff --git a/ibm/service/globaltagging/resource_ibm_resource_tag_test.go b/ibm/service/globaltagging/resource_ibm_resource_tag_test.go index 38b076b209..414a1a2d4b 100644 --- a/ibm/service/globaltagging/resource_ibm_resource_tag_test.go +++ b/ibm/service/globaltagging/resource_ibm_resource_tag_test.go @@ -7,6 +7,7 @@ import ( "fmt" "log" "regexp" + "strings" "testing" acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" @@ -17,16 +18,18 @@ import ( ) func TestAccResourceTag_Basic(t *testing.T) { - name := fmt.Sprintf("tf-satellitelocation-%d", acctest.RandIntRange(10, 100)) - managed_from := "wdc04" + name := fmt.Sprintf("tf-cos-%d", acctest.RandIntRange(10, 100)) + var tags []string + tags = append(tags, "env:dev") + tags = append(tags, "cpu:4") resource.Test(t, resource.TestCase{ - PreCheck: func() { acc.TestAccPreCheck(t) }, - Providers: acc.TestAccProviders, + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckTagDestroy("ibm_resource_tag.tag", "user", tags), Steps: []resource.TestStep{ - { - Config: testAccCheckResourceTagCreate(name, managed_from), + Config: testAccCheckResourceTagCreate(name, tags), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckResourceTagExists("ibm_resource_tag.tag"), resource.TestCheckResourceAttr("ibm_resource_tag.tag", "tags.#", "2"), @@ -36,30 +39,51 @@ func TestAccResourceTag_Basic(t *testing.T) { ResourceName: "ibm_resource_tag.tag", ImportState: true, ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "replace"}, }, }, }) } -func TestAccResourceTag_Wait(t *testing.T) { - name := fmt.Sprintf("tf-satellitelocation-%d", acctest.RandIntRange(10, 100)) +func TestAccResourceTag_FakeCrnExpectingError(t *testing.T) { + var tags []string + tags = append(tags, "env:dev") + tags = append(tags, "cpu:4") resource.Test(t, resource.TestCase{ PreCheck: func() { acc.TestAccPreCheck(t) }, Providers: acc.TestAccProviders, Steps: []resource.TestStep{ + { + Config: testAccCheckResourceTagCreateFakeCrnExpectingError(tags), + ExpectError: regexp.MustCompile("\"is_error\": true"), + }, + }, + }) +} +func TestAccResourceTag_AttachOnExistingResource(t *testing.T) { + crn := "crn:v1:bluemix:public:toolchain:eu-gb:a/970f5cb4bbc04119ab0a0f399e4b776c:8784b8c3-1c7f-476a-ac30-50ae07e3cce3::" + var tags []string + tags = append(tags, "env:dev") + tags = append(tags, "cpu:4") + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckTagOnExistingResourceDestroy(crn, "ibm_resource_tag.tag", "user", tags), + Steps: []resource.TestStep{ { - Config: testAccCheckResourceTagWaitCreate(name), + Config: testAccCheckResourceAttachOnExistingResource(crn, tags), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckResourceTagExists("ibm_resource_tag.tag"), - resource.TestCheckResourceAttr("ibm_resource_tag.tag", "tags.#", "3"), + resource.TestCheckResourceAttr("ibm_resource_tag.tag", "tags.#", "2"), ), }, }, }) } -func testAccCheckResourceTagExists(n string) resource.TestCheckFunc { +func testAccCheckTagDestroy(n, tagType string, tagNames []string) resource.TestCheckFunc { return func(s *terraform.State) error { var resourceID string rs, ok := s.RootModule().Resources[n] @@ -71,7 +95,80 @@ func testAccCheckResourceTagExists(n string) resource.TestCheckFunc { if err != nil { return err } + if crn.MatchString(rs.Primary.ID) { + resourceID = rs.Primary.ID + } else { + parts, err := flex.VmIdParts(rs.Primary.ID) + if err != nil { + return err + } + resourceID = parts[0] + } + results, errorGet := flex.GetTagsUsingResourceCRNFromTaggingApi(acc.TestAccProvider.Meta(), resourceID, "", tagType) + if errorGet != nil { + return fmt.Errorf("Error on get of resource tags (%s) : %s", resourceID, errorGet) + } + var taglist []string + for _, v := range results.List() { + taglist = append(taglist, fmt.Sprint(v)) + } + existingAccessTags := flex.NewStringSet(flex.ResourceIBMVPCHash, taglist) + for _, tagName := range tagNames { + if existingAccessTags.Contains(tagName) { + return fmt.Errorf("Tag still exists") + } + } + return nil + } +} + +func testAccCheckTagOnExistingResourceDestroy(resourceCrn, n, tagType string, tagNames []string) resource.TestCheckFunc { + return func(s *terraform.State) error { + var resourceID string + _, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + crnRegex := "^crn:v1(:[a-zA-Z0-9 \\-\\._~\\*\\+,;=!$&'\\(\\)\\/\\?#\\[\\]@]*){8}$|^[0-9]+$" + crn, err := regexp.Compile(crnRegex) + if err != nil { + return err + } + if crn.MatchString(resourceCrn) { + resourceID = resourceCrn + } else { + return fmt.Errorf("CRN not correct: %s", resourceCrn) + } + results, errorGet := flex.GetTagsUsingResourceCRNFromTaggingApi(acc.TestAccProvider.Meta(), resourceID, "", tagType) + if errorGet != nil { + return fmt.Errorf("Error on get of resource tags (%s) : %s", resourceID, errorGet) + } + var taglist []string + for _, v := range results.List() { + taglist = append(taglist, fmt.Sprint(v)) + } + existingAccessTags := flex.NewStringSet(flex.ResourceIBMVPCHash, taglist) + for _, tagName := range tagNames { + if existingAccessTags.Contains(tagName) { + return fmt.Errorf("Tag still exists") + } + } + return nil + } +} +func testAccCheckResourceTagExists(n string) resource.TestCheckFunc { + return func(s *terraform.State) error { + var resourceID string + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + crnRegex := "^crn:v1(:[a-zA-Z0-9 \\-\\._~\\*\\+,;=!$&'\\(\\)\\/\\?#\\[\\]@]*){8}$|^[0-9]+$" + crn, err := regexp.Compile(crnRegex) + if err != nil { + return err + } if crn.MatchString(rs.Primary.ID) { resourceID = rs.Primary.ID } else { @@ -90,42 +187,38 @@ func testAccCheckResourceTagExists(n string) resource.TestCheckFunc { } } -func testAccCheckResourceTagWaitCreate(name string) string { +func testAccCheckResourceTagCreate(name string, tagNames []string) string { return fmt.Sprintf(` - - resource "ibm_is_vpc" "vpc" { - name = "%s" - } - - data "ibm_is_vpc" "test_vpc" { - name = ibm_is_vpc.vpc.name + resource "ibm_resource_instance" "resource_1" { + name = "%s" + service = "cloud-object-storage" + plan = "lite" + location = "global" } resource "ibm_resource_tag" "tag" { - resource_id = data.ibm_is_vpc.test_vpc.crn - tags = ["env:dev", "cpu:4", "user:8"] + resource_id = ibm_resource_instance.resource_1.crn + tags = ["%s"] } -`, name) +`, name, strings.Join(tagNames[:], "\",\"")) } -func testAccCheckResourceTagCreate(name, managed_from string) string { - return fmt.Sprintf(` - resource "ibm_satellite_location" "location" { - location = "%s" - managed_from = "%s" - description = "satellite service" - zones = ["us-east-1", "us-east-2", "us-east-3"] - } - - data "ibm_satellite_location" "test_location" { - location = ibm_satellite_location.location.id +func testAccCheckResourceTagCreateFakeCrnExpectingError(tagNames []string) string { + return fmt.Sprintf(` + resource "ibm_resource_tag" "tag" { + resource_id = "crn:v1:staging:public:cloud-object-storage:global:a/d99e99999dfe99ee999999f99bddd099:ab99d9be-9e9c-99dd-ad99-9bced9999999::" + tags = ["%s"] } +`, strings.Join(tagNames[:], "\",\"")) +} +func testAccCheckResourceAttachOnExistingResource(crn string, tagNames []string) string { + return fmt.Sprintf(` resource "ibm_resource_tag" "tag" { - resource_id = data.ibm_satellite_location.test_location.crn - tags = ["env:dev", "cpu:4"] + resource_id = "%s" + tags = ["%s"] } -`, name, managed_from) +`, crn, strings.Join(tagNames[:], "\",\"")) } func TestAccResourceTag_replace_Basic(t *testing.T) { @@ -156,14 +249,11 @@ func TestAccResourceTag_replace_Basic(t *testing.T) { func testAccCheckResourceTagCreate_replace(name string) string { return fmt.Sprintf(` - resource "ibm_resource_instance" "resource_1" { name = "%s" service = "cloud-object-storage" plan = "lite" location = "global" - - } resource "ibm_resource_tag" "tag" { diff --git a/ibm/service/iamidentity/resource_ibm_iam_trusted_profile_template_assignment.go b/ibm/service/iamidentity/resource_ibm_iam_trusted_profile_template_assignment.go index ad1ae38e10..2b4a131291 100644 --- a/ibm/service/iamidentity/resource_ibm_iam_trusted_profile_template_assignment.go +++ b/ibm/service/iamidentity/resource_ibm_iam_trusted_profile_template_assignment.go @@ -6,10 +6,11 @@ package iamidentity import ( "context" "fmt" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "log" "time" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -434,14 +435,16 @@ func resourceIBMTrustedProfileTemplateAssignmentRead(context context.Context, d if err = d.Set("target", templateAssignmentResponse.Target); err != nil { return diag.FromErr(fmt.Errorf("error setting target: %s", err)) } + ctx := []map[string]interface{}{} if !core.IsNil(templateAssignmentResponse.Context) { contextMap, err := resourceIBMTrustedProfileTemplateAssignmentResponseContextToMap(templateAssignmentResponse.Context) if err != nil { return diag.FromErr(err) } - if err = d.Set("context", []map[string]interface{}{contextMap}); err != nil { - return diag.FromErr(fmt.Errorf("error setting context: %s", err)) - } + ctx = append(ctx, contextMap) + } + if err = d.Set("context", ctx); err != nil { + return diag.FromErr(fmt.Errorf("[ERROR] Error setting context: %s", err)) } if err = d.Set("account_id", templateAssignmentResponse.AccountID); err != nil { return diag.FromErr(fmt.Errorf("error setting account_id: %s", err)) @@ -462,8 +465,8 @@ func resourceIBMTrustedProfileTemplateAssignmentRead(context context.Context, d return diag.FromErr(fmt.Errorf("error setting resources: %s", err)) } } + history := []map[string]interface{}{} if !core.IsNil(templateAssignmentResponse.History) { - history := []map[string]interface{}{} for _, historyItem := range templateAssignmentResponse.History { historyItemMap, err := resourceIBMTrustedProfileTemplateAssignmentEnityHistoryRecordToMap(&historyItem) if err != nil { @@ -471,9 +474,9 @@ func resourceIBMTrustedProfileTemplateAssignmentRead(context context.Context, d } history = append(history, historyItemMap) } - if err = d.Set("history", history); err != nil { - return diag.FromErr(fmt.Errorf("error setting history: %s", err)) - } + } + if err = d.Set("history", history); err != nil { + return diag.FromErr(fmt.Errorf("[ERROR] Error setting history: %s", err)) } if !core.IsNil(templateAssignmentResponse.Href) { if err = d.Set("href", templateAssignmentResponse.Href); err != nil { diff --git a/ibm/service/iamidentity/resource_ibm_iam_trusted_profile_template_assignment_test.go b/ibm/service/iamidentity/resource_ibm_iam_trusted_profile_template_assignment_test.go index 8ceeec507a..fa8b5887b8 100644 --- a/ibm/service/iamidentity/resource_ibm_iam_trusted_profile_template_assignment_test.go +++ b/ibm/service/iamidentity/resource_ibm_iam_trusted_profile_template_assignment_test.go @@ -30,8 +30,8 @@ func TestAccIBMTrustedProfileTemplateAssignmentBasic(t *testing.T) { CheckDestroy: testAccCheckIBMTrustedProfileTemplateAssignmentResourceDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckIBMTrustedProfileTemplateAssignmentConfigBasic(name, 1), - ExpectNonEmptyPlan: true, + + Config: testAccCheckIBMTrustedProfileTemplateAssignmentConfigBasic(name, 1), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckIBMTrustedProfileTemplateAssignmentExists("ibm_iam_trusted_profile_template_assignment.trusted_profile_template_assignment_instance", conf), resource.TestCheckResourceAttrSet("ibm_iam_trusted_profile_template_assignment.trusted_profile_template_assignment_instance", "id"), @@ -54,8 +54,7 @@ func TestAccIBMTrustedProfileTemplateAssignmentBasic(t *testing.T) { Config: testAccCheckIBMTrustedProfileTemplateAssignmentConfigBasic(name, 3), }, { - ExpectNonEmptyPlan: true, - Config: testAccCheckIBMTrustedProfileTemplateAssignmentConfigBasic(name, 2), + Config: testAccCheckIBMTrustedProfileTemplateAssignmentConfigBasic(name, 2), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr("ibm_iam_trusted_profile_template_assignment.trusted_profile_template_assignment_instance", "template_version", "2"), ), diff --git a/ibm/service/iampolicy/data_source_ibm_iam_policy_assignment_test.go b/ibm/service/iampolicy/data_source_ibm_iam_policy_assignment_test.go index 4bcc33195a..96e7647359 100644 --- a/ibm/service/iampolicy/data_source_ibm_iam_policy_assignment_test.go +++ b/ibm/service/iampolicy/data_source_ibm_iam_policy_assignment_test.go @@ -64,12 +64,6 @@ resource "ibm_iam_policy_assignment" "policy_assignment" { id = "%s" } - options { - root { - requester_id = "orchestrator" - assignment_id = "test" - } - } templates{ id = ibm_iam_policy_template.policy_s2s_template.template_id version = ibm_iam_policy_template.policy_s2s_template.version diff --git a/ibm/service/iampolicy/resource_ibm_iam_policy_assignment.go b/ibm/service/iampolicy/resource_ibm_iam_policy_assignment.go index 9072c9f76d..08a5cd8b39 100644 --- a/ibm/service/iampolicy/resource_ibm_iam_policy_assignment.go +++ b/ibm/service/iampolicy/resource_ibm_iam_policy_assignment.go @@ -7,8 +7,11 @@ import ( "context" "fmt" "log" + "strings" + "time" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" @@ -17,6 +20,12 @@ import ( "github.com/IBM/platform-services-go-sdk/iampolicymanagementv1" ) +const ( + InProgress = "in_progress" + complete = "complete" + failed = "failed" +) + func ResourceIBMIAMPolicyAssignment() *schema.Resource { return &schema.Resource{ CreateContext: resourceIBMPolicyAssignmentCreate, @@ -24,7 +33,11 @@ func ResourceIBMIAMPolicyAssignment() *schema.Resource { UpdateContext: resourceIBMPolicyAssignmentUpdate, DeleteContext: resourceIBMPolicyAssignmentDelete, Importer: &schema.ResourceImporter{}, - + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(30 * time.Minute), + Update: schema.DefaultTimeout(30 * time.Minute), + Delete: schema.DefaultTimeout(30 * time.Minute), + }, Schema: map[string]*schema.Schema{ "version": { Type: schema.TypeString, @@ -251,9 +264,9 @@ func resourceIBMPolicyAssignmentCreate(context context.Context, d *schema.Resour createPolicyTemplateAssignmentOptions := &iampolicymanagementv1.CreatePolicyTemplateAssignmentOptions{} createPolicyTemplateAssignmentOptions.SetVersion(d.Get("version").(string)) - targetModel, err := ResourceIBMPolicyAssignmentMapToAssignmentTargetDetails(d.Get("target").(map[string]interface{})) - if err != nil { - return diag.FromErr(err) + targetModel, diags := GetTargetModel(d) + if diags.HasError() { + return diags } createPolicyTemplateAssignmentOptions.SetTarget(targetModel) var templates []iampolicymanagementv1.AssignmentTemplateDetails @@ -278,6 +291,14 @@ func resourceIBMPolicyAssignmentCreate(context context.Context, d *schema.Resour d.SetId(*policyAssignmentV1Collection.Assignments[0].ID) + if targetModel.Type != nil && (*targetModel.Type == "Account") { + log.Printf("[DEBUG] Skipping waitForAssignment for target type: %s", *targetModel.Type) + } else { + _, err = waitForAssignment(d.Timeout(schema.TimeoutCreate), meta, d, isAccessPolicyAssigned) + if err != nil { + return diag.FromErr(fmt.Errorf("error assigning: %s", err)) + } + } return resourceIBMPolicyAssignmentRead(context, d, meta) } @@ -385,6 +406,12 @@ func resourceIBMPolicyAssignmentUpdate(context context.Context, d *schema.Resour updatePolicyAssignmentOptions.SetAssignmentID(d.Id()) + targetModel, diags := GetTargetModel(d) + + if diags.HasError() { + return diags + } + hasChange := false if d.HasChange("template_version") { @@ -416,6 +443,16 @@ func resourceIBMPolicyAssignmentUpdate(context context.Context, d *schema.Resour log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) return tfErr.GetDiag() } + + if targetModel.Type != nil && (*targetModel.Type == "Account") { + log.Printf("[DEBUG] Skipping waitForAssignment for target type: %s", *targetModel.Type) + } else { + _, err = waitForAssignment(d.Timeout(schema.TimeoutUpdate), meta, d, isAccessPolicyAssigned) + if err != nil { + return diag.FromErr(fmt.Errorf("error assigning: %s", err)) + } + } + } return resourceIBMPolicyAssignmentRead(context, d, meta) @@ -433,11 +470,32 @@ func resourceIBMPolicyAssignmentDelete(context context.Context, d *schema.Resour deletePolicyAssignmentOptions.SetAssignmentID(d.Id()) - _, err = iamPolicyManagementClient.DeletePolicyAssignmentWithContext(context, deletePolicyAssignmentOptions) + response, err := iamPolicyManagementClient.DeletePolicyAssignmentWithContext(context, deletePolicyAssignmentOptions) if err != nil { - tfErr := flex.TerraformErrorf(err, fmt.Sprintf("DeletePolicyAssignmentWithContext failed: %s", err.Error()), "ibm_policy_assignment", "delete") - log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) - return tfErr.GetDiag() + if response != nil && response.StatusCode == 404 { + return nil + } else { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("DeletePolicyAssignmentWithContext failed: %s", err.Error()), "ibm_policy_assignment", "delete") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + } + + targetModel, diags := GetTargetModel(d) + if diags.HasError() { + return diags + } + if targetModel.Type != nil && (*targetModel.Type == "Account") { + log.Printf("[DEBUG] Skipping waitForAssignment for target type: %s", *targetModel.Type) + } else { + _, err = waitForAssignment(d.Timeout(schema.TimeoutDelete), meta, d, isAccessPolicyAssignedDeleted) + if err != nil { + if strings.Contains(err.Error(), "not found") { + return nil + } else { + return diag.FromErr(fmt.Errorf("error assigning: %s", err)) + } + } } d.SetId("") @@ -477,3 +535,119 @@ func ResourceIBMPolicyAssignmentAssignmentTemplateDetailsToMap(model *iampolicym } return modelMap, nil } + +func GetTargetModel(d *schema.ResourceData) (*iampolicymanagementv1.AssignmentTargetDetails, diag.Diagnostics) { + targetModel, err := ResourceIBMPolicyAssignmentMapToAssignmentTargetDetails(d.Get("target").(map[string]interface{})) + + if err != nil { + return targetModel, diag.FromErr(err) + } + + return targetModel, nil +} + +func waitForAssignment(timeout time.Duration, meta interface{}, d *schema.ResourceData, refreshFn func(string, interface{}) resource.StateRefreshFunc) (interface{}, error) { + + stateConf := &resource.StateChangeConf{ + Pending: []string{InProgress}, + Target: []string{complete}, + Refresh: refreshFn(d.Id(), meta), + Delay: 30 * time.Second, + PollInterval: time.Minute, + Timeout: timeout, + } + + return stateConf.WaitForState() +} + +func isAccessPolicyAssigned(id string, meta interface{}) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + iamPolicyManagementClient, err := meta.(conns.ClientSession).IAMPolicyManagementV1API() + if err != nil { + return nil, failed, err + } + + getAssignmentPolicyOptions := &iampolicymanagementv1.GetPolicyAssignmentOptions{ + AssignmentID: core.StringPtr(id), + Version: core.StringPtr("1.0"), + } + + getAssignmentPolicyOptions.SetAssignmentID(id) + + assignmentDetails, response, err := iamPolicyManagementClient.GetPolicyAssignment(getAssignmentPolicyOptions) + + if err != nil { + if response != nil && response.StatusCode == 404 { + return nil, failed, err + } + return nil, failed, err + } + + assignment, ok := assignmentDetails.(*iampolicymanagementv1.GetPolicyAssignmentResponse) + + if !ok { + return nil, failed, fmt.Errorf("[ERROR] Type assertion failed for assignment details : %s", id) + } + + if assignment != nil { + if *assignment.Status == "accepted" || *assignment.Status == "in_progress" { + log.Printf("Assignment still in progress\n") + return assignment, InProgress, nil + } + + if *assignment.Status == "succeeded" { + return assignment, complete, nil + } + + if *assignment.Status == "failed" { + return assignment, failed, fmt.Errorf("[ERROR] The assignment %s did not complete successfully and has a 'failed' status. Please check assignment resource for detailed errors: %s\n", id, response) + } + } + + return assignment, failed, fmt.Errorf("[ERROR] Unexpected status reached for assignment %s.: %s\n", id, response) + } +} + +func isAccessPolicyAssignedDeleted(id string, meta interface{}) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + iamPolicyManagementClient, err := meta.(conns.ClientSession).IAMPolicyManagementV1API() + if err != nil { + return nil, failed, err + } + + getAssignmentPolicyOptions := &iampolicymanagementv1.GetPolicyAssignmentOptions{ + AssignmentID: core.StringPtr(id), + Version: core.StringPtr("1.0"), + } + + getAssignmentPolicyOptions.SetAssignmentID(id) + + assignmentDetails, response, err := iamPolicyManagementClient.GetPolicyAssignment(getAssignmentPolicyOptions) + + if err != nil { + if response != nil && response.StatusCode == 404 { + return nil, failed, err + } + return nil, failed, err + } + + assignment, ok := assignmentDetails.(*iampolicymanagementv1.GetPolicyAssignmentResponse) + + if !ok { + return nil, failed, fmt.Errorf("[ERROR] Type assertion failed for assignment details : %s", id) + } + + if assignment != nil { + if *assignment.Status == "accepted" || *assignment.Status == "in_progress" { + log.Printf("Assignment still in progress\n") + return assignment, InProgress, nil + } + + if *assignment.Status == "failed" { + return assignment, failed, fmt.Errorf("[ERROR] The assignment %s did not complete successfully and has a 'failed' status. Please check assignment resource for detailed errors: %s\n", id, response) + } + } + + return assignment, failed, fmt.Errorf("[ERROR] Unexpected status reached for assignment %s.: %s\n", id, response) + } +} diff --git a/ibm/service/iampolicy/resource_ibm_iam_policy_assignment_test.go b/ibm/service/iampolicy/resource_ibm_iam_policy_assignment_test.go index 925fe756b1..aa1dc86bd7 100644 --- a/ibm/service/iampolicy/resource_ibm_iam_policy_assignment_test.go +++ b/ibm/service/iampolicy/resource_ibm_iam_policy_assignment_test.go @@ -70,6 +70,27 @@ func TestAccIBMPolicyAssignmentS2SBasic(t *testing.T) { }) } +func TestAccIBMPolicyAssignmentEnterprise(t *testing.T) { + var conf iampolicymanagementv1.GetPolicyAssignmentResponse + var name string = fmt.Sprintf("TerraformTemplateTest%d", acctest.RandIntRange(10, 100)) + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIBMPolicyAssignmentDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIBMPolicyAssignmentConfigEnterprise(name, acc.TargetEnterpriseId), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIBMPolicyAssignmentExists("ibm_iam_policy_assignment.policy_assignment", conf), + resource.TestCheckResourceAttr("ibm_iam_policy_template.policy_s2s_template", "name", name), + resource.TestCheckResourceAttr("ibm_iam_policy_template.policy_s2s_template", "policy.0.resource.0.attributes.0.value", resourceServiceName), + resource.TestCheckResourceAttr("ibm_iam_policy_template.policy_s2s_template", "policy.0.subject.0.attributes.0.value", "compliance"), + ), + }, + }, + }) +} + func testAccCheckIBMPolicyAssignmentConfigBasic(name string, targetId string) string { return fmt.Sprintf(` resource "ibm_iam_policy_template" "policy_s2s_template" { @@ -215,8 +236,46 @@ func testAccCheckIBMPolicyAssignmentConfigUpdate(name string, targetId string) s } templates{ - id = ibm_iam_policy_template.policy_s2stemplate.template_id - version = ibm_iam_policy_template.policy_s2stemplate.version + id = ibm_iam_policy_template_version.template_version.template_id + version = ibm_iam_policy_template_version.template_version.version + } + }`, name, targetId) +} + +func testAccCheckIBMPolicyAssignmentConfigEnterprise(name string, targetId string) string { + return fmt.Sprintf(` + resource "ibm_iam_policy_template" "policy_s2s_template" { + name = "%s" + policy { + type = "authorization" + description = "description" + resource { + attributes { + key = "serviceName" + operator = "stringEquals" + value = "kms" + } + } + subject { + attributes { + key = "serviceName" + operator = "stringEquals" + value = "compliance" + } + } + roles = ["Reader"] + } + committed=true + } + resource "ibm_iam_policy_assignment" "policy_assignment" { + version = "1.0" + target ={ + type = "Enterprise" + id = "%s" + } + templates{ + id = ibm_iam_policy_template.policy_s2s_template.template_id + version = ibm_iam_policy_template.policy_s2s_template.version } }`, name, targetId) } diff --git a/ibm/service/logsrouting/data_source_ibm_logs-router_targets.go b/ibm/service/logsrouting/data_source_ibm_logs-router_targets.go index 8e3b178a87..54655d4019 100644 --- a/ibm/service/logsrouting/data_source_ibm_logs-router_targets.go +++ b/ibm/service/logsrouting/data_source_ibm_logs-router_targets.go @@ -38,6 +38,12 @@ func DataSourceIBMLogsRouterTargets() *schema.Resource { Optional: true, Description: "Optional: Name of the tenant target.", }, + "region": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: "The region where the tenant for these targets exist.", + }, "targets": &schema.Schema{ Type: schema.TypeList, Computed: true, @@ -121,6 +127,10 @@ func dataSourceIBMLogsRouterTargetsRead(context context.Context, d *schema.Resou listTenantTargetsOptions.SetName(d.Get("name").(string)) } + if _, ok := d.GetOk("region"); ok { + listTenantTargetsOptions.SetRegion(d.Get("region").(string)) + } + targetTypeCollection, _, err := ibmCloudLogsRoutingClient.ListTenantTargetsWithContext(context, listTenantTargetsOptions) if err != nil { tfErr := flex.TerraformErrorf(err, fmt.Sprintf("ListTenantTargetsWithContext failed: %s", err.Error()), "(Data) ibm_logs_router_targets", "read") diff --git a/ibm/service/logsrouting/data_source_ibm_logs-router_targets_test.go b/ibm/service/logsrouting/data_source_ibm_logs-router_targets_test.go index 721dda7c6c..848adbc662 100644 --- a/ibm/service/logsrouting/data_source_ibm_logs-router_targets_test.go +++ b/ibm/service/logsrouting/data_source_ibm_logs-router_targets_test.go @@ -44,6 +44,7 @@ func testAccCheckIBMLogsRouterTargetsDataSourceConfigBasic(tenantName string) st return fmt.Sprintf(` resource "ibm_logs_router_tenant" "logs_router_tenant_instance" { name = "%s" + region = "br-sao" targets { log_sink_crn = "crn:v1:bluemix:public:logdna:eu-de:a/3516b8fa0a174a71899f5affa4f18d78:3517d2ed-9429-af34-ad52-34278391cbc8::" name = "my-log-sink" @@ -58,6 +59,7 @@ func testAccCheckIBMLogsRouterTargetsDataSourceConfigBasic(tenantName string) st data "ibm_logs_router_targets" "logs_router_targets_instance" { tenant_id = ibm_logs_router_tenant.logs_router_tenant_instance.id + region = ibm_logs_router_tenant.logs_router_tenant_instance.region } `, tenantName, acc.IngestionKey) } diff --git a/ibm/service/logsrouting/data_source_ibm_logs-router_tenants.go b/ibm/service/logsrouting/data_source_ibm_logs-router_tenants.go index 1c263b140c..778ce622c2 100644 --- a/ibm/service/logsrouting/data_source_ibm_logs-router_tenants.go +++ b/ibm/service/logsrouting/data_source_ibm_logs-router_tenants.go @@ -31,6 +31,12 @@ func DataSourceIBMLogsRouterTenants() *schema.Resource { Required: true, Description: "Optional: The name of a tenant.", }, + "region": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: "The region where the tenants exist.", + }, "tenants": &schema.Schema{ Type: schema.TypeList, Computed: true, @@ -152,6 +158,10 @@ func dataSourceIBMLogsRouterTenantsRead(context context.Context, d *schema.Resou listTenantsOptions.SetName(d.Get("name").(string)) } + if _, ok := d.GetOk("region"); ok { + listTenantsOptions.SetRegion(d.Get("region").(string)) + } + tenantCollection, _, err := ibmCloudLogsRoutingClient.ListTenantsWithContext(context, listTenantsOptions) if err != nil { tfErr := flex.TerraformErrorf(err, fmt.Sprintf("ListTenantsWithContext failed: %s", err.Error()), "(Data) ibm_logs_router_tenants", "read") diff --git a/ibm/service/logsrouting/data_source_ibm_logs-router_tenants_test.go b/ibm/service/logsrouting/data_source_ibm_logs-router_tenants_test.go index 897e488753..5165c0ce46 100644 --- a/ibm/service/logsrouting/data_source_ibm_logs-router_tenants_test.go +++ b/ibm/service/logsrouting/data_source_ibm_logs-router_tenants_test.go @@ -43,6 +43,7 @@ func testAccCheckIBMLogsRouterTenantsDataSourceConfigBasic(tenantName string) st return fmt.Sprintf(` resource "ibm_logs_router_tenant" "logs_router_tenant_instance" { name = "%s" + region = "br-sao" targets { log_sink_crn = "crn:v1:bluemix:public:logdna:eu-de:a/3516b8fa0a174a71899f5affa4f18d78:3517d2ed-9429-af34-ad52-34278391cbc8::" name = "my-log-sink" @@ -57,6 +58,7 @@ func testAccCheckIBMLogsRouterTenantsDataSourceConfigBasic(tenantName string) st data "ibm_logs_router_tenants" "logs_router_tenants_instance" { name = ibm_logs_router_tenant.logs_router_tenant_instance.name + region = ibm_logs_router_tenant.logs_router_tenant_instance.region } `, tenantName, acc.IngestionKey) } diff --git a/ibm/service/logsrouting/resource_ibm_logs-router_tenant.go b/ibm/service/logsrouting/resource_ibm_logs-router_tenant.go index 0788aea6db..3209118fec 100644 --- a/ibm/service/logsrouting/resource_ibm_logs-router_tenant.go +++ b/ibm/service/logsrouting/resource_ibm_logs-router_tenant.go @@ -30,7 +30,22 @@ func ResourceIBMLogsRouterTenant() *schema.Resource { ReadContext: resourceIBMLogsRouterTenantRead, UpdateContext: resourceIBMLogsRouterTenantUpdate, DeleteContext: resourceIBMLogsRouterTenantDelete, - Importer: &schema.ResourceImporter{}, + Importer: &schema.ResourceImporter{ + State: func(d *schema.ResourceData, meta interface{}) (result []*schema.ResourceData, err error) { + ID := d.Id() + parts := strings.Split(ID, "/") + if len(parts) < 2 { + return nil, fmt.Errorf("Invalid import format: please specify 'tenant_id/region'") + } + tenantID := parts[0] + region := parts[1] + d.SetId(tenantID) + if err := d.Set("region", region); err != nil { + return nil, err + } + return []*schema.ResourceData{d}, nil + }, + }, Schema: map[string]*schema.Schema{ "name": &schema.Schema{ @@ -39,9 +54,16 @@ func ResourceIBMLogsRouterTenant() *schema.Resource { ValidateFunc: validate.InvokeValidator("ibm_logs_router_tenant", "name"), Description: "The name for this tenant. The name is regionally unique across all tenants in the account.", }, + "region": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validate.InvokeValidator("ibm_logs_router_tenant", "region"), + Description: "The region where this tenant exists.", + }, "targets": &schema.Schema{ Type: schema.TypeList, - Optional: true, + Required: true, MinItems: 1, Description: "List of targets", Elem: &schema.Resource{ @@ -86,7 +108,7 @@ func ResourceIBMLogsRouterTenant() *schema.Resource { "parameters": &schema.Schema{ Type: schema.TypeList, MaxItems: 1, - Optional: true, + Required: true, Description: "List of properties returned from a successful list operation for a log-sink of type IBM Log Analysis (logdna).", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ @@ -148,6 +170,15 @@ func ResourceIBMLogsRouterTenantValidator() *validate.ResourceValidator { MinValueLength: 1, MaxValueLength: 35, }, + validate.ValidateSchema{ + Identifier: "region", + ValidateFunctionIdentifier: validate.ValidateRegexpLen, + Type: validate.TypeString, + Optional: true, + Regexp: `^[a-zA-Z0-9 -._:]+$`, + MinValueLength: 3, + MaxValueLength: 1000, + }, ) resourceValidator := validate.ResourceValidator{ResourceName: "ibm_logs_router_tenant", Schema: validateSchema} @@ -166,6 +197,7 @@ func resourceIBMLogsRouterTenantCreate(context context.Context, d *schema.Resour createTenantOptions := &ibmcloudlogsroutingv0.CreateTenantOptions{} createTenantOptions.SetName(d.Get("name").(string)) + createTenantOptions.SetRegion(d.Get("region").(string)) var targets []ibmcloudlogsroutingv0.TargetTypePrototypeIntf for _, v := range d.Get("targets").([]interface{}) { value := v.(map[string]interface{}) @@ -201,6 +233,7 @@ func resourceIBMLogsRouterTenantRead(context context.Context, d *schema.Resource tenantId := strfmt.UUID(d.Id()) getTenantDetailOptions.SetTenantID(&tenantId) + getTenantDetailOptions.SetRegion(d.Get("region").(string)) tenant, response, err := ibmCloudLogsRoutingClient.GetTenantDetailWithContext(context, getTenantDetailOptions) if err != nil { @@ -317,6 +350,7 @@ func resourceIBMLogsRouterTenantUpdate(context context.Context, d *schema.Resour tenantId := strfmt.UUID(d.Id()) updateTenantOptions.SetTenantID(&tenantId) + updateTenantOptions.SetRegion(d.Get("region").(string)) hasChange := false hasChangeTarget0 := false @@ -336,6 +370,7 @@ func resourceIBMLogsRouterTenantUpdate(context context.Context, d *schema.Resour target0ID := strfmt.UUID(d.Get("targets.0.id").(string)) updateTarget0Options.SetTenantID(&tenantId) updateTarget0Options.SetTargetID(&target0ID) + updateTarget0Options.SetRegion(d.Get("region").(string)) patchValsTarget0 := &ibmcloudlogsroutingv0.TargetTypePatch{} if d.HasChange("targets.0.tenant_id") { @@ -367,6 +402,7 @@ func resourceIBMLogsRouterTenantUpdate(context context.Context, d *schema.Resour target1ID := strfmt.UUID(d.Get("targets.1.id").(string)) updateTarget1Options.SetTenantID(&tenantId) updateTarget1Options.SetTargetID(&target1ID) + updateTarget1Options.SetRegion(d.Get("region").(string)) bodyModelMap := map[string]interface{}{} createTarget1Options := &ibmcloudlogsroutingv0.CreateTargetOptions{} @@ -383,6 +419,7 @@ func resourceIBMLogsRouterTenantUpdate(context context.Context, d *schema.Resour bodyModelMap["parameters"] = d.Get("targets.1.parameters") } createTarget1Options.SetTenantID(&tenantId) + createTarget1Options.SetRegion(d.Get("region").(string)) convertedModel, err := ResourceIBMLogsRouterTargetMapToTargetTypePrototypeTargetTypeLogDNAPrototype(bodyModelMap) if err != nil { return flex.DiscriminatedTerraformErrorf(err, err.Error(), "ibm_logs_router_target", "create", "parse-request-body").GetDiag() @@ -497,6 +534,7 @@ func resourceIBMLogsRouterTenantUpdate(context context.Context, d *schema.Resour deleteTargetOptions := &ibmcloudlogsroutingv0.DeleteTargetOptions{} deleteTargetOptions.SetTenantID(&tenantId) deleteTargetOptions.SetTargetID(&target1ID) + deleteTargetOptions.SetRegion(d.Get("region").(string)) _, err = ibmCloudLogsRoutingClient.DeleteTargetWithContext(context, deleteTargetOptions) if err != nil { tfErr := flex.TerraformErrorf(err, fmt.Sprintf("DeleteTargetWithContext failed: %s", err.Error()), "ibm_logs_router_target", "delete") @@ -567,6 +605,7 @@ func resourceIBMLogsRouterTenantDelete(context context.Context, d *schema.Resour tenantId := strfmt.UUID(d.Id()) deleteTenantOptions.SetTenantID(&tenantId) + deleteTenantOptions.SetRegion(d.Get("region").(string)) _, err = ibmCloudLogsRoutingClient.DeleteTenantWithContext(context, deleteTenantOptions) if err != nil { diff --git a/ibm/service/logsrouting/resource_ibm_logs-router_tenant_test.go b/ibm/service/logsrouting/resource_ibm_logs-router_tenant_test.go index af3559ba46..2b3b7dca4f 100644 --- a/ibm/service/logsrouting/resource_ibm_logs-router_tenant_test.go +++ b/ibm/service/logsrouting/resource_ibm_logs-router_tenant_test.go @@ -49,9 +49,16 @@ func TestAccIBMLogsRouterTenantBasic(t *testing.T) { ), }, resource.TestStep{ - ResourceName: "ibm_logs_router_tenant.logs_router_tenant_instance", - ImportState: true, - ImportStateVerify: true, + ResourceName: "ibm_logs_router_tenant.logs_router_tenant_instance", + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: func(s *terraform.State) (string, error) { + rs, ok := s.RootModule().Resources["ibm_logs_router_tenant.logs_router_tenant_instance"] + if !ok { + return "", fmt.Errorf("Not found: %s", "ibm_logs_router_tenant.logs_router_tenant_instance") + } + return fmt.Sprintf("%s/%s", rs.Primary.ID, rs.Primary.Attributes["region"]), nil + }, ImportStateVerifyIgnore: []string{"targets.0.parameters.0.access_credential", "targets.1.parameters.0.access_credential"}, }, }, @@ -92,9 +99,16 @@ func TestAccIBMLogsRouterTenantAllArgs(t *testing.T) { ), }, resource.TestStep{ - ResourceName: "ibm_logs_router_tenant.logs_router_tenant_instance", - ImportState: true, - ImportStateVerify: true, + ResourceName: "ibm_logs_router_tenant.logs_router_tenant_instance", + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: func(s *terraform.State) (string, error) { + rs, ok := s.RootModule().Resources["ibm_logs_router_tenant.logs_router_tenant_instance"] + if !ok { + return "", fmt.Errorf("Not found: %s", "ibm_logs_router_tenant.logs_router_tenant_instance") + } + return fmt.Sprintf("%s/%s", rs.Primary.ID, rs.Primary.Attributes["region"]), nil + }, ImportStateVerifyIgnore: []string{"targets.0.parameters.0.access_credential", "targets.1.parameters.0.access_credential"}, }, }, @@ -105,6 +119,7 @@ func testAccCheckIBMLogsRouterTenantConfigBasic(name string, crn string, host st return fmt.Sprintf(` resource "ibm_logs_router_tenant" "logs_router_tenant_instance" { name = "%s" + region = "br-sao" targets { log_sink_crn = "%s" name = "my-log-sink" @@ -122,6 +137,7 @@ func testAccCheckIBMLogsRouterTenantConfigAllArgs(name string, target0Name strin return fmt.Sprintf(` resource "ibm_logs_router_tenant" "logs_router_tenant_instance" { name = "%s" + region = "br-sao" targets { log_sink_crn = "crn:v1:bluemix:public:logdna:eu-de:a/3516b8fa0a174a71899f5affa4f18d78:3517d2ed-9429-af34-ad52-34278391cbc8::" name = "%s" @@ -151,6 +167,7 @@ func testAccCheckIBMLogsRouterTenantExists(n string, obj ibmcloudlogsroutingv0.T tenantId := strfmt.UUID(rs.Primary.ID) getTenantDetailOptions.SetTenantID(&tenantId) + getTenantDetailOptions.SetRegion(rs.Primary.Attributes["region"]) tenant, _, err := ibmCloudLogsRoutingClient.GetTenantDetail(getTenantDetailOptions) if err != nil { @@ -176,6 +193,7 @@ func testAccCheckIBMLogsRouterTenantDestroy(s *terraform.State) error { tenantId := strfmt.UUID(rs.Primary.ID) getTenantDetailOptions.SetTenantID(&tenantId) + getTenantDetailOptions.SetRegion(rs.Primary.Attributes["region"]) // Try to find the key _, response, err := ibmCloudLogsRoutingClient.GetTenantDetail(getTenantDetailOptions) diff --git a/ibm/service/resourcecontroller/resource_ibm_resource_instance.go b/ibm/service/resourcecontroller/resource_ibm_resource_instance.go index acadc93b7e..a31215fbb3 100644 --- a/ibm/service/resourcecontroller/resource_ibm_resource_instance.go +++ b/ibm/service/resourcecontroller/resource_ibm_resource_instance.go @@ -251,12 +251,14 @@ func ResourceIBMResourceInstance() *schema.Resource { "resource_aliases_url": { Description: "The relative path to the resource aliases for the instance.", Type: schema.TypeString, + Deprecated: "Remove this attribute's configuration as it's no longer in use and the attribute will be removed in the upcoming major version of the provider 1.71.0.", Computed: true, }, "resource_bindings_url": { Description: "The relative path to the resource bindings for the instance.", Type: schema.TypeString, + Deprecated: "Remove this attribute's configuration as it's no longer in use and the attribute will be removed in the upcoming major version of the provider 1.71.0.", Computed: true, }, diff --git a/ibm/service/resourcecontroller/resource_ibm_resource_key.go b/ibm/service/resourcecontroller/resource_ibm_resource_key.go index 5f693ddfc3..a5b08c077e 100644 --- a/ibm/service/resourcecontroller/resource_ibm_resource_key.go +++ b/ibm/service/resourcecontroller/resource_ibm_resource_key.go @@ -66,6 +66,7 @@ func ResourceIBMResourceKey() *schema.Resource { Optional: true, ForceNew: true, Description: "The id of the resource alias for which to create resource key", + Deprecated: "Remove this attribute's configuration as it's no longer in use and the attribute will be removed in the upcoming major version of the provider 1.71.0.", ConflictsWith: []string{"resource_instance_id"}, }, diff --git a/ibm/service/schematics/data_source_ibm_schematics_job.go b/ibm/service/schematics/data_source_ibm_schematics_job.go index 663e3fa14b..64f35170d5 100644 --- a/ibm/service/schematics/data_source_ibm_schematics_job.go +++ b/ibm/service/schematics/data_source_ibm_schematics_job.go @@ -4212,7 +4212,7 @@ func dataSourceJobLogSummaryToMap(logSummaryItem schematicsv1.JobLogSummary) (lo return logSummaryMap } -func dataSourceJobLogSummaryLogErrorsToMap(logErrorsItem schematicsv1.JobLogSummaryLogErrorsItem) (logErrorsMap map[string]interface{}) { +func dataSourceJobLogSummaryLogErrorsToMap(logErrorsItem schematicsv1.JobLogSummaryLogErrors) (logErrorsMap map[string]interface{}) { logErrorsMap = map[string]interface{}{} if logErrorsItem.ErrorCode != nil { diff --git a/ibm/service/schematics/resource_ibm_schematics_agent.go b/ibm/service/schematics/resource_ibm_schematics_agent.go index 36f440553f..02843f1efd 100644 --- a/ibm/service/schematics/resource_ibm_schematics_agent.go +++ b/ibm/service/schematics/resource_ibm_schematics_agent.go @@ -900,7 +900,9 @@ func resourceIbmSchematicsAgentDelete(context context.Context, d *schema.Resourc return diag.FromErr(err) } - deleteAgentDataOptions := &schematicsv1.DeleteAgentDataOptions{} + deleteAgentDataOptions := &schematicsv1.DeleteAgentDataOptions{ + Force: core.BoolPtr(true), + } session, err := meta.(conns.ClientSession).BluemixSession() if err != nil { return diag.FromErr(err) diff --git a/ibm/service/schematics/resource_ibm_schematics_agent_test.go b/ibm/service/schematics/resource_ibm_schematics_agent_test.go index f5a4c6e646..3a2dd4384e 100644 --- a/ibm/service/schematics/resource_ibm_schematics_agent_test.go +++ b/ibm/service/schematics/resource_ibm_schematics_agent_test.go @@ -195,9 +195,7 @@ func testAccCheckIbmSchematicsAgentDestroy(s *terraform.State) error { // Try to find the key _, response, err := schematicsClient.GetAgentData(getAgentDataOptions) if err == nil { - return nil - // TODO: uncomment the following lines of code once the agent delete actually deletes agentdoc - // return fmt.Errorf("schematics_agent still exists: %s", rs.Primary.ID) + return fmt.Errorf("schematics_agent still exists: %s", rs.Primary.ID) } else if response.StatusCode != 404 { return fmt.Errorf("Error checking for schematics_agent (%s) has been destroyed: %s", rs.Primary.ID, err) } diff --git a/ibm/service/schematics/resource_ibm_schematics_job.go b/ibm/service/schematics/resource_ibm_schematics_job.go index b8927e5101..4893b8b7ae 100644 --- a/ibm/service/schematics/resource_ibm_schematics_job.go +++ b/ibm/service/schematics/resource_ibm_schematics_job.go @@ -3701,7 +3701,7 @@ func resourceIBMSchematicsJobMapToJobLogSummary(jobLogSummaryMap map[string]inte jobLogSummary.ElapsedTime = core.Float64Ptr(jobLogSummaryMap["elapsed_time"].(float64)) } if jobLogSummaryMap["log_errors"] != nil { - logErrors := []schematicsv1.JobLogSummaryLogErrorsItem{} + logErrors := []schematicsv1.JobLogSummaryLogErrors{} for _, logErrorsItem := range jobLogSummaryMap["log_errors"].([]interface{}) { logErrorsItemModel := resourceIBMSchematicsJobMapToJobLogSummaryLogErrors(logErrorsItem.(map[string]interface{})) logErrors = append(logErrors, logErrorsItemModel) @@ -3732,8 +3732,8 @@ func resourceIBMSchematicsJobMapToJobLogSummary(jobLogSummaryMap map[string]inte return jobLogSummary } -func resourceIBMSchematicsJobMapToJobLogSummaryLogErrors(jobLogSummaryLogErrorsMap map[string]interface{}) schematicsv1.JobLogSummaryLogErrorsItem { - jobLogSummaryLogErrors := schematicsv1.JobLogSummaryLogErrorsItem{} +func resourceIBMSchematicsJobMapToJobLogSummaryLogErrors(jobLogSummaryLogErrorsMap map[string]interface{}) schematicsv1.JobLogSummaryLogErrors { + jobLogSummaryLogErrors := schematicsv1.JobLogSummaryLogErrors{} if jobLogSummaryLogErrorsMap["error_code"] != nil { jobLogSummaryLogErrors.ErrorCode = core.StringPtr(jobLogSummaryLogErrorsMap["error_code"].(string)) @@ -4803,7 +4803,7 @@ func resourceIBMSchematicsJobJobLogSummaryToMap(jobLogSummary schematicsv1.JobLo return jobLogSummaryMap } -func resourceIBMSchematicsJobJobLogSummaryLogErrorsToMap(jobLogSummaryLogErrors schematicsv1.JobLogSummaryLogErrorsItem) map[string]interface{} { +func resourceIBMSchematicsJobJobLogSummaryLogErrorsToMap(jobLogSummaryLogErrors schematicsv1.JobLogSummaryLogErrors) map[string]interface{} { jobLogSummaryLogErrorsMap := map[string]interface{}{} if jobLogSummaryLogErrors.ErrorCode != nil { diff --git a/ibm/service/schematics/resource_ibm_schematics_workspace.go b/ibm/service/schematics/resource_ibm_schematics_workspace.go index 0853d0c7d6..bbd89ddf2f 100644 --- a/ibm/service/schematics/resource_ibm_schematics_workspace.go +++ b/ibm/service/schematics/resource_ibm_schematics_workspace.go @@ -581,7 +581,7 @@ func ResourceIBMSchematicsWorkspaceValidator() *validate.ResourceValidator { Identifier: schematicsWorkspaceTemplateType, ValidateFunctionIdentifier: validate.ValidateRegexp, Type: validate.TypeString, - Regexp: `^terraform_v(?:0\.11|0\.12|0\.13|0\.14|0\.15|1\.0|1\.1|1\.2|1\.3|1\.4|1\.5|1\.6)(?:\.\d+)?$`, + Regexp: `^terraform_v(?:1\.4|1\.5|1\.6|1\.7|1\.8|1\.9)(?:\.\d+)?$`, Default: "[]", Optional: true}) diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_arbitrary_secret.go b/ibm/service/secretsmanager/data_source_ibm_sm_arbitrary_secret.go index 7572a8d2f0..2cd8853a85 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_arbitrary_secret.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_arbitrary_secret.go @@ -131,8 +131,7 @@ func DataSourceIbmSmArbitrarySecret() *schema.Resource { } func dataSourceIbmSmArbitrarySecretRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - - secret, region, instanceId, diagError := getSecretByIdOrByName(context, d, meta, ArbitrarySecretType) + secret, region, instanceId, diagError := getSecretByIdOrByName(context, d, meta, ArbitrarySecretType, ArbitrarySecretResourceName) if diagError != nil { return diagError } @@ -142,18 +141,22 @@ func dataSourceIbmSmArbitrarySecretRead(context context.Context, d *schema.Resou var err error if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_by", arbitrarySecret.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), fmt.Sprintf("(Data) %s", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(arbitrarySecret.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), fmt.Sprintf("(Data) %s", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("crn", arbitrarySecret.Crn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crn"), fmt.Sprintf("(Data) %s", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if arbitrarySecret.CustomMetadata != nil { @@ -163,59 +166,73 @@ func dataSourceIbmSmArbitrarySecretRead(context context.Context, d *schema.Resou } if err = d.Set("custom_metadata", flex.Flatten(convertedMap)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } } if err = d.Set("description", arbitrarySecret.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), fmt.Sprintf("(Data) %s", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("downloaded", arbitrarySecret.Downloaded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting downloaded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting downloaded"), fmt.Sprintf("(Data) %s", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("locks_total", flex.IntValue(arbitrarySecret.LocksTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locks_total"), fmt.Sprintf("(Data) %s", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("name", arbitrarySecret.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), fmt.Sprintf("(Data) %s", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_group_id", arbitrarySecret.SecretGroupID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_group_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_group_id"), fmt.Sprintf("(Data) %s", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", arbitrarySecret.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), fmt.Sprintf("(Data) %s", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state", flex.IntValue(arbitrarySecret.State)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state"), fmt.Sprintf("(Data) %s", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state_description", arbitrarySecret.StateDescription); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state_description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state_description"), fmt.Sprintf("(Data) %s", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(arbitrarySecret.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), fmt.Sprintf("(Data) %s", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("versions_total", flex.IntValue(arbitrarySecret.VersionsTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting versions_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting versions_total"), fmt.Sprintf("(Data) %s", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("expiration_date", DateTimeToRFC3339(arbitrarySecret.ExpirationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting expiration_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting expiration_date"), fmt.Sprintf("(Data) %s", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("payload", arbitrarySecret.Payload); err != nil { - return diag.FromErr(fmt.Errorf("Error setting payload: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting payload"), fmt.Sprintf("(Data) %s", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } return nil diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_arbitrary_secret_metadata.go b/ibm/service/secretsmanager/data_source_ibm_sm_arbitrary_secret_metadata.go index 9ac786871a..c822a89341 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_arbitrary_secret_metadata.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_arbitrary_secret_metadata.go @@ -119,7 +119,8 @@ func DataSourceIbmSmArbitrarySecretMetadata() *schema.Resource { func dataSourceIbmSmArbitrarySecretMetadataRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s_metadata", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -134,7 +135,8 @@ func dataSourceIbmSmArbitrarySecretMetadataRead(context context.Context, d *sche arbitrarySecretMetadataIntf, response, err := secretsManagerClient.GetSecretMetadataWithContext(context, getSecretMetadataOptions) if err != nil { log.Printf("[DEBUG] GetSecretMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretMetadataWithContext failed %s\n%s", err, response), fmt.Sprintf("(Data) %s_metadata", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } arbitrarySecretMetadata := arbitrarySecretMetadataIntf.(*secretsmanagerv2.ArbitrarySecretMetadata) @@ -142,19 +144,23 @@ func dataSourceIbmSmArbitrarySecretMetadataRead(context context.Context, d *sche d.SetId(fmt.Sprintf("%s/%s/%s", region, instanceId, secretId)) if err = d.Set("created_by", arbitrarySecretMetadata.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), fmt.Sprintf("(Data) %s_metadata", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s_metadata", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(arbitrarySecretMetadata.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), fmt.Sprintf("(Data) %s_metadata", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("crn", arbitrarySecretMetadata.Crn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crn"), fmt.Sprintf("(Data) %s_metadata", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if arbitrarySecretMetadata.CustomMetadata != nil { @@ -164,55 +170,68 @@ func dataSourceIbmSmArbitrarySecretMetadataRead(context context.Context, d *sche } if err = d.Set("custom_metadata", flex.Flatten(convertedMap)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s_metadata", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s_metadata", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } } if err = d.Set("description", arbitrarySecretMetadata.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), fmt.Sprintf("(Data) %s_metadata", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("downloaded", arbitrarySecretMetadata.Downloaded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting downloaded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting downloaded"), fmt.Sprintf("(Data) %s_metadata", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("locks_total", flex.IntValue(arbitrarySecretMetadata.LocksTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locks_total"), fmt.Sprintf("(Data) %s_metadata", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("name", arbitrarySecretMetadata.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), fmt.Sprintf("(Data) %s_metadata", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_group_id", arbitrarySecretMetadata.SecretGroupID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_group_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_group_id"), fmt.Sprintf("(Data) %s_metadata", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", arbitrarySecretMetadata.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), fmt.Sprintf("(Data) %s_metadata", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state", flex.IntValue(arbitrarySecretMetadata.State)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state"), fmt.Sprintf("(Data) %s_metadata", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state_description", arbitrarySecretMetadata.StateDescription); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state_description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state_description"), fmt.Sprintf("(Data) %s_metadata", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(arbitrarySecretMetadata.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), fmt.Sprintf("(Data) %s_metadata", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("versions_total", flex.IntValue(arbitrarySecretMetadata.VersionsTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting versions_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting versions_total"), fmt.Sprintf("(Data) %s_metadata", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("expiration_date", DateTimeToRFC3339(arbitrarySecretMetadata.ExpirationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting expiration_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting expiration_date"), fmt.Sprintf("(Data) %s_metadata", ArbitrarySecretResourceName), "read") + return tfErr.GetDiag() } return nil diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_configurations.go b/ibm/service/secretsmanager/data_source_ibm_sm_configurations.go index 8b950a1d17..7bf7d41211 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_configurations.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_configurations.go @@ -6,6 +6,7 @@ package secretsmanager import ( "context" "fmt" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "log" "time" @@ -201,7 +202,8 @@ func DataSourceIbmSmConfigurations() *schema.Resource { func dataSourceIbmSmConfigurationsRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", ConfigurationsResourceName), "read") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -231,13 +233,15 @@ func dataSourceIbmSmConfigurationsRead(context context.Context, d *schema.Resour var pager *secretsmanagerv2.ConfigurationsPager pager, err = secretsManagerClient.NewConfigurationsPager(listConfigurationsOptions) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", ConfigurationsResourceName), "read") + return tfErr.GetDiag() } allItems, err := pager.GetAll() if err != nil { log.Printf("[DEBUG] ConfigurationsPager.GetAll() failed %s", err) - return diag.FromErr(fmt.Errorf("ConfigurationsPager.GetAll() failed %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("ConfigurationsPager.GetAll() %s", err), fmt.Sprintf("(Data) %s", ConfigurationsResourceName), "read") + return tfErr.GetDiag() } d.SetId(dataSourceIbmSmConfigurationsID(d)) @@ -246,16 +250,19 @@ func dataSourceIbmSmConfigurationsRead(context context.Context, d *schema.Resour for _, modelItem := range allItems { modelMap, err := dataSourceIbmSmConfigurationsConfigurationMetadataToMap(modelItem) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", ConfigurationsResourceName), "read") + return tfErr.GetDiag() } mapSlice = append(mapSlice, modelMap) } if err = d.Set("configurations", mapSlice); err != nil { - return diag.FromErr(fmt.Errorf("Error setting configurations %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting configurations"), fmt.Sprintf("(Data) %s", ConfigurationsResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("total_count", len(mapSlice)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting total_count"), fmt.Sprintf("(Data) %s", ConfigurationsResourceName), "read") + return tfErr.GetDiag() } return nil diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_en_registration.go b/ibm/service/secretsmanager/data_source_ibm_sm_en_registration.go index 913ba863b1..928a7bf6ef 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_en_registration.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_en_registration.go @@ -6,6 +6,7 @@ package secretsmanager import ( "context" "fmt" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "log" @@ -31,7 +32,8 @@ func DataSourceIbmSmEnRegistration() *schema.Resource { func dataSourceIbmSmEnRegistrationRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", EnRegistrationResourceName), "read") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -43,16 +45,19 @@ func dataSourceIbmSmEnRegistrationRead(context context.Context, d *schema.Resour notificationsRegistration, response, err := secretsManagerClient.GetNotificationsRegistrationWithContext(context, getNotificationsRegistrationOptions) if err != nil { log.Printf("[DEBUG] GetNotificationsRegistrationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetNotificationsRegistrationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetNotificationsRegistrationWithContext failed %s\n%s", err, response), fmt.Sprintf("(Data) %s", EnRegistrationResourceName), "read") + return tfErr.GetDiag() } d.SetId(fmt.Sprintf("%s/%s", region, instanceId)) if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s", EnRegistrationResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("event_notifications_instance_crn", notificationsRegistration.EventNotificationsInstanceCrn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting event_notifications_instance_crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting event_notifications_instance_crn"), fmt.Sprintf("(Data) %s", EnRegistrationResourceName), "read") + return tfErr.GetDiag() } return nil diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_iam_credentials_configuration.go b/ibm/service/secretsmanager/data_source_ibm_sm_iam_credentials_configuration.go index ab8f4277de..d6e80959ee 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_iam_credentials_configuration.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_iam_credentials_configuration.go @@ -6,6 +6,7 @@ package secretsmanager import ( "context" "fmt" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "log" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" @@ -63,7 +64,8 @@ func DataSourceIbmSmIamCredentialsConfiguration() *schema.Resource { func dataSourceIbmSmIamCredentialsConfigurationRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", IAMCredentialsConfigResourceName), "read") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -77,37 +79,45 @@ func dataSourceIbmSmIamCredentialsConfigurationRead(context context.Context, d * iAMCredentialsConfigurationIntf, response, err := secretsManagerClient.GetConfigurationWithContext(context, getConfigurationOptions) if err != nil { log.Printf("[DEBUG] GetConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetConfigurationWithContext failed %s\n%s", err, response), fmt.Sprintf("(Data) %s", IAMCredentialsConfigResourceName), "read") + return tfErr.GetDiag() } iAMCredentialsConfiguration := iAMCredentialsConfigurationIntf.(*secretsmanagerv2.IAMCredentialsConfiguration) d.SetId(fmt.Sprintf("%s/%s/%s", region, instanceId, *getConfigurationOptions.Name)) if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s", IAMCredentialsConfigResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("config_type", iAMCredentialsConfiguration.ConfigType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting config_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting config_type"), fmt.Sprintf("(Data) %s", IAMCredentialsConfigResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", iAMCredentialsConfiguration.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), fmt.Sprintf("(Data) %s", IAMCredentialsConfigResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_by", iAMCredentialsConfiguration.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), fmt.Sprintf("(Data) %s", IAMCredentialsConfigResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(iAMCredentialsConfiguration.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), fmt.Sprintf("(Data) %s", IAMCredentialsConfigResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(iAMCredentialsConfiguration.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), fmt.Sprintf("(Data) %s", IAMCredentialsConfigResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("api_key", iAMCredentialsConfiguration.ApiKey); err != nil { - return diag.FromErr(fmt.Errorf("Error setting api_key: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting api_key"), fmt.Sprintf("(Data) %s", IAMCredentialsConfigResourceName), "read") + return tfErr.GetDiag() } return nil diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_iam_credentials_secret.go b/ibm/service/secretsmanager/data_source_ibm_sm_iam_credentials_secret.go index 2fc4b0929a..6c0a18e03e 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_iam_credentials_secret.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_iam_credentials_secret.go @@ -193,8 +193,7 @@ func DataSourceIbmSmIamCredentialsSecret() *schema.Resource { } func dataSourceIbmSmIamCredentialsSecretRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - - iAMCredentialsSecretIntf, region, instanceId, diagError := getSecretByIdOrByName(context, d, meta, IAMCredentialsSecretType) + iAMCredentialsSecretIntf, region, instanceId, diagError := getSecretByIdOrByName(context, d, meta, IAMCredentialsSecretType, IAMCredentialsSecretResourceName) if diagError != nil { return diagError } @@ -204,18 +203,22 @@ func dataSourceIbmSmIamCredentialsSecretRead(context context.Context, d *schema. var err error if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_by", iAMCredentialsSecret.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(iAMCredentialsSecret.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("crn", iAMCredentialsSecret.Crn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crn"), fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if iAMCredentialsSecret.CustomMetadata != nil { @@ -225,96 +228,118 @@ func dataSourceIbmSmIamCredentialsSecretRead(context context.Context, d *schema. } if err = d.Set("custom_metadata", flex.Flatten(convertedMap)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } } if err = d.Set("description", iAMCredentialsSecret.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("downloaded", iAMCredentialsSecret.Downloaded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting downloaded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting downloaded"), fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("locks_total", flex.IntValue(iAMCredentialsSecret.LocksTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locks_total"), fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("name", iAMCredentialsSecret.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_group_id", iAMCredentialsSecret.SecretGroupID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_group_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_group_id"), fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", iAMCredentialsSecret.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state", flex.IntValue(iAMCredentialsSecret.State)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state"), fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state_description", iAMCredentialsSecret.StateDescription); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state_description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state_description"), fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(iAMCredentialsSecret.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("versions_total", flex.IntValue(iAMCredentialsSecret.VersionsTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting versions_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting versions_total"), fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("ttl", iAMCredentialsSecret.TTL); err != nil { - return diag.FromErr(fmt.Errorf("Error setting ttl: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting ttl"), fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("api_key_id", iAMCredentialsSecret.ApiKeyID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting api_key_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting api_key_id"), fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("service_id", iAMCredentialsSecret.ServiceID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting service_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting service_id"), fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("service_id_is_static", iAMCredentialsSecret.ServiceIdIsStatic); err != nil { - return diag.FromErr(fmt.Errorf("Error setting service_id_is_static: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting service_id_is_static"), fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("reuse_api_key", iAMCredentialsSecret.ReuseApiKey); err != nil { - return diag.FromErr(fmt.Errorf("Error setting reuse_api_key: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting reuse_api_key"), fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } rotation := []map[string]interface{}{} if iAMCredentialsSecret.Rotation != nil { modelMap, err := dataSourceIbmSmIamCredentialsSecretRotationPolicyToMap(iAMCredentialsSecret.Rotation) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } rotation = append(rotation, modelMap) } if err = d.Set("rotation", rotation); err != nil { - return diag.FromErr(fmt.Errorf("Error setting rotation %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting rotation"), fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("next_rotation_date", DateTimeToRFC3339(iAMCredentialsSecret.NextRotationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting next_rotation_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting next_rotation_date"), fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("api_key", iAMCredentialsSecret.ApiKey); err != nil { - return diag.FromErr(fmt.Errorf("Error setting api_key: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting api_key"), fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if iAMCredentialsSecret.ExpirationDate != nil { if err = d.Set("expiration_date", DateTimeToRFC3339(iAMCredentialsSecret.ExpirationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting expiration_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting expiration_date"), fmt.Sprintf("(Data) %s", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } } return nil diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_iam_credentials_secret_metadata.go b/ibm/service/secretsmanager/data_source_ibm_sm_iam_credentials_secret_metadata.go index e4193e2ee6..0bca907e28 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_iam_credentials_secret_metadata.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_iam_credentials_secret_metadata.go @@ -181,7 +181,8 @@ func DataSourceIbmSmIamCredentialsSecretMetadata() *schema.Resource { func dataSourceIbmSmIamCredentialsSecretMetadataRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -196,25 +197,30 @@ func dataSourceIbmSmIamCredentialsSecretMetadataRead(context context.Context, d iAMCredentialsSecretMetadataIntf, response, err := secretsManagerClient.GetSecretMetadataWithContext(context, getSecretMetadataOptions) if err != nil { log.Printf("[DEBUG] GetSecretMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretMetadataWithContext failed %s\n%s", err, response), fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } iAMCredentialsSecretMetadata := iAMCredentialsSecretMetadataIntf.(*secretsmanagerv2.IAMCredentialsSecretMetadata) d.SetId(fmt.Sprintf("%s/%s/%s", region, instanceId, secretId)) if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_by", iAMCredentialsSecretMetadata.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(iAMCredentialsSecretMetadata.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("crn", iAMCredentialsSecretMetadata.Crn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crn"), fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if iAMCredentialsSecretMetadata.CustomMetadata != nil { @@ -224,92 +230,113 @@ func dataSourceIbmSmIamCredentialsSecretMetadataRead(context context.Context, d } if err = d.Set("custom_metadata", flex.Flatten(convertedMap)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } } if err = d.Set("description", iAMCredentialsSecretMetadata.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("downloaded", iAMCredentialsSecretMetadata.Downloaded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting downloaded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting downloaded"), fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("locks_total", flex.IntValue(iAMCredentialsSecretMetadata.LocksTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locks_total"), fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("name", iAMCredentialsSecretMetadata.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_group_id", iAMCredentialsSecretMetadata.SecretGroupID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_group_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_group_id"), fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", iAMCredentialsSecretMetadata.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state", flex.IntValue(iAMCredentialsSecretMetadata.State)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state"), fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state_description", iAMCredentialsSecretMetadata.StateDescription); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state_description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state_description"), fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(iAMCredentialsSecretMetadata.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("versions_total", flex.IntValue(iAMCredentialsSecretMetadata.VersionsTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting versions_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting versions_total"), fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("ttl", iAMCredentialsSecretMetadata.TTL); err != nil { - return diag.FromErr(fmt.Errorf("Error setting ttl: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting ttl"), fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("api_key_id", iAMCredentialsSecretMetadata.ApiKeyID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting api_key_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting api_key_id"), fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("service_id", iAMCredentialsSecretMetadata.ServiceID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting service_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting service_id"), fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("service_id_is_static", iAMCredentialsSecretMetadata.ServiceIdIsStatic); err != nil { - return diag.FromErr(fmt.Errorf("Error setting service_id_is_static: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting service_id_is_static"), fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("reuse_api_key", iAMCredentialsSecretMetadata.ReuseApiKey); err != nil { - return diag.FromErr(fmt.Errorf("Error setting reuse_api_key: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting reuse_api_key"), fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } rotation := []map[string]interface{}{} if iAMCredentialsSecretMetadata.Rotation != nil { modelMap, err := dataSourceIbmSmIamCredentialsSecretMetadataRotationPolicyToMap(iAMCredentialsSecretMetadata.Rotation) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } rotation = append(rotation, modelMap) } if err = d.Set("rotation", rotation); err != nil { - return diag.FromErr(fmt.Errorf("Error setting rotation %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting rotation"), fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("next_rotation_date", DateTimeToRFC3339(iAMCredentialsSecretMetadata.NextRotationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting next_rotation_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting next_rotation_date"), fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if iAMCredentialsSecretMetadata.ExpirationDate != nil { if err = d.Set("expiration_date", DateTimeToRFC3339(iAMCredentialsSecretMetadata.ExpirationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting expiration_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting expiration_date"), fmt.Sprintf("(Data) %s_metadata", IAMCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } } diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_imported_certificate.go b/ibm/service/secretsmanager/data_source_ibm_sm_imported_certificate.go index d951300505..1a0310db03 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_imported_certificate.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_imported_certificate.go @@ -197,7 +197,7 @@ func DataSourceIbmSmImportedCertificate() *schema.Resource { } func dataSourceIbmSmImportedCertificateRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - importedCertificateIntf, region, instanceId, diagError := getSecretByIdOrByName(context, d, meta, ImportedCertSecretType) + importedCertificateIntf, region, instanceId, diagError := getSecretByIdOrByName(context, d, meta, ImportedCertSecretType, ImportedCertSecretResourceName) if diagError != nil { return diagError } @@ -207,18 +207,22 @@ func dataSourceIbmSmImportedCertificateRead(context context.Context, d *schema.R var err error if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_by", importedCertificate.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(importedCertificate.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("crn", importedCertificate.Crn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crn"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if importedCertificate.CustomMetadata != nil { @@ -228,107 +232,132 @@ func dataSourceIbmSmImportedCertificateRead(context context.Context, d *schema.R } if err = d.Set("custom_metadata", flex.Flatten(convertedMap)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } } if err = d.Set("description", importedCertificate.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("downloaded", importedCertificate.Downloaded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting downloaded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting downloaded"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("locks_total", flex.IntValue(importedCertificate.LocksTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locks_total"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("name", importedCertificate.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_group_id", importedCertificate.SecretGroupID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_group_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_group_id"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", importedCertificate.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state", flex.IntValue(importedCertificate.State)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state_description", importedCertificate.StateDescription); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state_description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state_description"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(importedCertificate.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("versions_total", flex.IntValue(importedCertificate.VersionsTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting versions_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting versions_total"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("signing_algorithm", importedCertificate.SigningAlgorithm); err != nil { - return diag.FromErr(fmt.Errorf("Error setting signing_algorithm: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting signing_algorithm"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("common_name", importedCertificate.CommonName); err != nil { - return diag.FromErr(fmt.Errorf("Error setting common_name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting common_name"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("expiration_date", DateTimeToRFC3339(importedCertificate.ExpirationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting expiration_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting expiration_date"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("intermediate_included", importedCertificate.IntermediateIncluded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting intermediate_included: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting intermediate_included"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("issuer", importedCertificate.Issuer); err != nil { - return diag.FromErr(fmt.Errorf("Error setting issuer: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting issuer"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("key_algorithm", importedCertificate.KeyAlgorithm); err != nil { - return diag.FromErr(fmt.Errorf("Error setting key_algorithm: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting key_algorithm"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("private_key_included", importedCertificate.PrivateKeyIncluded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting private_key_included: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting private_key_included"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("serial_number", importedCertificate.SerialNumber); err != nil { - return diag.FromErr(fmt.Errorf("Error setting serial_number: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting serial_number"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } validity := []map[string]interface{}{} if importedCertificate.Validity != nil { modelMap, err := dataSourceIbmSmImportedCertificateCertificateValidityToMap(importedCertificate.Validity) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } validity = append(validity, modelMap) } if err = d.Set("validity", validity); err != nil { - return diag.FromErr(fmt.Errorf("Error setting validity %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting validity"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("certificate", importedCertificate.Certificate); err != nil { - return diag.FromErr(fmt.Errorf("Error setting certificate: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting certificate"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("intermediate", importedCertificate.Intermediate); err != nil { - return diag.FromErr(fmt.Errorf("Error setting intermediate: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting intermediate"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("private_key", importedCertificate.PrivateKey); err != nil { - return diag.FromErr(fmt.Errorf("Error setting private_key: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting private_key"), fmt.Sprintf("(Data) %s", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } return nil diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_imported_certificate_metadata.go b/ibm/service/secretsmanager/data_source_ibm_sm_imported_certificate_metadata.go index deb8aeb65d..d44b056af8 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_imported_certificate_metadata.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_imported_certificate_metadata.go @@ -173,7 +173,8 @@ func DataSourceIbmSmImportedCertificateMetadata() *schema.Resource { func dataSourceIbmSmImportedCertificateMetadataRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -188,26 +189,31 @@ func dataSourceIbmSmImportedCertificateMetadataRead(context context.Context, d * importedCertificateMetadataIntf, response, err := secretsManagerClient.GetSecretMetadataWithContext(context, getSecretMetadataOptions) if err != nil { log.Printf("[DEBUG] GetSecretMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretMetadataWithContext failed %s\n%s", err, response), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } importedCertificateMetadata := importedCertificateMetadataIntf.(*secretsmanagerv2.ImportedCertificateMetadata) d.SetId(fmt.Sprintf("%s/%s/%s", region, instanceId, secretId)) if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_by", importedCertificateMetadata.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(importedCertificateMetadata.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("crn", importedCertificateMetadata.Crn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crn"), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if importedCertificateMetadata.CustomMetadata != nil { @@ -217,95 +223,117 @@ func dataSourceIbmSmImportedCertificateMetadataRead(context context.Context, d * } if err = d.Set("custom_metadata", flex.Flatten(convertedMap)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } } if err = d.Set("description", importedCertificateMetadata.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("downloaded", importedCertificateMetadata.Downloaded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting downloaded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting downloaded"), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("locks_total", flex.IntValue(importedCertificateMetadata.LocksTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locks_total"), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("name", importedCertificateMetadata.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_group_id", importedCertificateMetadata.SecretGroupID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_group_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_group_id"), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", importedCertificateMetadata.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state", flex.IntValue(importedCertificateMetadata.State)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state"), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state_description", importedCertificateMetadata.StateDescription); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state_description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state_description"), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(importedCertificateMetadata.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("versions_total", flex.IntValue(importedCertificateMetadata.VersionsTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting versions_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting versions_total"), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("signing_algorithm", importedCertificateMetadata.SigningAlgorithm); err != nil { - return diag.FromErr(fmt.Errorf("Error setting signing_algorithm: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting signing_algorithm"), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("common_name", importedCertificateMetadata.CommonName); err != nil { - return diag.FromErr(fmt.Errorf("Error setting common_name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting common_name"), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("expiration_date", DateTimeToRFC3339(importedCertificateMetadata.ExpirationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting expiration_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting expiration_date"), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("intermediate_included", importedCertificateMetadata.IntermediateIncluded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting intermediate_included: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting intermediate_included"), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("issuer", importedCertificateMetadata.Issuer); err != nil { - return diag.FromErr(fmt.Errorf("Error setting issuer: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting issuer"), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("key_algorithm", importedCertificateMetadata.KeyAlgorithm); err != nil { - return diag.FromErr(fmt.Errorf("Error setting key_algorithm: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting key_algorithm"), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("private_key_included", importedCertificateMetadata.PrivateKeyIncluded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting private_key_included: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting private_key_included"), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("serial_number", importedCertificateMetadata.SerialNumber); err != nil { - return diag.FromErr(fmt.Errorf("Error setting serial_number: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting serial_number"), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } validity := []map[string]interface{}{} if importedCertificateMetadata.Validity != nil { modelMap, err := dataSourceIbmSmImportedCertificateMetadataCertificateValidityToMap(importedCertificateMetadata.Validity) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } validity = append(validity, modelMap) } if err = d.Set("validity", validity); err != nil { - return diag.FromErr(fmt.Errorf("Error setting validity %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting validity"), fmt.Sprintf("(Data) %s_metadata", ImportedCertSecretResourceName), "read") + return tfErr.GetDiag() } return nil diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_kv_secret.go b/ibm/service/secretsmanager/data_source_ibm_sm_kv_secret.go index 49e78f615f..8ad39c1e08 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_kv_secret.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_kv_secret.go @@ -130,7 +130,7 @@ func DataSourceIbmSmKvSecret() *schema.Resource { func dataSourceIbmSmKvSecretRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - secret, region, instanceId, diagError := getSecretByIdOrByName(context, d, meta, KvSecretType) + secret, region, instanceId, diagError := getSecretByIdOrByName(context, d, meta, KvSecretType, KvSecretResourceName) if diagError != nil { return diagError } @@ -140,19 +140,23 @@ func dataSourceIbmSmKvSecretRead(context context.Context, d *schema.ResourceData d.SetId(fmt.Sprintf("%s/%s/%s", region, instanceId, *kVSecret.ID)) var err error if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_by", kVSecret.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), fmt.Sprintf("(Data) %s", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(kVSecret.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), fmt.Sprintf("(Data) %s", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("crn", kVSecret.Crn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crn"), fmt.Sprintf("(Data) %s", KvSecretResourceName), "read") + return tfErr.GetDiag() } if kVSecret.CustomMetadata != nil { @@ -162,51 +166,63 @@ func dataSourceIbmSmKvSecretRead(context context.Context, d *schema.ResourceData } if err = d.Set("custom_metadata", flex.Flatten(convertedMap)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s", KvSecretResourceName), "read") + return tfErr.GetDiag() } } if err = d.Set("description", kVSecret.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), fmt.Sprintf("(Data) %s", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("downloaded", kVSecret.Downloaded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting downloaded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting downloaded"), fmt.Sprintf("(Data) %s", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("locks_total", flex.IntValue(kVSecret.LocksTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locks_total"), fmt.Sprintf("(Data) %s", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("name", kVSecret.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), fmt.Sprintf("(Data) %s", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_group_id", kVSecret.SecretGroupID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_group_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_group_id"), fmt.Sprintf("(Data) %s", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", kVSecret.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), fmt.Sprintf("(Data) %s", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state", flex.IntValue(kVSecret.State)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state"), fmt.Sprintf("(Data) %s", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state_description", kVSecret.StateDescription); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state_description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state_description"), fmt.Sprintf("(Data) %s", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(kVSecret.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), fmt.Sprintf("(Data) %s", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("versions_total", flex.IntValue(kVSecret.VersionsTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting versions_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting versions_total"), fmt.Sprintf("(Data) %s", KvSecretResourceName), "read") + return tfErr.GetDiag() } if kVSecret.Data != nil { @@ -216,10 +232,12 @@ func dataSourceIbmSmKvSecretRead(context context.Context, d *schema.ResourceData } if err = d.Set("data", flex.Flatten(convertedMap)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting data: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting data"), fmt.Sprintf("(Data) %s", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err != nil { - return diag.FromErr(fmt.Errorf("Error setting data %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting data"), fmt.Sprintf("(Data) %s", KvSecretResourceName), "read") + return tfErr.GetDiag() } } diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_kv_secret_metadata.go b/ibm/service/secretsmanager/data_source_ibm_sm_kv_secret_metadata.go index b36a9376fc..11f82b269e 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_kv_secret_metadata.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_kv_secret_metadata.go @@ -114,7 +114,8 @@ func DataSourceIbmSmKvSecretMetadata() *schema.Resource { func dataSourceIbmSmKvSecretMetadataRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s_metadata", KvSecretResourceName), "read") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -129,26 +130,31 @@ func dataSourceIbmSmKvSecretMetadataRead(context context.Context, d *schema.Reso kVSecretMetadataIntf, response, err := secretsManagerClient.GetSecretMetadataWithContext(context, getSecretMetadataOptions) if err != nil { log.Printf("[DEBUG] GetSecretMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretMetadataWithContext failed %s\n%s", err, response), fmt.Sprintf("(Data) %s_metadata", KvSecretResourceName), "read") + return tfErr.GetDiag() } kVSecretMetadata := kVSecretMetadataIntf.(*secretsmanagerv2.KVSecretMetadata) d.SetId(fmt.Sprintf("%s/%s/%s", region, instanceId, secretId)) if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s_metadata", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_by", kVSecretMetadata.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), fmt.Sprintf("(Data) %s_metadata", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(kVSecretMetadata.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), fmt.Sprintf("(Data) %s_metadata", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("crn", kVSecretMetadata.Crn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crn"), fmt.Sprintf("(Data) %s_metadata", KvSecretResourceName), "read") + return tfErr.GetDiag() } if kVSecretMetadata.CustomMetadata != nil { @@ -158,51 +164,63 @@ func dataSourceIbmSmKvSecretMetadataRead(context context.Context, d *schema.Reso } if err = d.Set("custom_metadata", flex.Flatten(convertedMap)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s_metadata", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s_metadata", KvSecretResourceName), "read") + return tfErr.GetDiag() } } if err = d.Set("description", kVSecretMetadata.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), fmt.Sprintf("(Data) %s_metadata", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("downloaded", kVSecretMetadata.Downloaded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting downloaded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting downloaded"), fmt.Sprintf("(Data) %s_metadata", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("locks_total", flex.IntValue(kVSecretMetadata.LocksTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locks_total"), fmt.Sprintf("(Data) %s_metadata", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("name", kVSecretMetadata.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), fmt.Sprintf("(Data) %s_metadata", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_group_id", kVSecretMetadata.SecretGroupID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_group_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_group_id"), fmt.Sprintf("(Data) %s_metadata", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", kVSecretMetadata.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), fmt.Sprintf("(Data) %s_metadata", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state", flex.IntValue(kVSecretMetadata.State)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state"), fmt.Sprintf("(Data) %s_metadata", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state_description", kVSecretMetadata.StateDescription); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state_description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state_description"), fmt.Sprintf("(Data) %s_metadata", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(kVSecretMetadata.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), fmt.Sprintf("(Data) %s_metadata", KvSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("versions_total", flex.IntValue(kVSecretMetadata.VersionsTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting versions_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting versions_total"), fmt.Sprintf("(Data) %s_metadata", KvSecretResourceName), "read") + return tfErr.GetDiag() } return nil diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_private_certificate.go b/ibm/service/secretsmanager/data_source_ibm_sm_private_certificate.go index 59ce4a1fa8..d8aa2181a7 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_private_certificate.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_private_certificate.go @@ -253,7 +253,7 @@ func DataSourceIbmSmPrivateCertificate() *schema.Resource { } func dataSourceIbmSmPrivateCertificateRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - privateCertificateIntf, region, instanceId, diagError := getSecretByIdOrByName(context, d, meta, PrivateCertSecretType) + privateCertificateIntf, region, instanceId, diagError := getSecretByIdOrByName(context, d, meta, PrivateCertSecretType, PrivateCertSecretResourceName) if diagError != nil { return diagError } @@ -264,19 +264,23 @@ func dataSourceIbmSmPrivateCertificateRead(context context.Context, d *schema.Re var err error if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_by", privateCertificate.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(privateCertificate.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("crn", privateCertificate.Crn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crn"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if privateCertificate.CustomMetadata != nil { @@ -286,131 +290,161 @@ func dataSourceIbmSmPrivateCertificateRead(context context.Context, d *schema.Re } if err = d.Set("custom_metadata", flex.Flatten(convertedMap)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } } if err = d.Set("description", privateCertificate.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("downloaded", privateCertificate.Downloaded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting downloaded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting downloaded"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("locks_total", flex.IntValue(privateCertificate.LocksTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locks_total"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("name", privateCertificate.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_group_id", privateCertificate.SecretGroupID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_group_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_group_id"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", privateCertificate.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state", flex.IntValue(privateCertificate.State)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state_description", privateCertificate.StateDescription); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state_description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state_description"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(privateCertificate.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("versions_total", flex.IntValue(privateCertificate.VersionsTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting versions_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting versions_total"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("signing_algorithm", privateCertificate.SigningAlgorithm); err != nil { - return diag.FromErr(fmt.Errorf("Error setting signing_algorithm: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting signing_algorithm"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("certificate_authority", privateCertificate.CertificateAuthority); err != nil { - return diag.FromErr(fmt.Errorf("Error setting certificate_authority: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting certificate_authority"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("certificate_template", privateCertificate.CertificateTemplate); err != nil { - return diag.FromErr(fmt.Errorf("Error setting certificate_template: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting certificate_template"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("common_name", privateCertificate.CommonName); err != nil { - return diag.FromErr(fmt.Errorf("Error setting common_name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting common_name"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("expiration_date", DateTimeToRFC3339(privateCertificate.ExpirationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting expiration_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting expiration_date"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("issuer", privateCertificate.Issuer); err != nil { - return diag.FromErr(fmt.Errorf("Error setting issuer: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting issuer"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("key_algorithm", privateCertificate.KeyAlgorithm); err != nil { - return diag.FromErr(fmt.Errorf("Error setting key_algorithm: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting key_algorithm"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("next_rotation_date", DateTimeToRFC3339(privateCertificate.NextRotationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting next_rotation_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting next_rotation_date"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } rotation := []map[string]interface{}{} if privateCertificate.Rotation != nil { modelMap, err := dataSourceIbmSmPrivateCertificateRotationPolicyToMap(privateCertificate.Rotation) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } rotation = append(rotation, modelMap) } if err = d.Set("rotation", rotation); err != nil { - return diag.FromErr(fmt.Errorf("Error setting rotation %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting rotation"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("serial_number", privateCertificate.SerialNumber); err != nil { - return diag.FromErr(fmt.Errorf("Error setting serial_number: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting serial_number"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } validity := []map[string]interface{}{} if privateCertificate.Validity != nil { modelMap, err := dataSourceIbmSmPrivateCertificateCertificateValidityToMap(privateCertificate.Validity) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } validity = append(validity, modelMap) } if err = d.Set("validity", validity); err != nil { - return diag.FromErr(fmt.Errorf("Error setting validity %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting validity"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("revocation_time_seconds", flex.IntValue(privateCertificate.RevocationTimeSeconds)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting revocation_time_seconds: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting revocation_time_seconds"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("revocation_time_rfc3339", DateTimeToRFC3339(privateCertificate.RevocationTimeRfc3339)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting revocation_time_rfc3339: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting revocation_time_rfc3339"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("certificate", privateCertificate.Certificate); err != nil { - return diag.FromErr(fmt.Errorf("Error setting certificate: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting certificate"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("private_key", privateCertificate.PrivateKey); err != nil { - return diag.FromErr(fmt.Errorf("Error setting private_key: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting private_key"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("issuing_ca", privateCertificate.IssuingCa); err != nil { - return diag.FromErr(fmt.Errorf("Error setting issuing_ca: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting issuing_ca"), fmt.Sprintf("(Data) %s", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } return nil diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_private_certificate_configuration_intermediate_ca.go b/ibm/service/secretsmanager/data_source_ibm_sm_private_certificate_configuration_intermediate_ca.go index 43c50c46a8..1db43ac87c 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_private_certificate_configuration_intermediate_ca.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_private_certificate_configuration_intermediate_ca.go @@ -309,7 +309,8 @@ func DataSourceIbmSmPrivateCertificateConfigurationIntermediateCA() *schema.Reso func dataSourceIbmSmPrivateCertificateConfigurationIntermediateCARead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -323,104 +324,128 @@ func dataSourceIbmSmPrivateCertificateConfigurationIntermediateCARead(context co configurationIntf, response, err := secretsManagerClient.GetConfigurationWithContext(context, getConfigurationOptions) if err != nil { log.Printf("[DEBUG] GetConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetConfigurationWithContext failed %s\n%s", err, response), fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } privateCertificateConfigurationIntermediateCA := configurationIntf.(*secretsmanagerv2.PrivateCertificateConfigurationIntermediateCA) d.SetId(fmt.Sprintf("%s/%s/%s", region, instanceId, *getConfigurationOptions.Name)) if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("config_type", privateCertificateConfigurationIntermediateCA.ConfigType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting config_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting config_type"), fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", privateCertificateConfigurationIntermediateCA.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("max_ttl_seconds", flex.IntValue(privateCertificateConfigurationIntermediateCA.MaxTtlSeconds)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting max_ttl_seconds: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting max_ttl_seconds"), fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("signing_method", privateCertificateConfigurationIntermediateCA.SigningMethod); err != nil { - return diag.FromErr(fmt.Errorf("Error setting signing_method: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting signing_method"), fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("issuer", privateCertificateConfigurationIntermediateCA.Issuer); err != nil { - return diag.FromErr(fmt.Errorf("Error setting issuer: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting issuer"), fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("crl_expiry_seconds", flex.IntValue(privateCertificateConfigurationIntermediateCA.CrlExpirySeconds)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crl_expiry_seconds: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crl_expiry_seconds"), fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("crl_disable", privateCertificateConfigurationIntermediateCA.CrlDisable); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crl_disable: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crl_disable"), fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("crl_distribution_points_encoded", privateCertificateConfigurationIntermediateCA.CrlDistributionPointsEncoded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crl_distribution_points_encoded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crl_distribution_points_encoded"), fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("issuing_certificates_urls_encoded", privateCertificateConfigurationIntermediateCA.IssuingCertificatesUrlsEncoded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting issuing_certificates_urls_encoded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting issuing_certificates_urls_encoded"), fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("common_name", privateCertificateConfigurationIntermediateCA.CommonName); err != nil { - return diag.FromErr(fmt.Errorf("Error setting common_name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting common_name"), fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("ip_sans", privateCertificateConfigurationIntermediateCA.IpSans); err != nil { - return diag.FromErr(fmt.Errorf("Error setting ip_sans: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting ip_sans"), fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("uri_sans", privateCertificateConfigurationIntermediateCA.UriSans); err != nil { - return diag.FromErr(fmt.Errorf("Error setting uri_sans: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting uri_sans"), fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("format", privateCertificateConfigurationIntermediateCA.Format); err != nil { - return diag.FromErr(fmt.Errorf("Error setting format: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting format"), fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("private_key_format", privateCertificateConfigurationIntermediateCA.PrivateKeyFormat); err != nil { - return diag.FromErr(fmt.Errorf("Error setting private_key_format: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting private_key_format"), fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("key_type", privateCertificateConfigurationIntermediateCA.KeyType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting key_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting key_type"), fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("key_bits", flex.IntValue(privateCertificateConfigurationIntermediateCA.KeyBits)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting key_bits: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting key_bits"), fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("exclude_cn_from_sans", privateCertificateConfigurationIntermediateCA.ExcludeCnFromSans); err != nil { - return diag.FromErr(fmt.Errorf("Error setting exclude_cn_from_sans: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting exclude_cn_from_sans"), fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("serial_number", privateCertificateConfigurationIntermediateCA.SerialNumber); err != nil { - return diag.FromErr(fmt.Errorf("Error setting serial_number: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting serial_number"), fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("status", privateCertificateConfigurationIntermediateCA.Status); err != nil { - return diag.FromErr(fmt.Errorf("Error setting status: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting status"), fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("expiration_date", DateTimeToRFC3339(privateCertificateConfigurationIntermediateCA.ExpirationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting expiration_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting expiration_date"), fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } if privateCertificateConfigurationIntermediateCA.CryptoKey != nil { cryptoKeyMap, err := resourceIbmSmPrivateCertificateConfigurationCryptoKeyToMap(privateCertificateConfigurationIntermediateCA.CryptoKey) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } if len(cryptoKeyMap) > 0 { if err = d.Set("crypto_key", []map[string]interface{}{cryptoKeyMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crypto_key: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crypto_key"), fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } } } @@ -429,12 +454,14 @@ func dataSourceIbmSmPrivateCertificateConfigurationIntermediateCARead(context co if privateCertificateConfigurationIntermediateCA.Data != nil { modelMap, err := dataSourceIbmSmPrivateCertificateConfigurationIntermediateCAPrivateCertificateCADataToMap(privateCertificateConfigurationIntermediateCA.Data) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } data = append(data, modelMap) } if err = d.Set("data", data); err != nil { - return diag.FromErr(fmt.Errorf("Error setting data %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting data"), fmt.Sprintf("(Data) %s", PrivateCertConfigIntermediateCAResourceName), "read") + return tfErr.GetDiag() } return nil diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_private_certificate_configuration_root_ca.go b/ibm/service/secretsmanager/data_source_ibm_sm_private_certificate_configuration_root_ca.go index 68a90a5690..a415d6efa3 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_private_certificate_configuration_root_ca.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_private_certificate_configuration_root_ca.go @@ -333,7 +333,8 @@ func DataSourceIbmSmPrivateCertificateConfigurationRootCA() *schema.Resource { func dataSourceIbmSmPrivateCertificateConfigurationRootCARead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -347,7 +348,8 @@ func dataSourceIbmSmPrivateCertificateConfigurationRootCARead(context context.Co privateCertificateConfigurationRootCAIntf, response, err := secretsManagerClient.GetConfigurationWithContext(context, getConfigurationOptions) if err != nil { log.Printf("[DEBUG] GetConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetConfigurationWithContext failed %s\n%s", err, response), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } privateCertificateConfigurationRootCA := privateCertificateConfigurationRootCAIntf.(*secretsmanagerv2.PrivateCertificateConfigurationRootCA) @@ -355,158 +357,194 @@ func dataSourceIbmSmPrivateCertificateConfigurationRootCARead(context context.Co d.SetId(fmt.Sprintf("%s/%s/%s", region, instanceId, *getConfigurationOptions.Name)) if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("config_type", privateCertificateConfigurationRootCA.ConfigType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting config_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting config_type"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", privateCertificateConfigurationRootCA.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_by", privateCertificateConfigurationRootCA.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(privateCertificateConfigurationRootCA.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(privateCertificateConfigurationRootCA.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("max_ttl_seconds", flex.IntValue(privateCertificateConfigurationRootCA.MaxTtlSeconds)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting max_ttl_seconds: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting max_ttl_seconds"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("crl_expiry_seconds", flex.IntValue(privateCertificateConfigurationRootCA.CrlExpirySeconds)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crl_expiry_seconds: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crl_expiry_seconds"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("crl_disable", privateCertificateConfigurationRootCA.CrlDisable); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crl_disable: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crl_disable"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("crl_distribution_points_encoded", privateCertificateConfigurationRootCA.CrlDistributionPointsEncoded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crl_distribution_points_encoded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crl_distribution_points_encoded"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("issuing_certificates_urls_encoded", privateCertificateConfigurationRootCA.IssuingCertificatesUrlsEncoded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting issuing_certificates_urls_encoded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting issuing_certificates_urls_encoded"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("common_name", privateCertificateConfigurationRootCA.CommonName); err != nil { - return diag.FromErr(fmt.Errorf("Error setting common_name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting common_name"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if privateCertificateConfigurationRootCA.AltNames != nil { if err = d.Set("alt_names", privateCertificateConfigurationRootCA.AltNames); err != nil { - return diag.FromErr(fmt.Errorf("Error setting alt_names: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting alt_names"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } } if err = d.Set("ip_sans", privateCertificateConfigurationRootCA.IpSans); err != nil { - return diag.FromErr(fmt.Errorf("Error setting ip_sans: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting ip_sans"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("uri_sans", privateCertificateConfigurationRootCA.UriSans); err != nil { - return diag.FromErr(fmt.Errorf("Error setting uri_sans: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting uri_sans"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if privateCertificateConfigurationRootCA.OtherSans != nil { if err = d.Set("other_sans", privateCertificateConfigurationRootCA.OtherSans); err != nil { - return diag.FromErr(fmt.Errorf("Error setting other_sans: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting other_sans"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } } if err = d.Set("ttl_seconds", flex.IntValue(privateCertificateConfigurationRootCA.TtlSeconds)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting ttl_seconds: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting ttl_seconds"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("format", privateCertificateConfigurationRootCA.Format); err != nil { - return diag.FromErr(fmt.Errorf("Error setting format: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting format"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("private_key_format", privateCertificateConfigurationRootCA.PrivateKeyFormat); err != nil { - return diag.FromErr(fmt.Errorf("Error setting private_key_format: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting private_key_format"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("key_type", privateCertificateConfigurationRootCA.KeyType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting key_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting key_type"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("key_bits", flex.IntValue(privateCertificateConfigurationRootCA.KeyBits)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting key_bits: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting key_bits"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("max_path_length", flex.IntValue(privateCertificateConfigurationRootCA.MaxPathLength)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting max_path_length: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting max_path_length"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("exclude_cn_from_sans", privateCertificateConfigurationRootCA.ExcludeCnFromSans); err != nil { - return diag.FromErr(fmt.Errorf("Error setting exclude_cn_from_sans: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting exclude_cn_from_sans"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if privateCertificateConfigurationRootCA.PermittedDnsDomains != nil { if err = d.Set("permitted_dns_domains", privateCertificateConfigurationRootCA.PermittedDnsDomains); err != nil { - return diag.FromErr(fmt.Errorf("Error setting permitted_dns_domains: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting permitted_dns_domains"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } } if privateCertificateConfigurationRootCA.Ou != nil { if err = d.Set("ou", privateCertificateConfigurationRootCA.Ou); err != nil { - return diag.FromErr(fmt.Errorf("Error setting ou: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting ou"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } } if privateCertificateConfigurationRootCA.Organization != nil { if err = d.Set("organization", privateCertificateConfigurationRootCA.Organization); err != nil { - return diag.FromErr(fmt.Errorf("Error setting organization: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting organization"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } } if privateCertificateConfigurationRootCA.Country != nil { if err = d.Set("country", privateCertificateConfigurationRootCA.Country); err != nil { - return diag.FromErr(fmt.Errorf("Error setting country: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting country"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } } if privateCertificateConfigurationRootCA.Locality != nil { if err = d.Set("locality", privateCertificateConfigurationRootCA.Locality); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locality: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locality"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } } if privateCertificateConfigurationRootCA.Province != nil { if err = d.Set("province", privateCertificateConfigurationRootCA.Province); err != nil { - return diag.FromErr(fmt.Errorf("Error setting province: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting province"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } } if privateCertificateConfigurationRootCA.StreetAddress != nil { if err = d.Set("street_address", privateCertificateConfigurationRootCA.StreetAddress); err != nil { - return diag.FromErr(fmt.Errorf("Error setting street_address: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting street_address"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } } if privateCertificateConfigurationRootCA.PostalCode != nil { if err = d.Set("postal_code", privateCertificateConfigurationRootCA.PostalCode); err != nil { - return diag.FromErr(fmt.Errorf("Error setting postal_code: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting postal_code"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } } if err = d.Set("serial_number", privateCertificateConfigurationRootCA.SerialNumber); err != nil { - return diag.FromErr(fmt.Errorf("Error setting serial_number: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting serial_number"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("status", privateCertificateConfigurationRootCA.Status); err != nil { - return diag.FromErr(fmt.Errorf("Error setting status: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting status"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("expiration_date", DateTimeToRFC3339(privateCertificateConfigurationRootCA.ExpirationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting expiration_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting expiration_date"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if privateCertificateConfigurationRootCA.CryptoKey != nil { cryptoKeyMap, err := resourceIbmSmPrivateCertificateConfigurationCryptoKeyToMap(privateCertificateConfigurationRootCA.CryptoKey) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if len(cryptoKeyMap) > 0 { if err = d.Set("crypto_key", []map[string]interface{}{cryptoKeyMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crypto_key: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crypto_key"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } } } @@ -514,10 +552,12 @@ func dataSourceIbmSmPrivateCertificateConfigurationRootCARead(context context.Co if privateCertificateConfigurationRootCA.Data != nil { dataMap, err := dataSourceIbmSmPrivateCertificateConfigurationRootCAPrivateCertificateCADataToMap(privateCertificateConfigurationRootCA.Data) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("data", []map[string]interface{}{dataMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting data: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting data"), fmt.Sprintf("(Data) %s", PrivateCertConfigRootCAResourceName), "read") + return tfErr.GetDiag() } } diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_private_certificate_configuration_template.go b/ibm/service/secretsmanager/data_source_ibm_sm_private_certificate_configuration_template.go index 2fbf395d9e..e82a8166fa 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_private_certificate_configuration_template.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_private_certificate_configuration_template.go @@ -290,7 +290,8 @@ func DataSourceIbmSmPrivateCertificateConfigurationTemplate() *schema.Resource { func dataSourceIbmSmPrivateCertificateConfigurationTemplateRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -304,130 +305,161 @@ func dataSourceIbmSmPrivateCertificateConfigurationTemplateRead(context context. privateCertificateConfigurationTemplateIntf, response, err := secretsManagerClient.GetConfigurationWithContext(context, getConfigurationOptions) if err != nil { log.Printf("[DEBUG] GetConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetConfigurationWithContext failed %s\n%s", err, response), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } privateCertificateConfigurationTemplate := privateCertificateConfigurationTemplateIntf.(*secretsmanagerv2.PrivateCertificateConfigurationTemplate) d.SetId(fmt.Sprintf("%s/%s/%s", region, instanceId, *getConfigurationOptions.Name)) if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("config_type", privateCertificateConfigurationTemplate.ConfigType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting config_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting config_type"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", privateCertificateConfigurationTemplate.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_by", privateCertificateConfigurationTemplate.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(privateCertificateConfigurationTemplate.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(privateCertificateConfigurationTemplate.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("certificate_authority", privateCertificateConfigurationTemplate.CertificateAuthority); err != nil { - return diag.FromErr(fmt.Errorf("Error setting certificate_authority: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting certificate_authority"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("allowed_secret_groups", privateCertificateConfigurationTemplate.AllowedSecretGroups); err != nil { - return diag.FromErr(fmt.Errorf("Error setting allowed_secret_groups: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting allowed_secret_groups"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("max_ttl_seconds", flex.IntValue(privateCertificateConfigurationTemplate.MaxTtlSeconds)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting max_ttl_seconds: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting max_ttl_seconds"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("ttl_seconds", flex.IntValue(privateCertificateConfigurationTemplate.TtlSeconds)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting ttl_seconds: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting ttl_seconds"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("allow_localhost", privateCertificateConfigurationTemplate.AllowLocalhost); err != nil { - return diag.FromErr(fmt.Errorf("Error setting allow_localhost: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting allow_localhost"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("allowed_domains_template", privateCertificateConfigurationTemplate.AllowedDomainsTemplate); err != nil { - return diag.FromErr(fmt.Errorf("Error setting allowed_domains_template: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting allowed_domains_template"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("allow_bare_domains", privateCertificateConfigurationTemplate.AllowBareDomains); err != nil { - return diag.FromErr(fmt.Errorf("Error setting allow_bare_domains: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting allow_bare_domains"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("allow_subdomains", privateCertificateConfigurationTemplate.AllowSubdomains); err != nil { - return diag.FromErr(fmt.Errorf("Error setting allow_subdomains: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting allow_subdomains"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("allow_glob_domains", privateCertificateConfigurationTemplate.AllowGlobDomains); err != nil { - return diag.FromErr(fmt.Errorf("Error setting allow_glob_domains: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting allow_glob_domains"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("allow_any_name", privateCertificateConfigurationTemplate.AllowAnyName); err != nil { - return diag.FromErr(fmt.Errorf("Error setting allow_any_name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting allow_any_name"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("enforce_hostnames", privateCertificateConfigurationTemplate.EnforceHostnames); err != nil { - return diag.FromErr(fmt.Errorf("Error setting enforce_hostnames: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting enforce_hostnames"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("allow_ip_sans", privateCertificateConfigurationTemplate.AllowIpSans); err != nil { - return diag.FromErr(fmt.Errorf("Error setting allow_ip_sans: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting allow_ip_sans"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("server_flag", privateCertificateConfigurationTemplate.ServerFlag); err != nil { - return diag.FromErr(fmt.Errorf("Error setting server_flag: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting server_flag"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("client_flag", privateCertificateConfigurationTemplate.ClientFlag); err != nil { - return diag.FromErr(fmt.Errorf("Error setting client_flag: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting client_flag"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("code_signing_flag", privateCertificateConfigurationTemplate.CodeSigningFlag); err != nil { - return diag.FromErr(fmt.Errorf("Error setting code_signing_flag: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting code_signing_flag"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("email_protection_flag", privateCertificateConfigurationTemplate.EmailProtectionFlag); err != nil { - return diag.FromErr(fmt.Errorf("Error setting email_protection_flag: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting email_protection_flag"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("key_type", privateCertificateConfigurationTemplate.KeyType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting key_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting key_type"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("key_bits", flex.IntValue(privateCertificateConfigurationTemplate.KeyBits)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting key_bits: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting key_bits"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("use_csr_common_name", privateCertificateConfigurationTemplate.UseCsrCommonName); err != nil { - return diag.FromErr(fmt.Errorf("Error setting use_csr_common_name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting use_csr_common_name"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("use_csr_sans", privateCertificateConfigurationTemplate.UseCsrSans); err != nil { - return diag.FromErr(fmt.Errorf("Error setting use_csr_sans: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting use_csr_sans"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("serial_number", privateCertificateConfigurationTemplate.SerialNumber); err != nil { - return diag.FromErr(fmt.Errorf("Error setting serial_number: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting serial_number"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("require_cn", privateCertificateConfigurationTemplate.RequireCn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting require_cn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting require_cn"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("basic_constraints_valid_for_non_ca", privateCertificateConfigurationTemplate.BasicConstraintsValidForNonCa); err != nil { - return diag.FromErr(fmt.Errorf("Error setting basic_constraints_valid_for_non_ca: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting basic_constraints_valid_for_non_ca"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("not_before_duration_seconds", flex.IntValue(privateCertificateConfigurationTemplate.NotBeforeDurationSeconds)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting not_before_duration_seconds: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting not_before_duration_seconds"), fmt.Sprintf("(Data) %s", PrivateCertConfigTemplateResourceName), "read") + return tfErr.GetDiag() } return nil diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_private_certificate_metadata.go b/ibm/service/secretsmanager/data_source_ibm_sm_private_certificate_metadata.go index a1afb4a638..12706e4f58 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_private_certificate_metadata.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_private_certificate_metadata.go @@ -220,7 +220,8 @@ func DataSourceIbmSmPrivateCertificateMetadata() *schema.Resource { func dataSourceIbmSmPrivateCertificateMetadataRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -235,7 +236,8 @@ func dataSourceIbmSmPrivateCertificateMetadataRead(context context.Context, d *s privateCertificateMetadataIntf, response, err := secretsManagerClient.GetSecretMetadataWithContext(context, getSecretMetadataOptions) if err != nil { log.Printf("[DEBUG] GetSecretMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretMetadataWithContext failed %s\n%s", err, response), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } privateCertificateMetadata := privateCertificateMetadataIntf.(*secretsmanagerv2.PrivateCertificateMetadata) @@ -243,19 +245,23 @@ func dataSourceIbmSmPrivateCertificateMetadataRead(context context.Context, d *s d.SetId(fmt.Sprintf("%s/%s/%s", region, instanceId, secretId)) if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_by", privateCertificateMetadata.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(privateCertificateMetadata.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("crn", privateCertificateMetadata.Crn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crn"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if privateCertificateMetadata.CustomMetadata != nil { @@ -265,119 +271,146 @@ func dataSourceIbmSmPrivateCertificateMetadataRead(context context.Context, d *s } if err = d.Set("custom_metadata", flex.Flatten(convertedMap)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } } if err = d.Set("description", privateCertificateMetadata.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("downloaded", privateCertificateMetadata.Downloaded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting downloaded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting downloaded"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("locks_total", flex.IntValue(privateCertificateMetadata.LocksTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locks_total"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("name", privateCertificateMetadata.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_group_id", privateCertificateMetadata.SecretGroupID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_group_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_group_id"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", privateCertificateMetadata.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state", flex.IntValue(privateCertificateMetadata.State)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state_description", privateCertificateMetadata.StateDescription); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state_description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state_description"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(privateCertificateMetadata.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("versions_total", flex.IntValue(privateCertificateMetadata.VersionsTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting versions_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting versions_total"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("signing_algorithm", privateCertificateMetadata.SigningAlgorithm); err != nil { - return diag.FromErr(fmt.Errorf("Error setting signing_algorithm: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting signing_algorithm"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("certificate_authority", privateCertificateMetadata.CertificateAuthority); err != nil { - return diag.FromErr(fmt.Errorf("Error setting certificate_authority: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting certificate_authority"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("certificate_template", privateCertificateMetadata.CertificateTemplate); err != nil { - return diag.FromErr(fmt.Errorf("Error setting certificate_template: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting certificate_template"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("common_name", privateCertificateMetadata.CommonName); err != nil { - return diag.FromErr(fmt.Errorf("Error setting common_name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting common_name"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("expiration_date", DateTimeToRFC3339(privateCertificateMetadata.ExpirationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting expiration_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting expiration_date"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("issuer", privateCertificateMetadata.Issuer); err != nil { - return diag.FromErr(fmt.Errorf("Error setting issuer: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting issuer"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("key_algorithm", privateCertificateMetadata.KeyAlgorithm); err != nil { - return diag.FromErr(fmt.Errorf("Error setting key_algorithm: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting key_algorithm"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("next_rotation_date", DateTimeToRFC3339(privateCertificateMetadata.NextRotationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting next_rotation_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting next_rotation_date"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } rotation := []map[string]interface{}{} if privateCertificateMetadata.Rotation != nil { modelMap, err := dataSourceIbmSmPrivateCertificateMetadataRotationPolicyToMap(privateCertificateMetadata.Rotation) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } rotation = append(rotation, modelMap) } if err = d.Set("rotation", rotation); err != nil { - return diag.FromErr(fmt.Errorf("Error setting rotation %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting rotation"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("serial_number", privateCertificateMetadata.SerialNumber); err != nil { - return diag.FromErr(fmt.Errorf("Error setting serial_number: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting serial_number"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } validity := []map[string]interface{}{} if privateCertificateMetadata.Validity != nil { modelMap, err := dataSourceIbmSmPrivateCertificateMetadataCertificateValidityToMap(privateCertificateMetadata.Validity) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } validity = append(validity, modelMap) } if err = d.Set("validity", validity); err != nil { - return diag.FromErr(fmt.Errorf("Error setting validity %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting validity"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("revocation_time_seconds", flex.IntValue(privateCertificateMetadata.RevocationTimeSeconds)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting revocation_time_seconds: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting revocation_time_seconds"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("revocation_time_rfc3339", DateTimeToRFC3339(privateCertificateMetadata.RevocationTimeRfc3339)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting revocation_time_rfc3339: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting revocation_time_rfc3339"), fmt.Sprintf("(Data) %s_metadata", PrivateCertSecretResourceName), "read") + return tfErr.GetDiag() } return nil diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_public_certificate.go b/ibm/service/secretsmanager/data_source_ibm_sm_public_certificate.go index 20bfe5e1dd..17bc5ead32 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_public_certificate.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_public_certificate.go @@ -307,7 +307,7 @@ func DataSourceIbmSmPublicCertificate() *schema.Resource { } func dataSourceIbmSmPublicCertificateSecretRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - publicCertificateIntf, region, instanceId, diagError := getSecretByIdOrByName(context, d, meta, PublicCertSecretType) + publicCertificateIntf, region, instanceId, diagError := getSecretByIdOrByName(context, d, meta, PublicCertSecretType, PublicCertSecretResourceName) if diagError != nil { return diagError } @@ -318,19 +318,23 @@ func dataSourceIbmSmPublicCertificateSecretRead(context context.Context, d *sche var err error if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_by", publicCertificate.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(publicCertificate.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("crn", publicCertificate.Crn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crn"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if publicCertificate.CustomMetadata != nil { @@ -340,146 +344,178 @@ func dataSourceIbmSmPublicCertificateSecretRead(context context.Context, d *sche } if err = d.Set("custom_metadata", flex.Flatten(convertedMap)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } } if err = d.Set("description", publicCertificate.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("downloaded", publicCertificate.Downloaded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting downloaded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting downloaded"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if publicCertificate.Labels != nil { if err = d.Set("labels", publicCertificate.Labels); err != nil { - return diag.FromErr(fmt.Errorf("Error setting labels: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting labels"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } } if err = d.Set("locks_total", flex.IntValue(publicCertificate.LocksTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locks_total"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("name", publicCertificate.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_group_id", publicCertificate.SecretGroupID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_group_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_group_id"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", publicCertificate.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state", flex.IntValue(publicCertificate.State)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state_description", publicCertificate.StateDescription); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state_description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state_description"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(publicCertificate.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("versions_total", flex.IntValue(publicCertificate.VersionsTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting versions_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting versions_total"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("signing_algorithm", publicCertificate.SigningAlgorithm); err != nil { - return diag.FromErr(fmt.Errorf("Error setting signing_algorithm: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting signing_algorithm"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if publicCertificate.AltNames != nil { if err = d.Set("alt_names", publicCertificate.AltNames); err != nil { - return diag.FromErr(fmt.Errorf("Error setting alt_names: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting alt_names"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } } if err = d.Set("common_name", publicCertificate.CommonName); err != nil { - return diag.FromErr(fmt.Errorf("Error setting common_name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting common_name"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("expiration_date", DateTimeToRFC3339(publicCertificate.ExpirationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting expiration_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting expiration_date"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } issuanceInfo := []map[string]interface{}{} if publicCertificate.IssuanceInfo != nil { modelMap, err := dataSourceIbmSmPublicCertificateSecretCertificateIssuanceInfoToMap(publicCertificate.IssuanceInfo) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } issuanceInfo = append(issuanceInfo, modelMap) } if err = d.Set("issuance_info", issuanceInfo); err != nil { - return diag.FromErr(fmt.Errorf("Error setting issuance_info %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting issuance_info"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("issuer", publicCertificate.Issuer); err != nil { - return diag.FromErr(fmt.Errorf("Error setting issuer: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting issuer"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("key_algorithm", publicCertificate.KeyAlgorithm); err != nil { - return diag.FromErr(fmt.Errorf("Error setting key_algorithm: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting key_algorithm"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("serial_number", publicCertificate.SerialNumber); err != nil { - return diag.FromErr(fmt.Errorf("Error setting serial_number: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting serial_number"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } validity := []map[string]interface{}{} if publicCertificate.Validity != nil { modelMap, err := dataSourceIbmSmPublicCertificateSecretCertificateValidityToMap(publicCertificate.Validity) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } validity = append(validity, modelMap) } if err = d.Set("validity", validity); err != nil { - return diag.FromErr(fmt.Errorf("Error setting validity %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting validity"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } rotation := []map[string]interface{}{} if publicCertificate.Rotation != nil { modelMap, err := dataSourceIbmSmPublicCertificateSecretRotationPolicyToMap(publicCertificate.Rotation) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } rotation = append(rotation, modelMap) } if err = d.Set("rotation", rotation); err != nil { - return diag.FromErr(fmt.Errorf("Error setting rotation %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting rotation"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("bundle_certs", publicCertificate.BundleCerts); err != nil { - return diag.FromErr(fmt.Errorf("Error setting bundle_certs: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting bundle_certs"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("ca", publicCertificate.Ca); err != nil { - return diag.FromErr(fmt.Errorf("Error setting ca: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting ca"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("dns", publicCertificate.Dns); err != nil { - return diag.FromErr(fmt.Errorf("Error setting dns: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting dns"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("certificate", publicCertificate.Certificate); err != nil { - return diag.FromErr(fmt.Errorf("Error setting certificate: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting certificate"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("intermediate", publicCertificate.Intermediate); err != nil { - return diag.FromErr(fmt.Errorf("Error setting intermediate: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting intermediate"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("private_key", publicCertificate.PrivateKey); err != nil { - return diag.FromErr(fmt.Errorf("Error setting private_key: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting private_key"), fmt.Sprintf("(Data) %s", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } return nil diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_public_certificate_configuration_ca_lets_encrypt.go b/ibm/service/secretsmanager/data_source_ibm_sm_public_certificate_configuration_ca_lets_encrypt.go index 4f2631e6c9..89d75dcfde 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_public_certificate_configuration_ca_lets_encrypt.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_public_certificate_configuration_ca_lets_encrypt.go @@ -6,6 +6,7 @@ package secretsmanager import ( "context" "fmt" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "log" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" @@ -63,7 +64,8 @@ func DataSourceIbmSmPublicCertificateConfigurationCALetsEncrypt() *schema.Resour func dataSourceIbmSmPublicCertificateConfigurationCALetsEncryptRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", PublicCertConfigCALetsEncryptResourceName), "read") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -77,38 +79,46 @@ func dataSourceIbmSmPublicCertificateConfigurationCALetsEncryptRead(context cont publicCertificateConfigurationCALetsEncryptIntf, response, err := secretsManagerClient.GetConfigurationWithContext(context, getConfigurationOptions) if err != nil { log.Printf("[DEBUG] GetConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetConfigurationWithContext failed %s\n%s", err, response), fmt.Sprintf("(Data) %s", PublicCertConfigCALetsEncryptResourceName), "read") + return tfErr.GetDiag() } publicCertificateConfigurationCALetsEncrypt := publicCertificateConfigurationCALetsEncryptIntf.(*secretsmanagerv2.PublicCertificateConfigurationCALetsEncrypt) d.SetId(fmt.Sprintf("%s/%s/%s", region, instanceId, *getConfigurationOptions.Name)) if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s", PublicCertConfigCALetsEncryptResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_by", publicCertificateConfigurationCALetsEncrypt.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), fmt.Sprintf("(Data) %s", PublicCertConfigCALetsEncryptResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(publicCertificateConfigurationCALetsEncrypt.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), fmt.Sprintf("(Data) %s", PublicCertConfigCALetsEncryptResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(publicCertificateConfigurationCALetsEncrypt.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), fmt.Sprintf("(Data) %s", PublicCertConfigCALetsEncryptResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("lets_encrypt_environment", publicCertificateConfigurationCALetsEncrypt.LetsEncryptEnvironment); err != nil { - return diag.FromErr(fmt.Errorf("Error setting lets_encrypt_environment: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting lets_encrypt_environment"), fmt.Sprintf("(Data) %s", PublicCertConfigCALetsEncryptResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("lets_encrypt_private_key", publicCertificateConfigurationCALetsEncrypt.LetsEncryptPrivateKey); err != nil { - return diag.FromErr(fmt.Errorf("Error setting lets_encrypt_private_key: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting lets_encrypt_private_key"), fmt.Sprintf("(Data) %s", PublicCertConfigCALetsEncryptResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("lets_encrypt_preferred_chain", publicCertificateConfigurationCALetsEncrypt.LetsEncryptPreferredChain); err != nil { - return diag.FromErr(fmt.Errorf("Error setting lets_encrypt_preferred_chain: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting lets_encrypt_preferred_chain"), fmt.Sprintf("(Data) %s", PublicCertConfigCALetsEncryptResourceName), "read") + return tfErr.GetDiag() } return nil diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_public_certificate_configuration_dns_cis.go b/ibm/service/secretsmanager/data_source_ibm_sm_public_certificate_configuration_dns_cis.go index 8a9acbe6f5..ab7f7d5893 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_public_certificate_configuration_dns_cis.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_public_certificate_configuration_dns_cis.go @@ -6,6 +6,7 @@ package secretsmanager import ( "context" "fmt" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "log" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" @@ -67,7 +68,8 @@ func DataSourceIbmSmConfigurationPublicCertificateDNSCis() *schema.Resource { func dataSourceIbmSmConfigurationPublicCertificateDNSCisRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", PublicCertConfigDnsCISResourceName), "read") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -81,7 +83,8 @@ func dataSourceIbmSmConfigurationPublicCertificateDNSCisRead(context context.Con publicCertificateConfigurationDNSCloudInternetServicesIntf, response, err := secretsManagerClient.GetConfigurationWithContext(context, getConfigurationOptions) if err != nil { log.Printf("[DEBUG] GetConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetConfigurationWithContext failed %s\n%s", err, response), fmt.Sprintf("(Data) %s", PublicCertConfigDnsCISResourceName), "read") + return tfErr.GetDiag() } publicCertificateConfigurationDNSCloudInternetServices := publicCertificateConfigurationDNSCloudInternetServicesIntf.(*secretsmanagerv2.PublicCertificateConfigurationDNSCloudInternetServices) @@ -89,35 +92,43 @@ func dataSourceIbmSmConfigurationPublicCertificateDNSCisRead(context context.Con d.SetId(fmt.Sprintf("%s/%s/%s", region, instanceId, *getConfigurationOptions.Name)) if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s", PublicCertConfigDnsCISResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("config_type", publicCertificateConfigurationDNSCloudInternetServices.ConfigType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting config_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting config_type"), fmt.Sprintf("(Data) %s", PublicCertConfigDnsCISResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", publicCertificateConfigurationDNSCloudInternetServices.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), fmt.Sprintf("(Data) %s", PublicCertConfigDnsCISResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_by", publicCertificateConfigurationDNSCloudInternetServices.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), fmt.Sprintf("(Data) %s", PublicCertConfigDnsCISResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(publicCertificateConfigurationDNSCloudInternetServices.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), fmt.Sprintf("(Data) %s", PublicCertConfigDnsCISResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(publicCertificateConfigurationDNSCloudInternetServices.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), fmt.Sprintf("(Data) %s", PublicCertConfigDnsCISResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("cloud_internet_services_apikey", publicCertificateConfigurationDNSCloudInternetServices.CloudInternetServicesApikey); err != nil { - return diag.FromErr(fmt.Errorf("Error setting cloud_internet_services_apikey: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting cloud_internet_services_apikey"), fmt.Sprintf("(Data) %s", PublicCertConfigDnsCISResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("cloud_internet_services_crn", publicCertificateConfigurationDNSCloudInternetServices.CloudInternetServicesCrn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting cloud_internet_services_crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting cloud_internet_services_crn"), fmt.Sprintf("(Data) %s", PublicCertConfigDnsCISResourceName), "read") + return tfErr.GetDiag() } return nil diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_public_certificate_configuration_dns_classic_infrastructure.go b/ibm/service/secretsmanager/data_source_ibm_sm_public_certificate_configuration_dns_classic_infrastructure.go index 5ddf409829..90e622cee9 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_public_certificate_configuration_dns_classic_infrastructure.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_public_certificate_configuration_dns_classic_infrastructure.go @@ -6,6 +6,7 @@ package secretsmanager import ( "context" "fmt" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "log" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" @@ -67,7 +68,8 @@ func DataSourceIbmSmPublicCertificateConfigurationDNSClassicInfrastructure() *sc func dataSourceIbmSmPublicCertificateConfigurationDNSClassicInfrastructureRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", PublicCertConfigDnsClassicInfrastructureResourceName), "read") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -81,42 +83,51 @@ func dataSourceIbmSmPublicCertificateConfigurationDNSClassicInfrastructureRead(c publicCertificateConfigurationDNSClassicInfrastructureInf, response, err := secretsManagerClient.GetConfigurationWithContext(context, getConfigurationOptions) if err != nil { log.Printf("[DEBUG] GetConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetConfigurationWithContext failed %s\n%s", err, response), fmt.Sprintf("(Data) %s", PublicCertConfigDnsClassicInfrastructureResourceName), "read") + return tfErr.GetDiag() } publicCertificateConfigurationDNSClassicInfrastructure := publicCertificateConfigurationDNSClassicInfrastructureInf.(*secretsmanagerv2.PublicCertificateConfigurationDNSClassicInfrastructure) d.SetId(fmt.Sprintf("%s/%s/%s", region, instanceId, *getConfigurationOptions.Name)) if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s", PublicCertConfigDnsClassicInfrastructureResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("config_type", publicCertificateConfigurationDNSClassicInfrastructure.ConfigType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting config_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting config_type"), fmt.Sprintf("(Data) %s", PublicCertConfigDnsClassicInfrastructureResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", publicCertificateConfigurationDNSClassicInfrastructure.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), fmt.Sprintf("(Data) %s", PublicCertConfigDnsClassicInfrastructureResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_by", publicCertificateConfigurationDNSClassicInfrastructure.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), fmt.Sprintf("(Data) %s", PublicCertConfigDnsClassicInfrastructureResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(publicCertificateConfigurationDNSClassicInfrastructure.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), fmt.Sprintf("(Data) %s", PublicCertConfigDnsClassicInfrastructureResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(publicCertificateConfigurationDNSClassicInfrastructure.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), fmt.Sprintf("(Data) %s", PublicCertConfigDnsClassicInfrastructureResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("classic_infrastructure_username", publicCertificateConfigurationDNSClassicInfrastructure.ClassicInfrastructureUsername); err != nil { - return diag.FromErr(fmt.Errorf("Error setting classic_infrastructure_username: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting classic_infrastructure_username"), fmt.Sprintf("(Data) %s", PublicCertConfigDnsClassicInfrastructureResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("classic_infrastructure_password", publicCertificateConfigurationDNSClassicInfrastructure.ClassicInfrastructurePassword); err != nil { - return diag.FromErr(fmt.Errorf("Error setting classic_infrastructure_password: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting classic_infrastructure_password"), fmt.Sprintf("(Data) %s", PublicCertConfigDnsClassicInfrastructureResourceName), "read") + return tfErr.GetDiag() } return nil diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_public_certificate_metadata.go b/ibm/service/secretsmanager/data_source_ibm_sm_public_certificate_metadata.go index 0114bf0c27..569fb67cec 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_public_certificate_metadata.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_public_certificate_metadata.go @@ -283,7 +283,8 @@ func DataSourceIbmSmPublicCertificateMetadata() *schema.Resource { func dataSourceIbmSmPublicCertificateMetadataRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -298,7 +299,8 @@ func dataSourceIbmSmPublicCertificateMetadataRead(context context.Context, d *sc publicCertificateMetadataIntf, response, err := secretsManagerClient.GetSecretMetadataWithContext(context, getSecretMetadataOptions) if err != nil { log.Printf("[DEBUG] GetSecretMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretMetadataWithContext failed %s\n%s", err, response), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } publicCertificateMetadata := publicCertificateMetadataIntf.(*secretsmanagerv2.PublicCertificateMetadata) @@ -306,19 +308,23 @@ func dataSourceIbmSmPublicCertificateMetadataRead(context context.Context, d *sc d.SetId(fmt.Sprintf("%s/%s/%s", region, instanceId, secretId)) if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_by", publicCertificateMetadata.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(publicCertificateMetadata.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("crn", publicCertificateMetadata.Crn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crn"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if publicCertificateMetadata.CustomMetadata != nil { @@ -328,123 +334,150 @@ func dataSourceIbmSmPublicCertificateMetadataRead(context context.Context, d *sc } if err = d.Set("custom_metadata", flex.Flatten(convertedMap)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } } if err = d.Set("description", publicCertificateMetadata.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("downloaded", publicCertificateMetadata.Downloaded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting downloaded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting downloaded"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("locks_total", flex.IntValue(publicCertificateMetadata.LocksTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locks_total"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("name", publicCertificateMetadata.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_group_id", publicCertificateMetadata.SecretGroupID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_group_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_group_id"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", publicCertificateMetadata.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state", flex.IntValue(publicCertificateMetadata.State)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state_description", publicCertificateMetadata.StateDescription); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state_description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state_description"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(publicCertificateMetadata.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("versions_total", flex.IntValue(publicCertificateMetadata.VersionsTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting versions_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting versions_total"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("signing_algorithm", publicCertificateMetadata.SigningAlgorithm); err != nil { - return diag.FromErr(fmt.Errorf("Error setting signing_algorithm: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting signing_algorithm"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("common_name", publicCertificateMetadata.CommonName); err != nil { - return diag.FromErr(fmt.Errorf("Error setting common_name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting common_name"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("expiration_date", DateTimeToRFC3339(publicCertificateMetadata.ExpirationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting expiration_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting expiration_date"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } issuanceInfo := []map[string]interface{}{} if publicCertificateMetadata.IssuanceInfo != nil { modelMap, err := dataSourceIbmSmPublicCertificateMetadataCertificateIssuanceInfoToMap(publicCertificateMetadata.IssuanceInfo) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } issuanceInfo = append(issuanceInfo, modelMap) } if err = d.Set("issuance_info", issuanceInfo); err != nil { - return diag.FromErr(fmt.Errorf("Error setting issuance_info %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting issuance_info"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("issuer", publicCertificateMetadata.Issuer); err != nil { - return diag.FromErr(fmt.Errorf("Error setting issuer: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting issuer"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("key_algorithm", publicCertificateMetadata.KeyAlgorithm); err != nil { - return diag.FromErr(fmt.Errorf("Error setting key_algorithm: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting key_algorithm"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("serial_number", publicCertificateMetadata.SerialNumber); err != nil { - return diag.FromErr(fmt.Errorf("Error setting serial_number: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting serial_number"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } validity := []map[string]interface{}{} if publicCertificateMetadata.Validity != nil { modelMap, err := dataSourceIbmSmPublicCertificateMetadataCertificateValidityToMap(publicCertificateMetadata.Validity) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } validity = append(validity, modelMap) } if err = d.Set("validity", validity); err != nil { - return diag.FromErr(fmt.Errorf("Error setting validity %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting validity"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } rotation := []map[string]interface{}{} if publicCertificateMetadata.Rotation != nil { modelMap, err := dataSourceIbmSmPublicCertificateMetadataRotationPolicyToMap(publicCertificateMetadata.Rotation) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } rotation = append(rotation, modelMap) } if err = d.Set("rotation", rotation); err != nil { - return diag.FromErr(fmt.Errorf("Error setting rotation %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting rotation"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("bundle_certs", publicCertificateMetadata.BundleCerts); err != nil { - return diag.FromErr(fmt.Errorf("Error setting bundle_certs: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting bundle_certs"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("ca", publicCertificateMetadata.Ca); err != nil { - return diag.FromErr(fmt.Errorf("Error setting ca: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting ca"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("dns", publicCertificateMetadata.Dns); err != nil { - return diag.FromErr(fmt.Errorf("Error setting dns: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting dns"), fmt.Sprintf("(Data) %s_metadata", PublicCertSecretResourceName), "read") + return tfErr.GetDiag() } return nil diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_secret_group.go b/ibm/service/secretsmanager/data_source_ibm_sm_secret_group.go index 7352119b19..8c074e439e 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_secret_group.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_secret_group.go @@ -6,6 +6,7 @@ package secretsmanager import ( "context" "fmt" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "log" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" @@ -52,7 +53,8 @@ func DataSourceIbmSmSecretGroup() *schema.Resource { func dataSourceIbmSmSecretGroupRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", SecretGroupResourceName), "read") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -67,28 +69,34 @@ func dataSourceIbmSmSecretGroupRead(context context.Context, d *schema.ResourceD secretGroup, response, err := secretsManagerClient.GetSecretGroupWithContext(context, getSecretGroupOptions) if err != nil { log.Printf("[DEBUG] GetSecretGroupWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretGroupWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretGroupWithContext failed %s\n%s", err, response), fmt.Sprintf("(Data) %s", SecretGroupResourceName), "read") + return tfErr.GetDiag() } d.SetId(fmt.Sprintf("%s/%s/%s", region, instanceId, secretGroupId)) if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s", SecretGroupResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("name", secretGroup.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), fmt.Sprintf("(Data) %s", SecretGroupResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("description", secretGroup.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), fmt.Sprintf("(Data) %s", SecretGroupResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(secretGroup.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), fmt.Sprintf("(Data) %s", SecretGroupResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(secretGroup.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), fmt.Sprintf("(Data) %s", SecretGroupResourceName), "read") + return tfErr.GetDiag() } return nil diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_secret_groups.go b/ibm/service/secretsmanager/data_source_ibm_sm_secret_groups.go index 014dbe6d51..ea1ee4dc89 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_secret_groups.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_secret_groups.go @@ -68,7 +68,8 @@ func DataSourceIbmSmSecretGroups() *schema.Resource { func dataSourceIbmSmSecretGroupsRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", SecretGroupsResourceName), "read") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -80,7 +81,8 @@ func dataSourceIbmSmSecretGroupsRead(context context.Context, d *schema.Resource secretGroupCollection, response, err := secretsManagerClient.ListSecretGroupsWithContext(context, listSecretGroupsOptions) if err != nil { log.Printf("[DEBUG] ListSecretGroupsWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("ListSecretGroupsWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("ListSecretGroupsWithContext failed %s\n%s", err, response), fmt.Sprintf("(Data) %s", SecretGroupsResourceName), "read") + return tfErr.GetDiag() } d.SetId(fmt.Sprintf("%s/%s", region, instanceId)) @@ -90,21 +92,25 @@ func dataSourceIbmSmSecretGroupsRead(context context.Context, d *schema.Resource for _, modelItem := range secretGroupCollection.SecretGroups { modelMap, err := dataSourceIbmSmSecretGroupsSecretGroupToMap(&modelItem) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", SecretGroupsResourceName), "read") + return tfErr.GetDiag() } secretGroups = append(secretGroups, modelMap) } } if err = d.Set("secret_groups", secretGroups); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_groups %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_groups"), fmt.Sprintf("(Data) %s", SecretGroupsResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("total_count", flex.IntValue(secretGroupCollection.TotalCount)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting total_count: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting total_count"), fmt.Sprintf("(Data) %s", SecretGroupsResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s", SecretGroupsResourceName), "read") + return tfErr.GetDiag() } return nil } diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_secrets.go b/ibm/service/secretsmanager/data_source_ibm_sm_secrets.go index a37c67ce96..a921d68cb9 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_secrets.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_secrets.go @@ -519,7 +519,8 @@ func DataSourceIbmSmSecrets() *schema.Resource { func dataSourceIbmSmSecretsRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", SecretsResourceName), "read") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -569,13 +570,15 @@ func dataSourceIbmSmSecretsRead(context context.Context, d *schema.ResourceData, var pager *secretsmanagerv2.SecretsPager pager, err = secretsManagerClient.NewSecretsPager(listSecretsOptions) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", SecretsResourceName), "read") + return tfErr.GetDiag() } allItems, err := pager.GetAll() if err != nil { log.Printf("[DEBUG] SecretsPager.GetAll() failed %s", err) - return diag.FromErr(fmt.Errorf("SecretsPager.GetAll() failed %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("SecretsPager.GetAll() failed %s", err), fmt.Sprintf("(Data) %s", SecretsResourceName), "read") + return tfErr.GetDiag() } d.SetId(fmt.Sprintf("%s/%s", region, instanceId)) @@ -584,20 +587,24 @@ func dataSourceIbmSmSecretsRead(context context.Context, d *schema.ResourceData, for _, modelItem := range allItems { modelMap, err := dataSourceIbmSmSecretsSecretMetadataToMap(modelItem) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", SecretsResourceName), "read") + return tfErr.GetDiag() } mapSlice = append(mapSlice, modelMap) } if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s", SecretsResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secrets", mapSlice); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secrets %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secrets"), fmt.Sprintf("(Data) %s", SecretsResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("total_count", len(mapSlice)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting total_count"), fmt.Sprintf("(Data) %s", SecretsResourceName), "read") + return tfErr.GetDiag() } return nil diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_service_credentials_secret.go b/ibm/service/secretsmanager/data_source_ibm_sm_service_credentials_secret.go index ac195ad03f..205328b790 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_service_credentials_secret.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_service_credentials_secret.go @@ -280,7 +280,7 @@ func DataSourceIbmSmServiceCredentialsSecret() *schema.Resource { } func dataSourceIbmSmServiceCredentialsSecretRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - ServiceCredentialsSecretIntf, region, instanceId, diagError := getSecretByIdOrByName(context, d, meta, ServiceCredentialsSecretType) + ServiceCredentialsSecretIntf, region, instanceId, diagError := getSecretByIdOrByName(context, d, meta, ServiceCredentialsSecretType, ServiceCredentialsSecretResourceName) if diagError != nil { return diagError } @@ -290,18 +290,22 @@ func dataSourceIbmSmServiceCredentialsSecretRead(context context.Context, d *sch var err error if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_by", ServiceCredentialsSecret.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), fmt.Sprintf("(Data) %s", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(ServiceCredentialsSecret.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), fmt.Sprintf("(Data) %s", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("crn", ServiceCredentialsSecret.Crn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crn"), fmt.Sprintf("(Data) %s", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if ServiceCredentialsSecret.CustomMetadata != nil { @@ -311,77 +315,94 @@ func dataSourceIbmSmServiceCredentialsSecretRead(context context.Context, d *sch } if err = d.Set("custom_metadata", flex.Flatten(convertedMap)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } } if err = d.Set("description", ServiceCredentialsSecret.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), fmt.Sprintf("(Data) %s", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("downloaded", ServiceCredentialsSecret.Downloaded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting downloaded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting downloaded"), fmt.Sprintf("(Data) %s", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if ServiceCredentialsSecret.Labels != nil { if err = d.Set("labels", ServiceCredentialsSecret.Labels); err != nil { - return diag.FromErr(fmt.Errorf("Error setting labels: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting labels"), fmt.Sprintf("(Data) %s", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } } if err = d.Set("locks_total", flex.IntValue(ServiceCredentialsSecret.LocksTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locks_total"), fmt.Sprintf("(Data) %s", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("name", ServiceCredentialsSecret.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), fmt.Sprintf("(Data) %s", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_group_id", ServiceCredentialsSecret.SecretGroupID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_group_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_group_id"), fmt.Sprintf("(Data) %s", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", ServiceCredentialsSecret.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), fmt.Sprintf("(Data) %s", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state", flex.IntValue(ServiceCredentialsSecret.State)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state"), fmt.Sprintf("(Data) %s", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state_description", ServiceCredentialsSecret.StateDescription); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state_description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state_description"), fmt.Sprintf("(Data) %s", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(ServiceCredentialsSecret.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), fmt.Sprintf("(Data) %s", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("versions_total", flex.IntValue(ServiceCredentialsSecret.VersionsTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting versions_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting versions_total"), fmt.Sprintf("(Data) %s", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("ttl", ServiceCredentialsSecret.TTL); err != nil { - return diag.FromErr(fmt.Errorf("Error setting ttl: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting ttl"), fmt.Sprintf("(Data) %s", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } rotation := []map[string]interface{}{} if ServiceCredentialsSecret.Rotation != nil { modelMap, err := dataSourceIbmSmServiceCredentialsSecretRotationPolicyToMap(ServiceCredentialsSecret.Rotation.(*secretsmanagerv2.RotationPolicy)) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } rotation = append(rotation, modelMap) } if err = d.Set("rotation", rotation); err != nil { - return diag.FromErr(fmt.Errorf("Error setting rotation %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting rotation"), fmt.Sprintf("(Data) %s", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("next_rotation_date", DateTimeToRFC3339(ServiceCredentialsSecret.NextRotationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting next_rotation_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting next_rotation_date"), fmt.Sprintf("(Data) %s", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if ServiceCredentialsSecret.Credentials != nil { @@ -389,23 +410,27 @@ func dataSourceIbmSmServiceCredentialsSecretRead(context context.Context, d *sch cred, _ := json.Marshal(ServiceCredentialsSecret.Credentials) json.Unmarshal(cred, &credInterface) if err = d.Set("credentials", flex.Flatten(credInterface)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting credentials: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting credentials"), fmt.Sprintf("(Data) %s", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } } sourceServiceMap, err := dataSourceIbmSmServiceCredentialsSecretSourceServiceToMap(ServiceCredentialsSecret.SourceService) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if len(sourceServiceMap) > 0 { if err = d.Set("source_service", []map[string]interface{}{sourceServiceMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting source_service: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting source_service"), fmt.Sprintf("(Data) %s", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } } if ServiceCredentialsSecret.ExpirationDate != nil { if err = d.Set("expiration_date", DateTimeToRFC3339(ServiceCredentialsSecret.ExpirationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting expiration_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting expiration_date"), fmt.Sprintf("(Data) %s", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } } diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_service_credentials_secret_metadata.go b/ibm/service/secretsmanager/data_source_ibm_sm_service_credentials_secret_metadata.go index af85181e3a..1114706736 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_service_credentials_secret_metadata.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_service_credentials_secret_metadata.go @@ -265,7 +265,8 @@ func DataSourceIbmSmServiceCredentialsSecretMetadata() *schema.Resource { func dataSourceIbmSmServiceCredentialsSecretMetadataRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -280,25 +281,30 @@ func dataSourceIbmSmServiceCredentialsSecretMetadataRead(context context.Context ServiceCredentialsSecretMetadataIntf, response, err := secretsManagerClient.GetSecretMetadataWithContext(context, getSecretMetadataOptions) if err != nil { log.Printf("[DEBUG] GetSecretMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretMetadataWithContext failed %s\n%s", err, response), fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } ServiceCredentialsSecretMetadata := ServiceCredentialsSecretMetadataIntf.(*secretsmanagerv2.ServiceCredentialsSecretMetadata) d.SetId(fmt.Sprintf("%s/%s/%s", region, instanceId, secretId)) if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_by", ServiceCredentialsSecretMetadata.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(ServiceCredentialsSecretMetadata.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("crn", ServiceCredentialsSecretMetadata.Crn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crn"), fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if ServiceCredentialsSecretMetadata.CustomMetadata != nil { @@ -308,92 +314,112 @@ func dataSourceIbmSmServiceCredentialsSecretMetadataRead(context context.Context } if err = d.Set("custom_metadata", flex.Flatten(convertedMap)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } } if err = d.Set("description", ServiceCredentialsSecretMetadata.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("downloaded", ServiceCredentialsSecretMetadata.Downloaded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting downloaded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting downloaded"), fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if ServiceCredentialsSecretMetadata.Labels != nil { if err = d.Set("labels", ServiceCredentialsSecretMetadata.Labels); err != nil { - return diag.FromErr(fmt.Errorf("Error setting labels: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting labels"), fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } } if err = d.Set("locks_total", flex.IntValue(ServiceCredentialsSecretMetadata.LocksTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locks_total"), fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("name", ServiceCredentialsSecretMetadata.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_group_id", ServiceCredentialsSecretMetadata.SecretGroupID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_group_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_group_id"), fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", ServiceCredentialsSecretMetadata.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state", flex.IntValue(ServiceCredentialsSecretMetadata.State)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state"), fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state_description", ServiceCredentialsSecretMetadata.StateDescription); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state_description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state_description"), fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(ServiceCredentialsSecretMetadata.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("versions_total", flex.IntValue(ServiceCredentialsSecretMetadata.VersionsTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting versions_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting versions_total"), fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("ttl", ServiceCredentialsSecretMetadata.TTL); err != nil { - return diag.FromErr(fmt.Errorf("Error setting ttl: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting ttl"), fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } rotation := []map[string]interface{}{} if ServiceCredentialsSecretMetadata.Rotation != nil { modelMap, err := dataSourceIbmSmServiceCredentialsSecretMetadataRotationPolicyToMap(ServiceCredentialsSecretMetadata.Rotation.(*secretsmanagerv2.RotationPolicy)) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } rotation = append(rotation, modelMap) } if err = d.Set("rotation", rotation); err != nil { - return diag.FromErr(fmt.Errorf("Error setting rotation %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting rotation"), fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("next_rotation_date", DateTimeToRFC3339(ServiceCredentialsSecretMetadata.NextRotationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting next_rotation_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting next_rotation_date"), fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } sourceServiceMap, err := dataSourceIbmSmServiceCredentialsSecretMetadataSourceServiceToMap(ServiceCredentialsSecretMetadata.SourceService) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } if len(sourceServiceMap) > 0 { if err = d.Set("source_service", []map[string]interface{}{sourceServiceMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting source_service: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting source_service"), fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } } if ServiceCredentialsSecretMetadata.ExpirationDate != nil { if err = d.Set("expiration_date", DateTimeToRFC3339(ServiceCredentialsSecretMetadata.ExpirationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting expiration_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting expiration_date"), fmt.Sprintf("(Data) %s_metadata", ServiceCredentialsSecretResourceName), "read") + return tfErr.GetDiag() } } diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_username_password_secret.go b/ibm/service/secretsmanager/data_source_ibm_sm_username_password_secret.go index 262b037ad5..2ef644bd18 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_username_password_secret.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_username_password_secret.go @@ -194,7 +194,7 @@ func DataSourceIbmSmUsernamePasswordSecret() *schema.Resource { } func dataSourceIbmSmUsernamePasswordSecretRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - secret, region, instanceId, diagError := getSecretByIdOrByName(context, d, meta, UsernamePasswordSecretType) + secret, region, instanceId, diagError := getSecretByIdOrByName(context, d, meta, UsernamePasswordSecretType, UsernamePasswordSecretResourceName) if diagError != nil { return diagError } @@ -205,19 +205,23 @@ func dataSourceIbmSmUsernamePasswordSecretRead(context context.Context, d *schem var err error if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_by", usernamePasswordSecret.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), fmt.Sprintf("(Data) %s", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(usernamePasswordSecret.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), fmt.Sprintf("(Data) %s", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("crn", usernamePasswordSecret.Crn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crn"), fmt.Sprintf("(Data) %s", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if usernamePasswordSecret.CustomMetadata != nil { @@ -227,91 +231,111 @@ func dataSourceIbmSmUsernamePasswordSecretRead(context context.Context, d *schem } if err = d.Set("custom_metadata", flex.Flatten(convertedMap)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } } if err = d.Set("description", usernamePasswordSecret.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), fmt.Sprintf("(Data) %s", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("downloaded", usernamePasswordSecret.Downloaded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting downloaded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting downloaded"), fmt.Sprintf("(Data) %s", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("locks_total", flex.IntValue(usernamePasswordSecret.LocksTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locks_total"), fmt.Sprintf("(Data) %s", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("name", usernamePasswordSecret.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), fmt.Sprintf("(Data) %s", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_group_id", usernamePasswordSecret.SecretGroupID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_group_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_group_id"), fmt.Sprintf("(Data) %s", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", usernamePasswordSecret.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), fmt.Sprintf("(Data) %s", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state", flex.IntValue(usernamePasswordSecret.State)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state"), fmt.Sprintf("(Data) %s", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state_description", usernamePasswordSecret.StateDescription); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state_description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state_description"), fmt.Sprintf("(Data) %s", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(usernamePasswordSecret.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), fmt.Sprintf("(Data) %s", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("versions_total", flex.IntValue(usernamePasswordSecret.VersionsTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting versions_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting versions_total"), fmt.Sprintf("(Data) %s", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } rotation := []map[string]interface{}{} if usernamePasswordSecret.Rotation != nil { modelMap, err := dataSourceIbmSmUsernamePasswordSecretRotationPolicyToMap(usernamePasswordSecret.Rotation) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } rotation = append(rotation, modelMap) } if err = d.Set("rotation", rotation); err != nil { - return diag.FromErr(fmt.Errorf("Error setting rotation %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting rotation"), fmt.Sprintf("(Data) %s", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } passwordPolicy := []map[string]interface{}{} if usernamePasswordSecret.PasswordGenerationPolicy != nil { modelMap, err := passwordGenerationPolicyToMap(usernamePasswordSecret.PasswordGenerationPolicy) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } passwordPolicy = append(passwordPolicy, modelMap) } if err = d.Set("password_generation_policy", passwordPolicy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting password_generation_policy %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting password_generation_policy"), fmt.Sprintf("(Data) %s", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("expiration_date", DateTimeToRFC3339(usernamePasswordSecret.ExpirationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting expiration_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting expiration_date"), fmt.Sprintf("(Data) %s", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("next_rotation_date", DateTimeToRFC3339(usernamePasswordSecret.NextRotationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting next_rotation_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting next_rotation_date"), fmt.Sprintf("(Data) %s", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("username", usernamePasswordSecret.Username); err != nil { - return diag.FromErr(fmt.Errorf("Error setting username: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting username"), fmt.Sprintf("(Data) %s", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("password", usernamePasswordSecret.Password); err != nil { - return diag.FromErr(fmt.Errorf("Error setting password: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting password"), fmt.Sprintf("(Data) %s", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } return nil diff --git a/ibm/service/secretsmanager/data_source_ibm_sm_username_password_secret_metadata.go b/ibm/service/secretsmanager/data_source_ibm_sm_username_password_secret_metadata.go index cc6756f00c..a1bdb8ce35 100644 --- a/ibm/service/secretsmanager/data_source_ibm_sm_username_password_secret_metadata.go +++ b/ibm/service/secretsmanager/data_source_ibm_sm_username_password_secret_metadata.go @@ -177,7 +177,8 @@ func DataSourceIbmSmUsernamePasswordSecretMetadata() *schema.Resource { func dataSourceIbmSmUsernamePasswordSecretMetadataRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s_metadata", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -192,26 +193,31 @@ func dataSourceIbmSmUsernamePasswordSecretMetadataRead(context context.Context, usernamePasswordSecretMetadataIntf, response, err := secretsManagerClient.GetSecretMetadataWithContext(context, getSecretMetadataOptions) if err != nil { log.Printf("[DEBUG] GetSecretMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretMetadataWithContext failed %s\n%s", err, response), fmt.Sprintf("(Data) %s_metadata", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } usernamePasswordSecretMetadata := usernamePasswordSecretMetadataIntf.(*secretsmanagerv2.UsernamePasswordSecretMetadata) d.SetId(fmt.Sprintf("%s/%s/%s", region, instanceId, secretId)) if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), fmt.Sprintf("(Data) %s_metadata", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_by", usernamePasswordSecretMetadata.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), fmt.Sprintf("(Data) %s_metadata", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(usernamePasswordSecretMetadata.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), fmt.Sprintf("(Data) %s_metadata", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("crn", usernamePasswordSecretMetadata.Crn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crn"), fmt.Sprintf("(Data) %s_metadata", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if usernamePasswordSecretMetadata.CustomMetadata != nil { @@ -221,83 +227,101 @@ func dataSourceIbmSmUsernamePasswordSecretMetadataRead(context context.Context, } if err = d.Set("custom_metadata", flex.Flatten(convertedMap)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s_metadata", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err != nil { - return diag.FromErr(fmt.Errorf("Error setting custom_metadata %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting custom_metadata"), fmt.Sprintf("(Data) %s_metadata", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } } if err = d.Set("description", usernamePasswordSecretMetadata.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), fmt.Sprintf("(Data) %s_metadata", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("downloaded", usernamePasswordSecretMetadata.Downloaded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting downloaded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting downloaded"), fmt.Sprintf("(Data) %s_metadata", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("locks_total", flex.IntValue(usernamePasswordSecretMetadata.LocksTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locks_total"), fmt.Sprintf("(Data) %s_metadata", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("name", usernamePasswordSecretMetadata.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), fmt.Sprintf("(Data) %s_metadata", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_group_id", usernamePasswordSecretMetadata.SecretGroupID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_group_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_group_id"), fmt.Sprintf("(Data) %s_metadata", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", usernamePasswordSecretMetadata.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), fmt.Sprintf("(Data) %s_metadata", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state", flex.IntValue(usernamePasswordSecretMetadata.State)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state"), fmt.Sprintf("(Data) %s_metadata", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("state_description", usernamePasswordSecretMetadata.StateDescription); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state_description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state_description"), fmt.Sprintf("(Data) %s_metadata", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(usernamePasswordSecretMetadata.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), fmt.Sprintf("(Data) %s_metadata", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("versions_total", flex.IntValue(usernamePasswordSecretMetadata.VersionsTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting versions_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting versions_total"), fmt.Sprintf("(Data) %s_metadata", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } rotation := []map[string]interface{}{} if usernamePasswordSecretMetadata.Rotation != nil { modelMap, err := dataSourceIbmSmUsernamePasswordSecretMetadataRotationPolicyToMap(usernamePasswordSecretMetadata.Rotation) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s_metadata", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } rotation = append(rotation, modelMap) } if err = d.Set("rotation", rotation); err != nil { - return diag.FromErr(fmt.Errorf("Error setting rotation %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting rotation"), fmt.Sprintf("(Data) %s_metadata", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } passwordPolicy := []map[string]interface{}{} if usernamePasswordSecretMetadata.PasswordGenerationPolicy != nil { modelMap, err := passwordGenerationPolicyToMap(usernamePasswordSecretMetadata.PasswordGenerationPolicy) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s_metadata", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } passwordPolicy = append(passwordPolicy, modelMap) } if err = d.Set("password_generation_policy", passwordPolicy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting password_generation_policy %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting password_generation_policy"), fmt.Sprintf("(Data) %s_metadata", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("expiration_date", DateTimeToRFC3339(usernamePasswordSecretMetadata.ExpirationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting expiration_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting expiration_date"), fmt.Sprintf("(Data) %s_metadata", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } if err = d.Set("next_rotation_date", DateTimeToRFC3339(usernamePasswordSecretMetadata.NextRotationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting next_rotation_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting next_rotation_date"), fmt.Sprintf("(Data) %s_metadata", UsernamePasswordSecretResourceName), "read") + return tfErr.GetDiag() } return nil diff --git a/ibm/service/secretsmanager/resource_ibm_sm_arbitrary_secret.go b/ibm/service/secretsmanager/resource_ibm_sm_arbitrary_secret.go index b4b4e2bd7f..88a3336911 100644 --- a/ibm/service/secretsmanager/resource_ibm_sm_arbitrary_secret.go +++ b/ibm/service/secretsmanager/resource_ibm_sm_arbitrary_secret.go @@ -144,7 +144,8 @@ func ResourceIbmSmArbitrarySecret() *schema.Resource { func resourceIbmSmArbitrarySecretCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", ArbitrarySecretResourceName, "create") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -155,14 +156,16 @@ func resourceIbmSmArbitrarySecretCreate(context context.Context, d *schema.Resou secretPrototypeModel, err := resourceIbmSmArbitrarySecretMapToArbitrarySecretPrototype(d) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", ArbitrarySecretResourceName, "create") + return tfErr.GetDiag() } createSecretOptions.SetSecretPrototype(secretPrototypeModel) secretIntf, response, err := secretsManagerClient.CreateSecretWithContext(context, createSecretOptions) if err != nil { log.Printf("[DEBUG] CreateSecretWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateSecretWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateSecretWithContext failed: %s\n%s", err.Error(), response), ArbitrarySecretResourceName, "create") + return tfErr.GetDiag() } secret := secretIntf.(*secretsmanagerv2.ArbitrarySecret) @@ -171,8 +174,8 @@ func resourceIbmSmArbitrarySecretCreate(context context.Context, d *schema.Resou _, err = waitForIbmSmArbitrarySecretCreate(secretsManagerClient, d) if err != nil { - return diag.FromErr(fmt.Errorf( - "Error waiting for resource IbmSmArbitrarySecret (%s) to be created: %s", d.Id(), err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error waiting for resource IbmSmArbitrarySecret (%s) to be created: %s", d.Id(), err.Error()), ArbitrarySecretResourceName, "create") + return tfErr.GetDiag() } return resourceIbmSmArbitrarySecretRead(context, d, meta) @@ -214,12 +217,14 @@ func waitForIbmSmArbitrarySecretCreate(secretsManagerClient *secretsmanagerv2.Se func resourceIbmSmArbitrarySecretRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", ArbitrarySecretResourceName, "read") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") if len(id) != 3 { - return diag.Errorf("Wrong format of resource ID. To import a secret use the format `//`") + tfErr := flex.TerraformErrorf(nil, "Wrong format of resource ID. To import a secret use the format `//`", ArbitrarySecretResourceName, "read") + return tfErr.GetDiag() } region := id[0] instanceId := id[1] @@ -237,72 +242,92 @@ func resourceIbmSmArbitrarySecretRead(context context.Context, d *schema.Resourc return nil } log.Printf("[DEBUG] GetSecretWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretWithContext failed %s\n%s", err, response), ArbitrarySecretResourceName, "read") + return tfErr.GetDiag() } secret := secretIntf.(*secretsmanagerv2.ArbitrarySecret) if err = d.Set("secret_id", secretId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_id"), ArbitrarySecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("instance_id", instanceId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting instance_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting instance_id"), ArbitrarySecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), ArbitrarySecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("created_by", secret.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), ArbitrarySecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(secret.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), ArbitrarySecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("crn", secret.Crn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crn"), ArbitrarySecretResourceName, "read") + return tfErr.GetDiag() + } + if secret.CustomMetadata != nil { + d.Set("custom_metadata", secret.CustomMetadata) + } + if err = d.Set("description", secret.Description); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), ArbitrarySecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("downloaded", secret.Downloaded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting downloaded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting downloaded"), ArbitrarySecretResourceName, "read") + return tfErr.GetDiag() + } + if secret.Labels != nil { + if err = d.Set("labels", secret.Labels); err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting labels"), ArbitrarySecretResourceName, "read") + return tfErr.GetDiag() + } } if err = d.Set("locks_total", flex.IntValue(secret.LocksTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locks_total"), ArbitrarySecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("name", secret.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), ArbitrarySecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("secret_group_id", secret.SecretGroupID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_group_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_group_id"), ArbitrarySecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", secret.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), ArbitrarySecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("state", flex.IntValue(secret.State)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state"), ArbitrarySecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("state_description", secret.StateDescription); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state_description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state_description"), ArbitrarySecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(secret.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), ArbitrarySecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("versions_total", flex.IntValue(secret.VersionsTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting versions_total: %s", err)) - } - if secret.CustomMetadata != nil { - d.Set("custom_metadata", secret.CustomMetadata) - } - if err = d.Set("description", secret.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) - } - if secret.Labels != nil { - if err = d.Set("labels", secret.Labels); err != nil { - return diag.FromErr(fmt.Errorf("Error setting labels: %s", err)) - } + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting versions_total"), ArbitrarySecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("expiration_date", DateTimeToRFC3339(secret.ExpirationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting expiration_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting expiration_date"), ArbitrarySecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("payload", secret.Payload); err != nil { - return diag.FromErr(fmt.Errorf("Error setting payload: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting payload"), ArbitrarySecretResourceName, "read") + return tfErr.GetDiag() } // Call get version metadata API to get the current version_custom_metadata @@ -313,13 +338,15 @@ func resourceIbmSmArbitrarySecretRead(context context.Context, d *schema.Resourc versionMetadataIntf, response, err := secretsManagerClient.GetSecretVersionMetadataWithContext(context, getVersionMetdataOptions) if err != nil { log.Printf("[DEBUG] GetSecretVersionMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretVersionMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretVersionMetadataWithContext failed %s\n%s", err, response), ArbitrarySecretResourceName, "read") + return tfErr.GetDiag() } versionMetadata := versionMetadataIntf.(*secretsmanagerv2.ArbitrarySecretVersionMetadata) if versionMetadata.VersionCustomMetadata != nil { if err = d.Set("version_custom_metadata", versionMetadata.VersionCustomMetadata); err != nil { - return diag.FromErr(fmt.Errorf("Error setting version_custom_metadata: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting version_custom_metadata"), ArbitrarySecretResourceName, "read") + return tfErr.GetDiag() } } @@ -329,7 +356,8 @@ func resourceIbmSmArbitrarySecretRead(context context.Context, d *schema.Resourc func resourceIbmSmArbitrarySecretUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", ArbitrarySecretResourceName, "update") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -373,13 +401,15 @@ func resourceIbmSmArbitrarySecretUpdate(context context.Context, d *schema.Resou layout := time.RFC3339 parseToTime, err := time.Parse(layout, d.Get("expiration_date").(string)) if err != nil { - return diag.FromErr(errors.New(`Failed to get "expiration_date". Error: ` + err.Error())) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf(`Failed to get "expiration_date"`), ArbitrarySecretResourceName, "update") + return tfErr.GetDiag() } parseToDateTime := strfmt.DateTime(parseToTime) patchVals.ExpirationDate = &parseToDateTime hasChange = true } else { - return diag.FromErr(errors.New(`The "expiration_date" field cannot be removed. To disable expiration set expiration date to a far future date'`)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf(`The "expiration_date" field cannot be removed. To disable expiration set expiration date to a far future date'`), ArbitrarySecretResourceName, "update") + return tfErr.GetDiag() } } @@ -389,7 +419,8 @@ func resourceIbmSmArbitrarySecretUpdate(context context.Context, d *schema.Resou _, response, err := secretsManagerClient.UpdateSecretMetadataWithContext(context, updateSecretMetadataOptions) if err != nil { log.Printf("[DEBUG] UpdateSecretMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateSecretMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateSecretMetadataWithContext failed %s\n%s", err, response), ArbitrarySecretResourceName, "update") + return tfErr.GetDiag() } } @@ -415,7 +446,8 @@ func resourceIbmSmArbitrarySecretUpdate(context context.Context, d *schema.Resou resourceIbmSmArbitrarySecretRead(context, d, meta) } log.Printf("[DEBUG] CreateSecretVersionWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateSecretVersionWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateSecretVersionWithContext failed %s\n%s", err, response), ArbitrarySecretResourceName, "update") + return tfErr.GetDiag() } } else if d.HasChange("version_custom_metadata") { // Apply change to version_custom_metadata in current version @@ -434,7 +466,8 @@ func resourceIbmSmArbitrarySecretUpdate(context context.Context, d *schema.Resou resourceIbmSmArbitrarySecretRead(context, d, meta) } log.Printf("[DEBUG] UpdateSecretVersionMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateSecretVersionMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateSecretVersionMetadataWithContext failed %s\n%s", err, response), ArbitrarySecretResourceName, "update") + return tfErr.GetDiag() } } @@ -444,7 +477,8 @@ func resourceIbmSmArbitrarySecretUpdate(context context.Context, d *schema.Resou func resourceIbmSmArbitrarySecretDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", ArbitrarySecretResourceName, "delete") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -460,7 +494,8 @@ func resourceIbmSmArbitrarySecretDelete(context context.Context, d *schema.Resou response, err := secretsManagerClient.DeleteSecretWithContext(context, deleteSecretOptions) if err != nil { log.Printf("[DEBUG] DeleteSecretWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("DeleteSecretWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("DeleteSecretWithContext failed %s\n%s", err, response), ArbitrarySecretResourceName, "delete") + return tfErr.GetDiag() } d.SetId("") diff --git a/ibm/service/secretsmanager/resource_ibm_sm_en_registration.go b/ibm/service/secretsmanager/resource_ibm_sm_en_registration.go index c32fd78b37..f0ce9112e7 100644 --- a/ibm/service/secretsmanager/resource_ibm_sm_en_registration.go +++ b/ibm/service/secretsmanager/resource_ibm_sm_en_registration.go @@ -6,6 +6,7 @@ package secretsmanager import ( "context" "fmt" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "log" "strings" @@ -30,21 +31,21 @@ func ResourceIbmSmEnRegistration() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - ValidateFunc: validate.InvokeValidator("ibm_sm_en_registration", "event_notifications_instance_crn"), + ValidateFunc: validate.InvokeValidator(EnRegistrationResourceName, "event_notifications_instance_crn"), Description: "A CRN that uniquely identifies an IBM Cloud resource.", }, "event_notifications_source_name": &schema.Schema{ Type: schema.TypeString, Required: true, ForceNew: true, - ValidateFunc: validate.InvokeValidator("ibm_sm_en_registration", "event_notifications_source_name"), + ValidateFunc: validate.InvokeValidator(EnRegistrationResourceName, "event_notifications_source_name"), Description: "The name that is displayed as a source that is in your Event Notifications instance.", }, "event_notifications_source_description": &schema.Schema{ Type: schema.TypeString, Optional: true, ForceNew: true, - ValidateFunc: validate.InvokeValidator("ibm_sm_en_registration", "event_notifications_source_description"), + ValidateFunc: validate.InvokeValidator(EnRegistrationResourceName, "event_notifications_source_description"), Description: "An optional description for the source that is in your Event Notifications instance.", }, }, @@ -83,14 +84,15 @@ func ResourceIbmSmEnRegistrationValidator() *validate.ResourceValidator { }, ) - resourceValidator := validate.ResourceValidator{ResourceName: "ibm_sm_en_registration", Schema: validateSchema} + resourceValidator := validate.ResourceValidator{ResourceName: EnRegistrationResourceName, Schema: validateSchema} return &resourceValidator } func resourceIbmSmEnRegistrationCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", EnRegistrationResourceName, "create") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -108,7 +110,8 @@ func resourceIbmSmEnRegistrationCreate(context context.Context, d *schema.Resour _, response, err := secretsManagerClient.CreateNotificationsRegistrationWithContext(context, createNotificationsRegistrationOptions) if err != nil { log.Printf("[DEBUG] CreateNotificationsRegistrationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateNotificationsRegistrationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateNotificationsRegistrationWithContext failed %s\n%s", err, response), EnRegistrationResourceName, "create") + return tfErr.GetDiag() } d.SetId(fmt.Sprintf("%s/%s", region, instanceId)) @@ -119,12 +122,14 @@ func resourceIbmSmEnRegistrationCreate(context context.Context, d *schema.Resour func resourceIbmSmEnRegistrationRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", EnRegistrationResourceName, "read") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") if len(id) != 2 { - return diag.Errorf("Wrong format of resource ID. To import event notification registration use the format `/`") + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Wrong format of resource ID. To import event notification registration use the format `/`"), EnRegistrationResourceName, "read") + return tfErr.GetDiag() } region := id[0] instanceId := id[1] @@ -139,17 +144,21 @@ func resourceIbmSmEnRegistrationRead(context context.Context, d *schema.Resource return nil } log.Printf("[DEBUG] GetNotificationsRegistrationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetNotificationsRegistrationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetNotificationsRegistrationWithContext failed %s\n%s", err, response), EnRegistrationResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("instance_id", instanceId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting instance_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting instance_id"), EnRegistrationResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), EnRegistrationResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("event_notifications_instance_crn", notificationsRegistration.EventNotificationsInstanceCrn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting event_notifications_instance_crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting event_notifications_instance_crn"), EnRegistrationResourceName, "read") + return tfErr.GetDiag() } return nil @@ -158,7 +167,8 @@ func resourceIbmSmEnRegistrationRead(context context.Context, d *schema.Resource func resourceIbmSmEnRegistrationUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf(""), EnRegistrationResourceName, "update") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -183,8 +193,9 @@ func resourceIbmSmEnRegistrationUpdate(context context.Context, d *schema.Resour if hasChange { _, response, err := secretsManagerClient.CreateNotificationsRegistrationWithContext(context, createNotificationsRegistrationOptions) if err != nil { - log.Printf("[DEBUG] CreateNotificationsRegistrationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateNotificationsRegistrationWithContext failed %s\n%s", err, response)) + log.Printf("[DEBUG] UpdateNotificationsRegistrationWithContext failed %s\n%s", err, response) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateNotificationsRegistrationWithContext failed %s\n%s", err, response), EnRegistrationResourceName, "update") + return tfErr.GetDiag() } } @@ -194,7 +205,8 @@ func resourceIbmSmEnRegistrationUpdate(context context.Context, d *schema.Resour func resourceIbmSmEnRegistrationDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", EnRegistrationResourceName, "delete") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -207,7 +219,8 @@ func resourceIbmSmEnRegistrationDelete(context context.Context, d *schema.Resour response, err := secretsManagerClient.DeleteNotificationsRegistrationWithContext(context, deleteNotificationsRegistrationOptions) if err != nil { log.Printf("[DEBUG] DeleteNotificationsRegistrationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("DeleteNotificationsRegistrationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("DeleteNotificationsRegistrationWithContext failed %s\n%s", err, response), EnRegistrationResourceName, "delete") + return tfErr.GetDiag() } d.SetId("") diff --git a/ibm/service/secretsmanager/resource_ibm_sm_iam_credentials_configuration.go b/ibm/service/secretsmanager/resource_ibm_sm_iam_credentials_configuration.go index b284d0567d..cfda48d0bd 100644 --- a/ibm/service/secretsmanager/resource_ibm_sm_iam_credentials_configuration.go +++ b/ibm/service/secretsmanager/resource_ibm_sm_iam_credentials_configuration.go @@ -6,6 +6,7 @@ package secretsmanager import ( "context" "fmt" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "log" "strings" @@ -70,7 +71,8 @@ func ResourceIbmSmIamCredentialsConfiguration() *schema.Resource { func resourceIbmSmIamCredentialsConfigurationCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", IAMCredentialsConfigResourceName, "create") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -81,14 +83,16 @@ func resourceIbmSmIamCredentialsConfigurationCreate(context context.Context, d * configurationPrototypeModel, err := resourceIbmSmIamCredentialsConfigurationMapToConfigurationPrototype(d) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", IAMCredentialsConfigResourceName, "create") + return tfErr.GetDiag() } createConfigurationOptions.SetConfigurationPrototype(configurationPrototypeModel) configurationIntf, response, err := secretsManagerClient.CreateConfigurationWithContext(context, createConfigurationOptions) if err != nil { log.Printf("[DEBUG] CreateConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateConfigurationWithContext failed %s\n%s", err, response), IAMCredentialsConfigResourceName, "create") + return tfErr.GetDiag() } configuration := configurationIntf.(*secretsmanagerv2.IAMCredentialsConfiguration) @@ -100,12 +104,14 @@ func resourceIbmSmIamCredentialsConfigurationCreate(context context.Context, d * func resourceIbmSmIamCredentialsConfigurationRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", IAMCredentialsConfigResourceName, "read") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") if len(id) != 3 { - return diag.Errorf("Wrong format of resource ID. To import IAM credentials configuration use the format `//`") + tfErr := flex.TerraformErrorf(nil, "Wrong format of resource ID. To import IAM credentials configuration use the format `//`", IAMCredentialsConfigResourceName, "read") + return tfErr.GetDiag() } region := id[0] instanceId := id[1] @@ -123,33 +129,42 @@ func resourceIbmSmIamCredentialsConfigurationRead(context context.Context, d *sc return nil } log.Printf("[DEBUG] GetConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetConfigurationWithContext failed %s\n%s", err, response), IAMCredentialsConfigResourceName, "read") + return tfErr.GetDiag() } configuration := configurationIntf.(*secretsmanagerv2.IAMCredentialsConfiguration) if err = d.Set("instance_id", instanceId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting instance_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting instance_id"), IAMCredentialsConfigResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), IAMCredentialsConfigResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("name", configuration.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), IAMCredentialsConfigResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", configuration.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), IAMCredentialsConfigResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("created_by", configuration.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), IAMCredentialsConfigResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(configuration.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), IAMCredentialsConfigResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(configuration.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), IAMCredentialsConfigResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("api_key", configuration.ApiKey); err != nil { - return diag.FromErr(fmt.Errorf("Error setting api_key: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting api_key"), IAMCredentialsConfigResourceName, "read") + return tfErr.GetDiag() } return nil @@ -158,7 +173,8 @@ func resourceIbmSmIamCredentialsConfigurationRead(context context.Context, d *sc func resourceIbmSmIamCredentialsConfigurationUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", IAMCredentialsConfigResourceName, "update") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -186,7 +202,8 @@ func resourceIbmSmIamCredentialsConfigurationUpdate(context context.Context, d * _, response, err := secretsManagerClient.UpdateConfigurationWithContext(context, updateConfigurationOptions) if err != nil { log.Printf("[DEBUG] UpdateConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateConfigurationWithContext failed %s\n%s", err, response), IAMCredentialsConfigResourceName, "update") + return tfErr.GetDiag() } } @@ -212,7 +229,8 @@ func resourceIbmSmIamCredentialsConfigurationDelete(context context.Context, d * response, err := secretsManagerClient.DeleteConfigurationWithContext(context, deleteConfigurationOptions) if err != nil { log.Printf("[DEBUG] DeleteConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("DeleteConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("DeleteConfigurationWithContext failed %s\n%s", err, response), IAMCredentialsConfigResourceName, "delete") + return tfErr.GetDiag() } d.SetId("") diff --git a/ibm/service/secretsmanager/resource_ibm_sm_iam_credentials_secret.go b/ibm/service/secretsmanager/resource_ibm_sm_iam_credentials_secret.go index a0fef420ab..0a78d80a50 100644 --- a/ibm/service/secretsmanager/resource_ibm_sm_iam_credentials_secret.go +++ b/ibm/service/secretsmanager/resource_ibm_sm_iam_credentials_secret.go @@ -212,7 +212,8 @@ func ResourceIbmSmIamCredentialsSecret() *schema.Resource { func resourceIbmSmIamCredentialsSecretCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", IAMCredentialsSecretResourceName, "create") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -222,18 +223,21 @@ func resourceIbmSmIamCredentialsSecretCreate(context context.Context, d *schema. createSecretOptions := &secretsmanagerv2.CreateSecretOptions{} if !d.Get("reuse_api_key").(bool) { - return diag.Errorf("IAM credentials secrets managed by Terraform must have reuse_api_key set to true") + tfErr := flex.TerraformErrorf(err, "IAM credentials secrets managed by Terraform must have reuse_api_key set to true", IAMCredentialsSecretResourceName, "create") + return tfErr.GetDiag() } secretPrototypeModel, err := resourceIbmSmIamCredentialsSecretMapToSecretPrototype(d) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", IAMCredentialsSecretResourceName, "create") + return tfErr.GetDiag() } createSecretOptions.SetSecretPrototype(secretPrototypeModel) secretIntf, response, err := secretsManagerClient.CreateSecretWithContext(context, createSecretOptions) if err != nil { log.Printf("[DEBUG] CreateSecretWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateSecretWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateSecretWithContext failed: %s\n%s", err.Error(), response), IAMCredentialsSecretResourceName, "create") + return tfErr.GetDiag() } secret := secretIntf.(*secretsmanagerv2.IAMCredentialsSecret) @@ -242,8 +246,8 @@ func resourceIbmSmIamCredentialsSecretCreate(context context.Context, d *schema. _, err = waitForIbmSmIamCredentialsSecretCreate(secretsManagerClient, d) if err != nil { - return diag.FromErr(fmt.Errorf( - "Error waiting for resource IbmSmIamCredentialsSecret (%s) to be created: %s", d.Id(), err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error waiting for resource IbmSmIamCredentialsSecret (%s) to be created: %s", d.Id(), err.Error()), IAMCredentialsSecretResourceName, "create") + return tfErr.GetDiag() } return resourceIbmSmIamCredentialsSecretRead(context, d, meta) @@ -286,12 +290,14 @@ func waitForIbmSmIamCredentialsSecretCreate(secretsManagerClient *secretsmanager func resourceIbmSmIamCredentialsSecretRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") if len(id) != 3 { - return diag.Errorf("Wrong format of resource ID. To import a secret use the format `//`") + tfErr := flex.TerraformErrorf(nil, "Wrong format of resource ID. To import a secret use the format `//`", IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } region := id[0] instanceId := id[1] @@ -309,107 +315,136 @@ func resourceIbmSmIamCredentialsSecretRead(context context.Context, d *schema.Re return nil } log.Printf("[DEBUG] GetSecretWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretWithContext failed %s\n%s", err, response), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } secret := secretIntf.(*secretsmanagerv2.IAMCredentialsSecret) if err = d.Set("secret_id", secretId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_id"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("instance_id", instanceId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting instance_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting instance_id"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("created_by", secret.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(secret.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("crn", secret.Crn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crn"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if secret.CustomMetadata != nil { d.Set("custom_metadata", secret.CustomMetadata) } if err = d.Set("description", secret.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("downloaded", secret.Downloaded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting downloaded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting downloaded"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if secret.Labels != nil { if err = d.Set("labels", secret.Labels); err != nil { - return diag.FromErr(fmt.Errorf("Error setting labels: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting labels"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("locks_total", flex.IntValue(secret.LocksTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locks_total"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("name", secret.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("secret_group_id", secret.SecretGroupID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_group_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_group_id"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", secret.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("state", flex.IntValue(secret.State)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("state_description", secret.StateDescription); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state_description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state_description"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(secret.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("versions_total", flex.IntValue(secret.VersionsTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting versions_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting versions_total"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("ttl", secret.TTL); err != nil { - return diag.FromErr(fmt.Errorf("Error setting signing_algorithm: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting ttl"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if secret.AccessGroups != nil { if err = d.Set("access_groups", secret.AccessGroups); err != nil { - return diag.FromErr(fmt.Errorf("Error setting access_groups: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting access_groups"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("api_key_id", secret.ApiKeyID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting api_key_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting api_key_id"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("service_id", secret.ServiceID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting service_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting service_id"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("service_id_is_static", secret.ServiceIdIsStatic); err != nil { - return diag.FromErr(fmt.Errorf("Error setting service_id_is_static: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting service_id_is_static"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } // Prevent import of secrets with reuse_api_key = false into Terraform if !*secret.ReuseApiKey { - return diag.Errorf("IAM credentials secrets with Reuse IAM credentials turned off (reuse_api_key = false) cannot be managed by Terraform") + tfErr := flex.TerraformErrorf(nil, "IAM credentials secrets with Reuse IAM credentials turned off (reuse_api_key = false) cannot be managed by Terraform", IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } else { if err = d.Set("reuse_api_key", true); err != nil { - return diag.FromErr(fmt.Errorf("Error setting reuse_api_key: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting reuse_api_key"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } } rotationMap, err := resourceIbmSmIamCredentialsSecretRotationPolicyToMap(secret.Rotation) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if len(rotationMap) > 0 { if err = d.Set("rotation", []map[string]interface{}{rotationMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting rotation: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting rotation"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("next_rotation_date", DateTimeToRFC3339(secret.NextRotationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting next_rotation_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting next_rotation_date"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("api_key", secret.ApiKey); err != nil { - return diag.FromErr(fmt.Errorf("Error setting signing_algorithm: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting api_key"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } // Call get version metadata API to get the current version_custom_metadata @@ -420,19 +455,22 @@ func resourceIbmSmIamCredentialsSecretRead(context context.Context, d *schema.Re versionMetadataIntf, response, err := secretsManagerClient.GetSecretVersionMetadataWithContext(context, getVersionMetdataOptions) if err != nil { log.Printf("[DEBUG] GetSecretVersionMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretVersionMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretVersionMetadataWithContext failed %s\n%s", err, response), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } versionMetadata := versionMetadataIntf.(*secretsmanagerv2.IAMCredentialsSecretVersionMetadata) if versionMetadata.VersionCustomMetadata != nil { if err = d.Set("version_custom_metadata", versionMetadata.VersionCustomMetadata); err != nil { - return diag.FromErr(fmt.Errorf("Error setting version_custom_metadata: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting version_custom_metadata"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } } if secret.ExpirationDate != nil { if err = d.Set("expiration_date", DateTimeToRFC3339(secret.ExpirationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting expiration_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting expiration_date"), IAMCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } } @@ -442,7 +480,8 @@ func resourceIbmSmIamCredentialsSecretRead(context context.Context, d *schema.Re func resourceIbmSmIamCredentialsSecretUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", IAMCredentialsSecretResourceName, "update") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -488,7 +527,8 @@ func resourceIbmSmIamCredentialsSecretUpdate(context context.Context, d *schema. RotationModel, err := resourceIbmSmIamCredentialsSecretMapToRotationPolicy(d.Get("rotation").([]interface{})[0].(map[string]interface{})) if err != nil { log.Printf("[DEBUG] UpdateSecretMetadataWithContext failed: Reading Rotation parameter failed: %s", err) - return diag.FromErr(fmt.Errorf("UpdateSecretMetadataWithContext failed: Reading Rotation parameter failed: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateSecretMetadataWithContext failed: Reading Rotation parameter failed: %s", err), IAMCredentialsSecretResourceName, "update") + return tfErr.GetDiag() } patchVals.Rotation = RotationModel hasChange = true @@ -499,7 +539,8 @@ func resourceIbmSmIamCredentialsSecretUpdate(context context.Context, d *schema. _, response, err := secretsManagerClient.UpdateSecretMetadataWithContext(context, updateSecretMetadataOptions) if err != nil { log.Printf("[DEBUG] UpdateSecretMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateSecretMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateSecretMetadataWithContext failed %s\n%s", err, response), IAMCredentialsSecretResourceName, "update") + return tfErr.GetDiag() } } @@ -520,7 +561,8 @@ func resourceIbmSmIamCredentialsSecretUpdate(context context.Context, d *schema. resourceIbmSmIamCredentialsSecretRead(context, d, meta) } log.Printf("[DEBUG] UpdateSecretVersionMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateSecretVersionMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateSecretVersionMetadataWithContext failed %s\n%s", err, response), IAMCredentialsSecretResourceName, "update") + return tfErr.GetDiag() } } @@ -530,7 +572,8 @@ func resourceIbmSmIamCredentialsSecretUpdate(context context.Context, d *schema. func resourceIbmSmIamCredentialsSecretDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", IAMCredentialsSecretResourceName, "delete") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -546,7 +589,8 @@ func resourceIbmSmIamCredentialsSecretDelete(context context.Context, d *schema. response, err := secretsManagerClient.DeleteSecretWithContext(context, deleteSecretOptions) if err != nil { log.Printf("[DEBUG] DeleteSecretWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("DeleteSecretWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("DeleteSecretWithContext failed %s\n%s", err, response), IAMCredentialsSecretResourceName, "delete") + return tfErr.GetDiag() } d.SetId("") diff --git a/ibm/service/secretsmanager/resource_ibm_sm_imported_certificate.go b/ibm/service/secretsmanager/resource_ibm_sm_imported_certificate.go index c91f1c2d31..adc731ae96 100644 --- a/ibm/service/secretsmanager/resource_ibm_sm_imported_certificate.go +++ b/ibm/service/secretsmanager/resource_ibm_sm_imported_certificate.go @@ -223,7 +223,8 @@ func ResourceIbmSmImportedCertificate() *schema.Resource { func resourceIbmSmImportedCertificateCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", ImportedCertSecretResourceName, "create") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -234,14 +235,16 @@ func resourceIbmSmImportedCertificateCreate(context context.Context, d *schema.R secretPrototypeModel, err := resourceIbmSmImportedCertificateMapToSecretPrototype(d) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", ImportedCertSecretResourceName, "create") + return tfErr.GetDiag() } createSecretOptions.SetSecretPrototype(secretPrototypeModel) secretIntf, response, err := secretsManagerClient.CreateSecretWithContext(context, createSecretOptions) if err != nil { log.Printf("[DEBUG] CreateSecretWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateSecretWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateSecretWithContext failed: %s\n%s", err.Error(), response), ImportedCertSecretResourceName, "create") + return tfErr.GetDiag() } secret := secretIntf.(*secretsmanagerv2.ImportedCertificate) @@ -250,8 +253,8 @@ func resourceIbmSmImportedCertificateCreate(context context.Context, d *schema.R _, err = waitForIbmSmImportedCertificateCreate(secretsManagerClient, d) if err != nil { - return diag.FromErr(fmt.Errorf( - "Error waiting for resource IbmSmImportedCertificate (%s) to be created: %s", d.Id(), err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error waiting for resource IbmSmImportedCertificate (%s) to be created: %s", d.Id(), err.Error()), ImportedCertSecretResourceName, "create") + return tfErr.GetDiag() } return resourceIbmSmImportedCertificateRead(context, d, meta) @@ -294,12 +297,14 @@ func waitForIbmSmImportedCertificateCreate(secretsManagerClient *secretsmanagerv func resourceIbmSmImportedCertificateRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") if len(id) != 3 { - return diag.Errorf("Wrong format of resource ID. To import a secret use the format `//`") + tfErr := flex.TerraformErrorf(nil, "Wrong format of resource ID. To import a secret use the format `//`", ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } region := id[0] instanceId := id[1] @@ -317,105 +322,136 @@ func resourceIbmSmImportedCertificateRead(context context.Context, d *schema.Res return nil } log.Printf("[DEBUG] GetSecretWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretWithContext failed %s\n%s", err, response), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } secret := secretIntf.(*secretsmanagerv2.ImportedCertificate) if err = d.Set("secret_id", secretId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_id"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("instance_id", instanceId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting instance_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting instance_id"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("created_by", secret.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(secret.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("crn", secret.Crn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crn"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if secret.CustomMetadata != nil { d.Set("custom_metadata", secret.CustomMetadata) } if err = d.Set("description", secret.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("downloaded", secret.Downloaded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting downloaded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting downloaded"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if secret.Labels != nil { if err = d.Set("labels", secret.Labels); err != nil { - return diag.FromErr(fmt.Errorf("Error setting labels: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting labels"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("locks_total", flex.IntValue(secret.LocksTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locks_total"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("name", secret.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("secret_group_id", secret.SecretGroupID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_group_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_group_id"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", secret.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("state", flex.IntValue(secret.State)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("state_description", secret.StateDescription); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state_description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state_description"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(secret.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("versions_total", flex.IntValue(secret.VersionsTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting versions_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting versions_total"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("signing_algorithm", secret.SigningAlgorithm); err != nil { - return diag.FromErr(fmt.Errorf("Error setting signing_algorithm: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting signing_algorithm"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("common_name", secret.CommonName); err != nil { - return diag.FromErr(fmt.Errorf("Error setting common_name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting common_name"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("expiration_date", DateTimeToRFC3339(secret.ExpirationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting expiration_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting expiration_date"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("intermediate_included", secret.IntermediateIncluded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting intermediate_included: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting intermediate_included"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("issuer", secret.Issuer); err != nil { - return diag.FromErr(fmt.Errorf("Error setting issuer: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting issuer"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("key_algorithm", secret.KeyAlgorithm); err != nil { - return diag.FromErr(fmt.Errorf("Error setting key_algorithm: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting key_algorithm"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("private_key_included", secret.PrivateKeyIncluded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting private_key_included: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting private_key_included"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("serial_number", secret.SerialNumber); err != nil { - return diag.FromErr(fmt.Errorf("Error setting serial_number: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting serial_number"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } validityMap, err := resourceIbmSmImportedCertificateCertificateValidityToMap(secret.Validity) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("validity", []map[string]interface{}{validityMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting validity: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting validity"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("certificate", secret.Certificate); err != nil { - return diag.FromErr(fmt.Errorf("Error setting certificate: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting certificate"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("intermediate", secret.Intermediate); err != nil { - return diag.FromErr(fmt.Errorf("Error setting intermediate: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting intermediate"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("private_key", secret.PrivateKey); err != nil { - return diag.FromErr(fmt.Errorf("Error setting private_key: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting private_key"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } // Call get version metadata API to get the current version_custom_metadata @@ -426,13 +462,15 @@ func resourceIbmSmImportedCertificateRead(context context.Context, d *schema.Res versionMetadataIntf, response, err := secretsManagerClient.GetSecretVersionMetadataWithContext(context, getVersionMetdataOptions) if err != nil { log.Printf("[DEBUG] GetSecretVersionMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretVersionMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretVersionMetadataWithContext failed %s\n%s", err, response), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } versionMetadata := versionMetadataIntf.(*secretsmanagerv2.ImportedCertificateVersionMetadata) if versionMetadata.VersionCustomMetadata != nil { if err = d.Set("version_custom_metadata", versionMetadata.VersionCustomMetadata); err != nil { - return diag.FromErr(fmt.Errorf("Error setting version_custom_metadata: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting version_custom_metadata"), ImportedCertSecretResourceName, "read") + return tfErr.GetDiag() } } @@ -442,7 +480,8 @@ func resourceIbmSmImportedCertificateRead(context context.Context, d *schema.Res func resourceIbmSmImportedCertificateUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", ImportedCertSecretResourceName, "update") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -487,7 +526,8 @@ func resourceIbmSmImportedCertificateUpdate(context context.Context, d *schema.R _, response, err := secretsManagerClient.UpdateSecretMetadataWithContext(context, updateSecretMetadataOptions) if err != nil { log.Printf("[DEBUG] UpdateSecretMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateSecretMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateSecretMetadataWithContext failed %s\n%s", err, response), ImportedCertSecretResourceName, "update") + return tfErr.GetDiag() } } @@ -519,7 +559,8 @@ func resourceIbmSmImportedCertificateUpdate(context context.Context, d *schema.R resourceIbmSmImportedCertificateRead(context, d, meta) } log.Printf("[DEBUG] CreateSecretVersionWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateSecretVersionWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateSecretVersionWithContext failed %s\n%s", err, response), ImportedCertSecretResourceName, "update") + return tfErr.GetDiag() } } else if d.HasChange("version_custom_metadata") { // Apply change to version_custom_metadata in current version @@ -538,7 +579,8 @@ func resourceIbmSmImportedCertificateUpdate(context context.Context, d *schema.R resourceIbmSmImportedCertificateRead(context, d, meta) } log.Printf("[DEBUG] UpdateSecretVersionMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateSecretVersionMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateSecretVersionMetadataWithContext failed %s\n%s", err, response), ImportedCertSecretResourceName, "update") + return tfErr.GetDiag() } } return resourceIbmSmImportedCertificateRead(context, d, meta) @@ -547,7 +589,8 @@ func resourceIbmSmImportedCertificateUpdate(context context.Context, d *schema.R func resourceIbmSmImportedCertificateDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", ImportedCertSecretResourceName, "delete") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -563,7 +606,8 @@ func resourceIbmSmImportedCertificateDelete(context context.Context, d *schema.R response, err := secretsManagerClient.DeleteSecretWithContext(context, deleteSecretOptions) if err != nil { log.Printf("[DEBUG] DeleteSecretWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("DeleteSecretWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("DeleteSecretWithContext failed %s\n%s", err, response), ImportedCertSecretResourceName, "delete") + return tfErr.GetDiag() } d.SetId("") diff --git a/ibm/service/secretsmanager/resource_ibm_sm_kv_secret.go b/ibm/service/secretsmanager/resource_ibm_sm_kv_secret.go index f32d9ee23a..81a6f44be1 100644 --- a/ibm/service/secretsmanager/resource_ibm_sm_kv_secret.go +++ b/ibm/service/secretsmanager/resource_ibm_sm_kv_secret.go @@ -135,7 +135,8 @@ func ResourceIbmSmKvSecret() *schema.Resource { func resourceIbmSmKvSecretCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", KvSecretResourceName, "create") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -146,14 +147,16 @@ func resourceIbmSmKvSecretCreate(context context.Context, d *schema.ResourceData secretPrototypeModel, err := resourceIbmSmKvSecretMapToSecretPrototype(d) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", KvSecretResourceName, "create") + return tfErr.GetDiag() } createSecretOptions.SetSecretPrototype(secretPrototypeModel) secretIntf, response, err := secretsManagerClient.CreateSecretWithContext(context, createSecretOptions) if err != nil { log.Printf("[DEBUG] CreateSecretWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateSecretWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateSecretWithContext failed: %s\n%s", err.Error(), response), KvSecretResourceName, "create") + return tfErr.GetDiag() } secret := secretIntf.(*secretsmanagerv2.KVSecret) @@ -162,8 +165,8 @@ func resourceIbmSmKvSecretCreate(context context.Context, d *schema.ResourceData _, err = waitForIbmSmKvSecretCreate(secretsManagerClient, d) if err != nil { - return diag.FromErr(fmt.Errorf( - "Error waiting for resource IbmSmKvSecret (%s) to be created: %s", d.Id(), err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error waiting for resource IbmSmKvSecret (%s) to be created: %s", d.Id(), err.Error()), KvSecretResourceName, "create") + return tfErr.GetDiag() } return resourceIbmSmKvSecretRead(context, d, meta) @@ -206,12 +209,14 @@ func waitForIbmSmKvSecretCreate(secretsManagerClient *secretsmanagerv2.SecretsMa func resourceIbmSmKvSecretRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", KvSecretResourceName, "read") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") if len(id) != 3 { - return diag.Errorf("Wrong format of resource ID. To import a secret use the format `//`") + tfErr := flex.TerraformErrorf(nil, "Wrong format of resource ID. To import a secret use the format `//`", KvSecretResourceName, "read") + return tfErr.GetDiag() } region := id[0] instanceId := id[1] @@ -229,65 +234,83 @@ func resourceIbmSmKvSecretRead(context context.Context, d *schema.ResourceData, return nil } log.Printf("[DEBUG] GetSecretWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretWithContext failed %s\n%s", err, response), KvSecretResourceName, "read") + return tfErr.GetDiag() } secret := secretIntf.(*secretsmanagerv2.KVSecret) if err = d.Set("secret_id", secretId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_id"), KvSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("instance_id", instanceId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting instance_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting instance_id"), KvSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), KvSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("created_by", secret.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), KvSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(secret.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), KvSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("crn", secret.Crn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crn"), KvSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("downloaded", secret.Downloaded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting downloaded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting downloaded"), KvSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("locks_total", flex.IntValue(secret.LocksTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locks_total"), KvSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("name", secret.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), KvSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("secret_group_id", secret.SecretGroupID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_group_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_group_id"), KvSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", secret.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), KvSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("state", flex.IntValue(secret.State)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state"), KvSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("state_description", secret.StateDescription); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state_description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state_description"), KvSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(secret.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), KvSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("versions_total", flex.IntValue(secret.VersionsTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting versions_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting versions_total"), KvSecretResourceName, "read") + return tfErr.GetDiag() } if secret.CustomMetadata != nil { d.Set("custom_metadata", secret.CustomMetadata) } if err = d.Set("description", secret.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), KvSecretResourceName, "read") + return tfErr.GetDiag() } if secret.Labels != nil { if err = d.Set("labels", secret.Labels); err != nil { - return diag.FromErr(fmt.Errorf("Error setting labels: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting labels"), KvSecretResourceName, "read") + return tfErr.GetDiag() } } if secret.Data != nil { @@ -302,13 +325,15 @@ func resourceIbmSmKvSecretRead(context context.Context, d *schema.ResourceData, versionMetadataIntf, response, err := secretsManagerClient.GetSecretVersionMetadataWithContext(context, getVersionMetdataOptions) if err != nil { log.Printf("[DEBUG] GetSecretVersionMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretVersionMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretVersionMetadataWithContext failed %s\n%s", err, response), KvSecretResourceName, "read") + return tfErr.GetDiag() } versionMetadata := versionMetadataIntf.(*secretsmanagerv2.KVSecretVersionMetadata) if versionMetadata.VersionCustomMetadata != nil { if err = d.Set("version_custom_metadata", versionMetadata.VersionCustomMetadata); err != nil { - return diag.FromErr(fmt.Errorf("Error setting version_custom_metadata: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting version_custom_metadata"), KvSecretResourceName, "read") + return tfErr.GetDiag() } } @@ -318,7 +343,8 @@ func resourceIbmSmKvSecretRead(context context.Context, d *schema.ResourceData, func resourceIbmSmKvSecretUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", KvSecretResourceName, "update") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -363,7 +389,8 @@ func resourceIbmSmKvSecretUpdate(context context.Context, d *schema.ResourceData _, response, err := secretsManagerClient.UpdateSecretMetadataWithContext(context, updateSecretMetadataOptions) if err != nil { log.Printf("[DEBUG] UpdateSecretMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateSecretMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateSecretMetadataWithContext failed %s\n%s", err, response), KvSecretResourceName, "update") + return tfErr.GetDiag() } } @@ -389,7 +416,8 @@ func resourceIbmSmKvSecretUpdate(context context.Context, d *schema.ResourceData resourceIbmSmKvSecretRead(context, d, meta) } log.Printf("[DEBUG] CreateSecretVersionWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateSecretVersionWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateSecretVersionWithContext failed %s\n%s", err, response), KvSecretResourceName, "update") + return tfErr.GetDiag() } } else if d.HasChange("version_custom_metadata") { // Apply change to version_custom_metadata in current version @@ -408,7 +436,8 @@ func resourceIbmSmKvSecretUpdate(context context.Context, d *schema.ResourceData resourceIbmSmKvSecretRead(context, d, meta) } log.Printf("[DEBUG] UpdateSecretVersionMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateSecretVersionMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateSecretVersionMetadataWithContext failed %s\n%s", err, response), KvSecretResourceName, "update") + return tfErr.GetDiag() } } @@ -418,7 +447,8 @@ func resourceIbmSmKvSecretUpdate(context context.Context, d *schema.ResourceData func resourceIbmSmKvSecretDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", KvSecretResourceName, "delete") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -434,7 +464,8 @@ func resourceIbmSmKvSecretDelete(context context.Context, d *schema.ResourceData response, err := secretsManagerClient.DeleteSecretWithContext(context, deleteSecretOptions) if err != nil { log.Printf("[DEBUG] DeleteSecretWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("DeleteSecretWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("DeleteSecretWithContext failed %s\n%s", err, response), KvSecretResourceName, "delete") + return tfErr.GetDiag() } d.SetId("") diff --git a/ibm/service/secretsmanager/resource_ibm_sm_private_certificate.go b/ibm/service/secretsmanager/resource_ibm_sm_private_certificate.go index 6cd0aa6faf..8a2e424619 100644 --- a/ibm/service/secretsmanager/resource_ibm_sm_private_certificate.go +++ b/ibm/service/secretsmanager/resource_ibm_sm_private_certificate.go @@ -320,7 +320,8 @@ func ResourceIbmSmPrivateCertificate() *schema.Resource { func resourceIbmSmPrivateCertificateCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertSecretResourceName, "create") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -331,14 +332,16 @@ func resourceIbmSmPrivateCertificateCreate(context context.Context, d *schema.Re secretPrototypeModel, err := resourceIbmSmPrivateCertificateMapToSecretPrototype(d) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertSecretResourceName, "create") + return tfErr.GetDiag() } createSecretOptions.SetSecretPrototype(secretPrototypeModel) secretIntf, response, err := secretsManagerClient.CreateSecretWithContext(context, createSecretOptions) if err != nil { log.Printf("[DEBUG] CreateSecretWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateSecretWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateSecretWithContext failed: %s\n%s", err.Error(), response), PrivateCertSecretResourceName, "create") + return tfErr.GetDiag() } secret := secretIntf.(*secretsmanagerv2.PrivateCertificate) @@ -347,8 +350,8 @@ func resourceIbmSmPrivateCertificateCreate(context context.Context, d *schema.Re _, err = waitForIbmSmPrivateCertificateCreate(secretsManagerClient, d) if err != nil { - return diag.FromErr(fmt.Errorf( - "Error waiting for resource IbmSmPrivateCertificate (%s) to be created: %s", d.Id(), err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error waiting for resource IbmSmPrivateCertificate (%s) to be created: %s", d.Id(), err.Error()), PrivateCertSecretResourceName, "create") + return tfErr.GetDiag() } return resourceIbmSmPrivateCertificateRead(context, d, meta) @@ -391,12 +394,14 @@ func waitForIbmSmPrivateCertificateCreate(secretsManagerClient *secretsmanagerv2 func resourceIbmSmPrivateCertificateRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") if len(id) != 3 { - return diag.Errorf("Wrong format of resource ID. To import a secret use the format `//`") + tfErr := flex.TerraformErrorf(nil, "Wrong format of resource ID. To import a secret use the format `//`", PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } region := id[0] instanceId := id[1] @@ -414,135 +419,173 @@ func resourceIbmSmPrivateCertificateRead(context context.Context, d *schema.Reso return nil } log.Printf("[DEBUG] GetSecretWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretWithContext failed %s\n%s", err, response), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } secret := secretIntf.(*secretsmanagerv2.PrivateCertificate) if err = d.Set("secret_id", secretId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_id"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("instance_id", instanceId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting instance_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting instance_id"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("created_by", secret.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(secret.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("crn", secret.Crn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crn"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if secret.CustomMetadata != nil { d.Set("custom_metadata", secret.CustomMetadata) } if err = d.Set("description", secret.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("downloaded", secret.Downloaded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting downloaded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting downloaded"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if secret.Labels != nil { if err = d.Set("labels", secret.Labels); err != nil { - return diag.FromErr(fmt.Errorf("Error setting labels: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting labels"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("locks_total", flex.IntValue(secret.LocksTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locks_total"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("name", secret.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("secret_group_id", secret.SecretGroupID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_group_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_group_id"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", secret.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("state", flex.IntValue(secret.State)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("state_description", secret.StateDescription); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state_description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state_description"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(secret.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("versions_total", flex.IntValue(secret.VersionsTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting versions_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting versions_total"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("signing_algorithm", secret.SigningAlgorithm); err != nil { - return diag.FromErr(fmt.Errorf("Error setting signing_algorithm: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting signing_algorithm"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if secret.AltNames != nil { if err = d.Set("alt_names", secret.AltNames); err != nil { - return diag.FromErr(fmt.Errorf("Error setting alt_names: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting alt_names"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("certificate_authority", secret.CertificateAuthority); err != nil { - return diag.FromErr(fmt.Errorf("Error setting certificate_authority: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting certificate_authority"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("certificate_template", secret.CertificateTemplate); err != nil { - return diag.FromErr(fmt.Errorf("Error setting certificate_template: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting certificate_template"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("common_name", secret.CommonName); err != nil { - return diag.FromErr(fmt.Errorf("Error setting common_name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting common_name"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("expiration_date", DateTimeToRFC3339(secret.ExpirationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting expiration_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting expiration_date"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("issuer", secret.Issuer); err != nil { - return diag.FromErr(fmt.Errorf("Error setting issuer: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting issuer"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("key_algorithm", secret.KeyAlgorithm); err != nil { - return diag.FromErr(fmt.Errorf("Error setting key_algorithm: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting key_algorithm"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("next_rotation_date", DateTimeToRFC3339(secret.NextRotationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting next_rotation_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting next_rotation_date"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } rotationMap, err := resourceIbmSmPrivateCertificateRotationPolicyToMap(secret.Rotation) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if len(rotationMap) > 0 { if err = d.Set("rotation", []map[string]interface{}{rotationMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting rotation: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting rotation"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("serial_number", secret.SerialNumber); err != nil { - return diag.FromErr(fmt.Errorf("Error setting serial_number: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting serial_number"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if secret.Validity != nil { validityMap, err := resourceIbmSmPrivateCertificateCertificateValidityToMap(secret.Validity) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("validity", []map[string]interface{}{validityMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting validity: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting validity"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("revocation_time_seconds", flex.IntValue(secret.RevocationTimeSeconds)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting revocation_time_seconds: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting revocation_time_seconds"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("revocation_time_rfc3339", DateTimeToRFC3339(secret.RevocationTimeRfc3339)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting revocation_time_rfc3339: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting revocation_time_rfc3339"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("certificate", secret.Certificate); err != nil { - return diag.FromErr(fmt.Errorf("Error setting certificate: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting certificate"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("private_key", secret.PrivateKey); err != nil { - return diag.FromErr(fmt.Errorf("Error setting private_key: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting private_key"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("issuing_ca", secret.IssuingCa); err != nil { - return diag.FromErr(fmt.Errorf("Error setting issuing_ca: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting issuing_ca"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } if secret.CaChain != nil { if err = d.Set("ca_chain", secret.CaChain); err != nil { - return diag.FromErr(fmt.Errorf("Error setting ca_chain: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting ca_chain"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } } @@ -554,13 +597,15 @@ func resourceIbmSmPrivateCertificateRead(context context.Context, d *schema.Reso versionMetadataIntf, response, err := secretsManagerClient.GetSecretVersionMetadataWithContext(context, getVersionMetdataOptions) if err != nil { log.Printf("[DEBUG] GetSecretVersionMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretVersionMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretVersionMetadataWithContext failed %s\n%s", err, response), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } versionMetadata := versionMetadataIntf.(*secretsmanagerv2.PrivateCertificateVersionMetadata) if versionMetadata.VersionCustomMetadata != nil { if err = d.Set("version_custom_metadata", versionMetadata.VersionCustomMetadata); err != nil { - return diag.FromErr(fmt.Errorf("Error setting version_custom_metadata: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting version_custom_metadata"), PrivateCertSecretResourceName, "read") + return tfErr.GetDiag() } } return nil @@ -569,7 +614,8 @@ func resourceIbmSmPrivateCertificateRead(context context.Context, d *schema.Reso func resourceIbmSmPrivateCertificateUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertSecretResourceName, "update") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -611,7 +657,8 @@ func resourceIbmSmPrivateCertificateUpdate(context context.Context, d *schema.Re RotationModel, err := resourceIbmSmPrivateCertificateMapToRotationPolicy(d.Get("rotation").([]interface{})[0].(map[string]interface{})) if err != nil { log.Printf("[DEBUG] UpdateSecretMetadataWithContext failed: Reading Rotation parameter failed: %s", err) - return diag.FromErr(fmt.Errorf("UpdateSecretMetadataWithContext failed: Reading Rotation parameter failed: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateSecretMetadataWithContext failed: Reading Rotation parameter failed: %s", err), PrivateCertSecretResourceName, "update") + return tfErr.GetDiag() } patchVals.Rotation = RotationModel hasChange = true @@ -622,7 +669,8 @@ func resourceIbmSmPrivateCertificateUpdate(context context.Context, d *schema.Re _, response, err := secretsManagerClient.UpdateSecretMetadataWithContext(context, updateSecretMetadataOptions) if err != nil { log.Printf("[DEBUG] UpdateSecretMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateSecretMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateSecretMetadataWithContext failed %s\n%s", err, response), PrivateCertSecretResourceName, "update") + return tfErr.GetDiag() } } @@ -643,7 +691,8 @@ func resourceIbmSmPrivateCertificateUpdate(context context.Context, d *schema.Re resourceIbmSmPrivateCertificateRead(context, d, meta) } log.Printf("[DEBUG] UpdateSecretVersionMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateSecretVersionMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateSecretVersionMetadataWithContext failed %s\n%s", err, response), PrivateCertSecretResourceName, "update") + return tfErr.GetDiag() } } @@ -653,7 +702,8 @@ func resourceIbmSmPrivateCertificateUpdate(context context.Context, d *schema.Re func resourceIbmSmPrivateCertificateDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertSecretResourceName, "delete") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -669,7 +719,8 @@ func resourceIbmSmPrivateCertificateDelete(context context.Context, d *schema.Re response, err := secretsManagerClient.DeleteSecretWithContext(context, deleteSecretOptions) if err != nil { log.Printf("[DEBUG] DeleteSecretWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("DeleteSecretWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("DeleteSecretWithContext failed %s\n%s", err, response), PrivateCertSecretResourceName, "delete") + return tfErr.GetDiag() } d.SetId("") diff --git a/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_action_set_signed.go b/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_action_set_signed.go index 99f3836a8e..fe29f3c189 100644 --- a/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_action_set_signed.go +++ b/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_action_set_signed.go @@ -3,6 +3,7 @@ package secretsmanager import ( "context" "fmt" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM/go-sdk-core/v5/core" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -47,7 +48,8 @@ func ResourceIbmSmPrivateCertificateConfigurationActionSetSigned() *schema.Resou func resourceIbmSmPrivateCertificateConfigurationActionSetSignedCreateOrUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertConfigActionSetSigned, "create/update") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -58,7 +60,8 @@ func resourceIbmSmPrivateCertificateConfigurationActionSetSignedCreateOrUpdate(c configurationActionPrototypeModel, err := resourceIbmSmPrivateCertificateConfigurationActionSetSignedPrototype(d) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertConfigActionSetSigned, "create/update") + return tfErr.GetDiag() } createConfigurationActionOptions.SetConfigActionPrototype(configurationActionPrototypeModel) createConfigurationActionOptions.SetName(d.Get("name").(string)) @@ -66,7 +69,8 @@ func resourceIbmSmPrivateCertificateConfigurationActionSetSignedCreateOrUpdate(c _, response, err := secretsManagerClient.CreateConfigurationActionWithContext(context, createConfigurationActionOptions) if err != nil { log.Printf("[DEBUG] CreateConfigurationActionWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateConfigurationActionWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateConfigurationActionWithContext failed: %s\n%s", err.Error(), response), PrivateCertConfigActionSetSigned, "create/update") + return tfErr.GetDiag() } d.SetId(fmt.Sprintf("%s/%s/%s/set_signed", region, instanceId, d.Get("name").(string))) diff --git a/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_action_sign_csr.go b/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_action_sign_csr.go index 0c808c4791..e177853407 100644 --- a/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_action_sign_csr.go +++ b/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_action_sign_csr.go @@ -212,7 +212,8 @@ func ResourceIbmSmPrivateCertificateConfigurationActionSignCsr() *schema.Resourc func resourceIbmSmPrivateCertificateConfigurationActionSignCsrCreateOrUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertConfigActionSignCsr, "create/update") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -223,7 +224,8 @@ func resourceIbmSmPrivateCertificateConfigurationActionSignCsrCreateOrUpdate(con configurationActionPrototypeModel, err := resourceIbmSmPrivateCertificateConfigurationActionSignCsrMapToConfigurationActionPrototype(d) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertConfigActionSignCsr, "create/update") + return tfErr.GetDiag() } createConfigurationActionOptions.SetConfigActionPrototype(configurationActionPrototypeModel) createConfigurationActionOptions.SetName(d.Get("name").(string)) @@ -231,7 +233,8 @@ func resourceIbmSmPrivateCertificateConfigurationActionSignCsrCreateOrUpdate(con configurationActionIntf, response, err := secretsManagerClient.CreateConfigurationActionWithContext(context, createConfigurationActionOptions) if err != nil { log.Printf("[DEBUG] CreateConfigurationActionWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateConfigurationActionWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateConfigurationActionWithContext failed: %s\n%s", err.Error(), response), PrivateCertConfigActionSignCsr, "create/update") + return tfErr.GetDiag() } configurationAction := configurationActionIntf.(*secretsmanagerv2.PrivateCertificateConfigurationActionSignCSR) @@ -239,10 +242,12 @@ func resourceIbmSmPrivateCertificateConfigurationActionSignCsrCreateOrUpdate(con if configurationAction.Data != nil { dataMap, err := resourceIbmSmPrivateCertificateConfigurationActionSignCsrDataToMap(*configurationAction.Data) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertConfigActionSignCsr, "create/update") + return tfErr.GetDiag() } if err = d.Set("data", []map[string]interface{}{dataMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting data: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting data: %s", err), PrivateCertConfigActionSignCsr, "create/update") + return tfErr.GetDiag() } } diff --git a/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_intermediate_ca.go b/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_intermediate_ca.go index e82d66747c..e774f2f764 100644 --- a/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_intermediate_ca.go +++ b/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_intermediate_ca.go @@ -389,7 +389,8 @@ func ResourceIbmSmPrivateCertificateConfigurationIntermediateCA() *schema.Resour func resourceIbmSmPrivateCertificateConfigurationIntermediateCACreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertConfigIntermediateCAResourceName, "create") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -400,14 +401,16 @@ func resourceIbmSmPrivateCertificateConfigurationIntermediateCACreate(context co configurationPrototypeModel, err := resourceIbmSmPrivateCertificateConfigurationIntermediateCAMapToConfigurationPrototype(d) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertConfigIntermediateCAResourceName, "create") + return tfErr.GetDiag() } createConfigurationOptions.SetConfigurationPrototype(configurationPrototypeModel) configurationIntf, response, err := secretsManagerClient.CreateConfigurationWithContext(context, createConfigurationOptions) if err != nil { log.Printf("[DEBUG] CreateConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateConfigurationWithContext failed: %s\n%s", err.Error(), response), PrivateCertConfigIntermediateCAResourceName, "create") + return tfErr.GetDiag() } configuration := configurationIntf.(*secretsmanagerv2.PrivateCertificateConfigurationIntermediateCA) @@ -421,17 +424,20 @@ func resourceIbmSmPrivateCertificateConfigurationIntermediateCACreate(context co createConfigurationActionOptions.SetName(d.Get("issuer").(string)) configurationActionPrototypeModel, err := resourceIbmSmConfigurationActionPrivateCertificateSignIntermediateCAMapToConfigurationActionPrototype(d) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertConfigIntermediateCAResourceName, "create") + return tfErr.GetDiag() } createConfigurationActionOptions.SetConfigActionPrototype(configurationActionPrototypeModel) _, responseAction, errAction := secretsManagerClient.CreateConfigurationActionWithContext(context, createConfigurationActionOptions) if errAction != nil { log.Printf("[DEBUG] CreateConfigurationActionWithContext failed %s\n%s", errAction, responseAction) - return diag.FromErr(fmt.Errorf("CreateConfigurationActionWithContext failed %s\n%s", errAction, responseAction)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateConfigurationActionWithContext failed %s\n%s", errAction, responseAction), PrivateCertConfigIntermediateCAResourceName, "create") + return tfErr.GetDiag() } } else { - return diag.FromErr(fmt.Errorf("`issuer` parameter is missing")) + tfErr := flex.TerraformErrorf(nil, "`issuer` parameter is missing", PrivateCertConfigIntermediateCAResourceName, "create") + return tfErr.GetDiag() } } @@ -441,12 +447,14 @@ func resourceIbmSmPrivateCertificateConfigurationIntermediateCACreate(context co func resourceIbmSmPrivateCertificateConfigurationIntermediateCARead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") if len(id) != 3 { - return diag.Errorf("Wrong format of resource ID. To import an intermediate CA use the format `//`") + tfErr := flex.TerraformErrorf(nil, "Wrong format of resource ID. To import an intermediate CA use the format `//`", PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } region := id[0] instanceId := id[1] @@ -464,151 +472,190 @@ func resourceIbmSmPrivateCertificateConfigurationIntermediateCARead(context cont return nil } log.Printf("[DEBUG] GetConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetConfigurationWithContext failed %s\n%s", err, response), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } configuration := configurationIntf.(*secretsmanagerv2.PrivateCertificateConfigurationIntermediateCA) if err = d.Set("instance_id", instanceId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting instance_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting instance_id"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("name", configuration.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("config_type", configuration.ConfigType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting config_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting config_type"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", configuration.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("max_ttl_seconds", flex.IntValue(configuration.MaxTtlSeconds)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting max_ttl_seconds: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting max_ttl_seconds"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } if d.Get("max_ttl") == nil || d.Get("max_ttl") == "" { if err = d.Set("max_ttl", strconv.FormatInt(*configuration.MaxTtlSeconds, 10)+"s"); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting max_ttl"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("crl_expiry_seconds", flex.IntValue(configuration.CrlExpirySeconds)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crl_expiry_seconds: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crl_expiry_seconds"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } if d.Get("crl_expiry") == nil || d.Get("crl_expiry") == "" { if err = d.Set("crl_expiry", strconv.FormatInt(*configuration.CrlExpirySeconds, 10)+"s"); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crl_expiry"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("signing_method", configuration.SigningMethod); err != nil { - return diag.FromErr(fmt.Errorf("Error setting signing_method: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting signing_method"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("issuer", configuration.Issuer); err != nil { - return diag.FromErr(fmt.Errorf("Error setting issuer: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting issuer"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("crl_disable", configuration.CrlDisable); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crl_disable: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crl_disable"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("crl_distribution_points_encoded", configuration.CrlDistributionPointsEncoded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crl_distribution_points_encoded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crl_distribution_points_encoded"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("issuing_certificates_urls_encoded", configuration.IssuingCertificatesUrlsEncoded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting issuing_certificates_urls_encoded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting issuing_certificates_urls_encoded"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("common_name", configuration.CommonName); err != nil { - return diag.FromErr(fmt.Errorf("Error setting common_name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting common_name"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } if configuration.AltNames != nil { if err = d.Set("alt_names", configuration.AltNames); err != nil { - return diag.FromErr(fmt.Errorf("Error setting alt_names: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting alt_names"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("ip_sans", configuration.IpSans); err != nil { - return diag.FromErr(fmt.Errorf("Error setting ip_sans: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting ip_sans"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("uri_sans", configuration.UriSans); err != nil { - return diag.FromErr(fmt.Errorf("Error setting uri_sans: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting uri_sans"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } if configuration.OtherSans != nil { if err = d.Set("other_sans", configuration.OtherSans); err != nil { - return diag.FromErr(fmt.Errorf("Error setting other_sans: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting other_sans"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("format", configuration.Format); err != nil { - return diag.FromErr(fmt.Errorf("Error setting format: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting format"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("private_key_format", configuration.PrivateKeyFormat); err != nil { - return diag.FromErr(fmt.Errorf("Error setting private_key_format: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting private_key_format"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("key_type", configuration.KeyType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting key_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting key_type"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("key_bits", flex.IntValue(configuration.KeyBits)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting key_bits: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting key_bits"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("exclude_cn_from_sans", configuration.ExcludeCnFromSans); err != nil { - return diag.FromErr(fmt.Errorf("Error setting exclude_cn_from_sans: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting exclude_cn_from_sans"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } if configuration.Ou != nil { if err = d.Set("ou", configuration.Ou); err != nil { - return diag.FromErr(fmt.Errorf("Error setting ou: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting ou"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } } if configuration.Organization != nil { if err = d.Set("organization", configuration.Organization); err != nil { - return diag.FromErr(fmt.Errorf("Error setting organization: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting organization"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } } if configuration.Country != nil { if err = d.Set("country", configuration.Country); err != nil { - return diag.FromErr(fmt.Errorf("Error setting country: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting country"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } } if configuration.Locality != nil { if err = d.Set("locality", configuration.Locality); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locality: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locality"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } } if configuration.Province != nil { if err = d.Set("province", configuration.Province); err != nil { - return diag.FromErr(fmt.Errorf("Error setting province: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting province"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } } if configuration.StreetAddress != nil { if err = d.Set("street_address", configuration.StreetAddress); err != nil { - return diag.FromErr(fmt.Errorf("Error setting street_address: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting street_address"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } } if configuration.PostalCode != nil { if err = d.Set("postal_code", configuration.PostalCode); err != nil { - return diag.FromErr(fmt.Errorf("Error setting postal_code: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting postal_code"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("serial_number", configuration.SerialNumber); err != nil { - return diag.FromErr(fmt.Errorf("Error setting serial_number: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting serial_number"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("status", configuration.Status); err != nil { - return diag.FromErr(fmt.Errorf("Error setting status: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting status"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("expiration_date", DateTimeToRFC3339(configuration.ExpirationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting expiration_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting expiration_date"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } if configuration.Data != nil { dataMap, err := resourceIbmSmPrivateCertificateConfigurationIntermediateCAPrivateCertificateCADataToMap(configuration.Data) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("data", []map[string]interface{}{dataMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting data: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting data"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } } if configuration.CryptoKey != nil { cryptoKeyMap, err := resourceIbmSmPrivateCertificateConfigurationCryptoKeyToMap(configuration.CryptoKey) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } if len(cryptoKeyMap) > 0 { if err = d.Set("crypto_key", []map[string]interface{}{cryptoKeyMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crypto_key: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crypto_key"), PrivateCertConfigIntermediateCAResourceName, "read") + return tfErr.GetDiag() } } } @@ -660,7 +707,8 @@ func resourceIbmSmPrivateCertificateConfigurationCryptoKeyProviderToMap(provider func resourceIbmSmPrivateCertificateConfigurationIntermediateCAUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertConfigIntermediateCAResourceName, "update") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -708,7 +756,8 @@ func resourceIbmSmPrivateCertificateConfigurationIntermediateCAUpdate(context co _, response, err := secretsManagerClient.UpdateConfigurationWithContext(context, updateConfigurationOptions) if err != nil { log.Printf("[DEBUG] UpdateConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateConfigurationWithContext failed %s\n%s", err, response), PrivateCertConfigIntermediateCAResourceName, "update") + return tfErr.GetDiag() } } @@ -718,7 +767,8 @@ func resourceIbmSmPrivateCertificateConfigurationIntermediateCAUpdate(context co func resourceIbmSmPrivateCertificateConfigurationIntermediateCADelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertConfigIntermediateCAResourceName, "delete") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -734,7 +784,8 @@ func resourceIbmSmPrivateCertificateConfigurationIntermediateCADelete(context co response, err := secretsManagerClient.DeleteConfigurationWithContext(context, deleteConfigurationOptions) if err != nil { log.Printf("[DEBUG] DeleteConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("DeleteConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("DeleteConfigurationWithContext failed %s\n%s", err, response), PrivateCertConfigIntermediateCAResourceName, "delete") + return tfErr.GetDiag() } d.SetId("") diff --git a/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_intermediate_ca_test.go b/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_intermediate_ca_test.go index 0983c1c3e0..0865e6ec58 100644 --- a/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_intermediate_ca_test.go +++ b/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_intermediate_ca_test.go @@ -186,7 +186,7 @@ func privateCertificateIntermediateCAConfigCryptoKey() string { common_name = "ibm.com" crypto_key { allow_generate_key = true - label = "tf_test" + label = "e2e-tf-test" provider { type = "%s" instance_crn = "%s" diff --git a/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_root_ca.go b/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_root_ca.go index e51d97856c..77e167787a 100644 --- a/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_root_ca.go +++ b/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_root_ca.go @@ -393,7 +393,8 @@ func ResourceIbmSmPrivateCertificateConfigurationRootCA() *schema.Resource { func resourceIbmSmPrivateCertificateConfigurationRootCACreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertConfigRootCAResourceName, "create") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -404,14 +405,16 @@ func resourceIbmSmPrivateCertificateConfigurationRootCACreate(context context.Co configurationPrototypeModel, err := resourceIbmSmPrivateCertificateConfigurationRootCAMapToConfigurationPrototype(d) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertConfigRootCAResourceName, "create") + return tfErr.GetDiag() } createConfigurationOptions.SetConfigurationPrototype(configurationPrototypeModel) configurationIntf, response, err := secretsManagerClient.CreateConfigurationWithContext(context, createConfigurationOptions) if err != nil { log.Printf("[DEBUG] CreateConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateConfigurationWithContext failed: %s\n%s", err.Error(), response), PrivateCertConfigRootCAResourceName, "create") + return tfErr.GetDiag() } configuration := configurationIntf.(*secretsmanagerv2.PrivateCertificateConfigurationRootCA) @@ -423,12 +426,14 @@ func resourceIbmSmPrivateCertificateConfigurationRootCACreate(context context.Co func resourceIbmSmPrivateCertificateConfigurationRootCARead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") if len(id) != 3 { - return diag.Errorf("Wrong format of resource ID. To import a root CA use the format `//`") + tfErr := flex.TerraformErrorf(nil, "Wrong format of resource ID. To import a root CA use the format `//`", PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } region := id[0] instanceId := id[1] @@ -446,165 +451,207 @@ func resourceIbmSmPrivateCertificateConfigurationRootCARead(context context.Cont return nil } log.Printf("[DEBUG] GetConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetConfigurationWithContext failed %s\n%s", err, response), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } configuration := configurationIntf.(*secretsmanagerv2.PrivateCertificateConfigurationRootCA) if err = d.Set("instance_id", instanceId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting instance_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting instance_id"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("name", configuration.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", configuration.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("created_by", configuration.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(configuration.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(configuration.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("max_ttl_seconds", flex.IntValue(configuration.MaxTtlSeconds)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting max_ttl_seconds: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting max_ttl_seconds"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if d.Get("max_ttl") == nil || d.Get("max_ttl") == "" { if err = d.Set("max_ttl", strconv.FormatInt(*configuration.MaxTtlSeconds, 10)+"s"); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting max_ttl"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("crl_expiry_seconds", flex.IntValue(configuration.CrlExpirySeconds)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crl_expiry_seconds: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crl_expiry_seconds"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if d.Get("crl_expiry") == nil || d.Get("crl_expiry") == "" { if err = d.Set("crl_expiry", strconv.FormatInt(*configuration.CrlExpirySeconds, 10)+"s"); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crl_expiry"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("crl_disable", configuration.CrlDisable); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crl_disable: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crl_disable"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("crl_distribution_points_encoded", configuration.CrlDistributionPointsEncoded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crl_distribution_points_encoded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crl_distribution_points_encoded"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("issuing_certificates_urls_encoded", configuration.IssuingCertificatesUrlsEncoded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting issuing_certificates_urls_encoded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting issuing_certificates_urls_encoded"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("common_name", configuration.CommonName); err != nil { - return diag.FromErr(fmt.Errorf("Error setting common_name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting common_name"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if configuration.AltNames != nil { if err = d.Set("alt_names", configuration.AltNames); err != nil { - return diag.FromErr(fmt.Errorf("Error setting alt_names: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting alt_names"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("ip_sans", configuration.IpSans); err != nil { - return diag.FromErr(fmt.Errorf("Error setting ip_sans: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting ip_sans"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("uri_sans", configuration.UriSans); err != nil { - return diag.FromErr(fmt.Errorf("Error setting uri_sans: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting uri_sans"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if configuration.OtherSans != nil { if err = d.Set("other_sans", configuration.OtherSans); err != nil { - return diag.FromErr(fmt.Errorf("Error setting other_sans: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting other_sans"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("ttl_seconds", flex.IntValue(configuration.TtlSeconds)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting ttl_seconds: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting ttl_seconds"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("format", configuration.Format); err != nil { - return diag.FromErr(fmt.Errorf("Error setting format: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting format"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("private_key_format", configuration.PrivateKeyFormat); err != nil { - return diag.FromErr(fmt.Errorf("Error setting private_key_format: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting private_key_format"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("key_type", configuration.KeyType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting key_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting key_type"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("key_bits", flex.IntValue(configuration.KeyBits)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting key_bits: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting key_bits"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("max_path_length", flex.IntValue(configuration.MaxPathLength)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting max_path_length: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting max_path_length"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("exclude_cn_from_sans", configuration.ExcludeCnFromSans); err != nil { - return diag.FromErr(fmt.Errorf("Error setting exclude_cn_from_sans: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting exclude_cn_from_sans"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if configuration.PermittedDnsDomains != nil { if err = d.Set("permitted_dns_domains", configuration.PermittedDnsDomains); err != nil { - return diag.FromErr(fmt.Errorf("Error setting permitted_dns_domains: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting permitted_dns_domains"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } } if configuration.Ou != nil { if err = d.Set("ou", configuration.Ou); err != nil { - return diag.FromErr(fmt.Errorf("Error setting ou: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting ou"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } } if configuration.Organization != nil { if err = d.Set("organization", configuration.Organization); err != nil { - return diag.FromErr(fmt.Errorf("Error setting organization: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting organization"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } } if configuration.Country != nil { if err = d.Set("country", configuration.Country); err != nil { - return diag.FromErr(fmt.Errorf("Error setting country: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting country"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } } if configuration.Locality != nil { if err = d.Set("locality", configuration.Locality); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locality: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locality"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } } if configuration.Province != nil { if err = d.Set("province", configuration.Province); err != nil { - return diag.FromErr(fmt.Errorf("Error setting province: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting province"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } } if configuration.StreetAddress != nil { if err = d.Set("street_address", configuration.StreetAddress); err != nil { - return diag.FromErr(fmt.Errorf("Error setting street_address: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting street_address"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } } if configuration.PostalCode != nil { if err = d.Set("postal_code", configuration.PostalCode); err != nil { - return diag.FromErr(fmt.Errorf("Error setting postal_code: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting postal_code"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("serial_number", configuration.SerialNumber); err != nil { - return diag.FromErr(fmt.Errorf("Error setting serial_number: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting serial_number"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("status", configuration.Status); err != nil { - return diag.FromErr(fmt.Errorf("Error setting status: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting status"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("expiration_date", DateTimeToRFC3339(configuration.ExpirationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting expiration_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting expiration_date"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if configuration.Data != nil { dataMap, err := resourceIbmSmPrivateCertificateConfigurationRootCAPrivateCertificateCADataToMap(configuration.Data) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("data", []map[string]interface{}{dataMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting data: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting data"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } } if configuration.CryptoKey != nil { cryptoKeyMap, err := resourceIbmSmPrivateCertificateConfigurationCryptoKeyToMap(configuration.CryptoKey) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } if len(cryptoKeyMap) > 0 { if err = d.Set("crypto_key", []map[string]interface{}{cryptoKeyMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crypto_key: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crypto_key"), PrivateCertConfigRootCAResourceName, "read") + return tfErr.GetDiag() } } } @@ -615,7 +662,8 @@ func resourceIbmSmPrivateCertificateConfigurationRootCARead(context context.Cont func resourceIbmSmPrivateCertificateConfigurationRootCAUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertConfigRootCAResourceName, "update") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -658,7 +706,8 @@ func resourceIbmSmPrivateCertificateConfigurationRootCAUpdate(context context.Co _, response, err := secretsManagerClient.UpdateConfigurationWithContext(context, updateConfigurationOptions) if err != nil { log.Printf("[DEBUG] UpdateConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateConfigurationWithContext failed %s\n%s", err, response), PrivateCertConfigRootCAResourceName, "update") + return tfErr.GetDiag() } } @@ -668,7 +717,8 @@ func resourceIbmSmPrivateCertificateConfigurationRootCAUpdate(context context.Co func resourceIbmSmPrivateCertificateConfigurationRootCADelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertConfigRootCAResourceName, "delete") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -684,7 +734,8 @@ func resourceIbmSmPrivateCertificateConfigurationRootCADelete(context context.Co response, err := secretsManagerClient.DeleteConfigurationWithContext(context, deleteConfigurationOptions) if err != nil { log.Printf("[DEBUG] DeleteConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("DeleteConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("DeleteConfigurationWithContext failed %s\n%s", err, response), PrivateCertConfigRootCAResourceName, "delete") + return tfErr.GetDiag() } d.SetId("") diff --git a/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_root_ca_test.go b/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_root_ca_test.go index 7d3d10de13..b9825fd9e5 100644 --- a/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_root_ca_test.go +++ b/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_root_ca_test.go @@ -184,7 +184,7 @@ func privateCertificateRootCAConfigCryptoKey() string { alt_names = ["ddd.com", "aaa.com"] crypto_key { allow_generate_key = true - label = "tf_test" + label = "e2e-tf-test" provider { type = "%s" instance_crn = "%s" diff --git a/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_template.go b/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_template.go index fbebe341a0..d7c104cf7d 100644 --- a/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_template.go +++ b/ibm/service/secretsmanager/resource_ibm_sm_private_certificate_configuration_template.go @@ -325,7 +325,8 @@ func ResourceIbmSmPrivateCertificateConfigurationTemplate() *schema.Resource { func resourceIbmSmPrivateCertificateConfigurationTemplateCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertConfigTemplateResourceName, "create") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -336,14 +337,16 @@ func resourceIbmSmPrivateCertificateConfigurationTemplateCreate(context context. configurationPrototypeModel, err := resourceIbmSmPrivateCertificateConfigurationTemplateMapToConfigurationPrototype(d) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertConfigTemplateResourceName, "create") + return tfErr.GetDiag() } createConfigurationOptions.SetConfigurationPrototype(configurationPrototypeModel) configurationIntf, response, err := secretsManagerClient.CreateConfigurationWithContext(context, createConfigurationOptions) if err != nil { log.Printf("[DEBUG] CreateConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateConfigurationWithContext failed: %s\n%s", err.Error(), response), PrivateCertConfigTemplateResourceName, "create") + return tfErr.GetDiag() } configuration := configurationIntf.(*secretsmanagerv2.PrivateCertificateConfigurationTemplate) @@ -355,12 +358,14 @@ func resourceIbmSmPrivateCertificateConfigurationTemplateCreate(context context. func resourceIbmSmPrivateCertificateConfigurationTemplateRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") if len(id) != 3 { - return diag.Errorf("Wrong format of resource ID. To import a certificate template use the format `//`") + tfErr := flex.TerraformErrorf(nil, "Wrong format of resource ID. To import a certificate template use the format `//`", PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } region := id[0] instanceId := id[1] @@ -378,163 +383,206 @@ func resourceIbmSmPrivateCertificateConfigurationTemplateRead(context context.Co return nil } log.Printf("[DEBUG] GetConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetConfigurationWithContext failed %s\n%s", err, response), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } configuration := configurationIntf.(*secretsmanagerv2.PrivateCertificateConfigurationTemplate) if err = d.Set("instance_id", instanceId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting instance_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting instance_id"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("name", configuration.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("config_type", configuration.ConfigType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting config_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting config_type"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", configuration.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("certificate_authority", configuration.CertificateAuthority); err != nil { - return diag.FromErr(fmt.Errorf("Error setting certificate_authority: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting certificate_authority"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("allowed_secret_groups", configuration.AllowedSecretGroups); err != nil { - return diag.FromErr(fmt.Errorf("Error setting allowed_secret_groups: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting allowed_secret_groups"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("max_ttl_seconds", flex.IntValue(configuration.MaxTtlSeconds)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting max_ttl_seconds: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting max_ttl_seconds"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("ttl_seconds", flex.IntValue(configuration.TtlSeconds)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting ttl_seconds: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting ttl_seconds"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("allow_localhost", configuration.AllowLocalhost); err != nil { - return diag.FromErr(fmt.Errorf("Error setting allow_localhost: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting allow_localhost"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if configuration.AllowedDomains != nil { if err = d.Set("allowed_domains", configuration.AllowedDomains); err != nil { - return diag.FromErr(fmt.Errorf("Error setting allowed_domains: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting allowed_domains"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("allowed_domains_template", configuration.AllowedDomainsTemplate); err != nil { - return diag.FromErr(fmt.Errorf("Error setting allowed_domains_template: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting allowed_domains_template"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("allow_bare_domains", configuration.AllowBareDomains); err != nil { - return diag.FromErr(fmt.Errorf("Error setting allow_bare_domains: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting allow_bare_domains"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("allow_subdomains", configuration.AllowSubdomains); err != nil { - return diag.FromErr(fmt.Errorf("Error setting allow_subdomains: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting allow_subdomains"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("allow_glob_domains", configuration.AllowGlobDomains); err != nil { - return diag.FromErr(fmt.Errorf("Error setting allow_glob_domains: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting allow_glob_domains"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("allow_any_name", configuration.AllowAnyName); err != nil { - return diag.FromErr(fmt.Errorf("Error setting allow_any_name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting allow_any_name"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("enforce_hostnames", configuration.EnforceHostnames); err != nil { - return diag.FromErr(fmt.Errorf("Error setting enforce_hostnames: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting enforce_hostnames"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("allow_ip_sans", configuration.AllowIpSans); err != nil { - return diag.FromErr(fmt.Errorf("Error setting allow_ip_sans: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting allow_ip_sans"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if configuration.AllowedUriSans != nil { if err = d.Set("allowed_uri_sans", configuration.AllowedUriSans); err != nil { - return diag.FromErr(fmt.Errorf("Error setting allowed_uri_sans: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting allowed_uri_sans"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } } if configuration.AllowedOtherSans != nil { if err = d.Set("allowed_other_sans", configuration.AllowedOtherSans); err != nil { - return diag.FromErr(fmt.Errorf("Error setting allowed_other_sans: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting allowed_other_sans"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("server_flag", configuration.ServerFlag); err != nil { - return diag.FromErr(fmt.Errorf("Error setting server_flag: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting server_flag"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("client_flag", configuration.ClientFlag); err != nil { - return diag.FromErr(fmt.Errorf("Error setting client_flag: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting client_flag"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("code_signing_flag", configuration.CodeSigningFlag); err != nil { - return diag.FromErr(fmt.Errorf("Error setting code_signing_flag: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting code_signing_flag"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("email_protection_flag", configuration.EmailProtectionFlag); err != nil { - return diag.FromErr(fmt.Errorf("Error setting email_protection_flag: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting email_protection_flag"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("key_type", configuration.KeyType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting key_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting key_type"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("key_bits", flex.IntValue(configuration.KeyBits)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting key_bits: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting key_bits"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if configuration.KeyUsage != nil { if err = d.Set("key_usage", configuration.KeyUsage); err != nil { - return diag.FromErr(fmt.Errorf("Error setting key_usage: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting key_usage"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } } if configuration.ExtKeyUsage != nil { if err = d.Set("ext_key_usage", configuration.ExtKeyUsage); err != nil { - return diag.FromErr(fmt.Errorf("Error setting ext_key_usage: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting ext_key_usage"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } } if configuration.ExtKeyUsageOids != nil { if err = d.Set("ext_key_usage_oids", configuration.ExtKeyUsageOids); err != nil { - return diag.FromErr(fmt.Errorf("Error setting ext_key_usage_oids: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting ext_key_usage_oids"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("use_csr_common_name", configuration.UseCsrCommonName); err != nil { - return diag.FromErr(fmt.Errorf("Error setting use_csr_common_name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting use_csr_common_name"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("use_csr_sans", configuration.UseCsrSans); err != nil { - return diag.FromErr(fmt.Errorf("Error setting use_csr_sans: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting use_csr_sans"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if configuration.Ou != nil { if err = d.Set("ou", configuration.Ou); err != nil { - return diag.FromErr(fmt.Errorf("Error setting ou: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting ou"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } } if configuration.Organization != nil { if err = d.Set("organization", configuration.Organization); err != nil { - return diag.FromErr(fmt.Errorf("Error setting organization: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting organization"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } } if configuration.Country != nil { if err = d.Set("country", configuration.Country); err != nil { - return diag.FromErr(fmt.Errorf("Error setting country: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting country"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } } if configuration.Locality != nil { if err = d.Set("locality", configuration.Locality); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locality: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locality"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } } if configuration.Province != nil { if err = d.Set("province", configuration.Province); err != nil { - return diag.FromErr(fmt.Errorf("Error setting province: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting province"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } } if configuration.StreetAddress != nil { if err = d.Set("street_address", configuration.StreetAddress); err != nil { - return diag.FromErr(fmt.Errorf("Error setting street_address: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting street_address"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } } if configuration.PostalCode != nil { if err = d.Set("postal_code", configuration.PostalCode); err != nil { - return diag.FromErr(fmt.Errorf("Error setting postal_code: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting postal_code"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("require_cn", configuration.RequireCn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting require_cn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting require_cn"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if configuration.PolicyIdentifiers != nil { if err = d.Set("policy_identifiers", configuration.PolicyIdentifiers); err != nil { - return diag.FromErr(fmt.Errorf("Error setting policy_identifiers: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting policy_identifiers"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("basic_constraints_valid_for_non_ca", configuration.BasicConstraintsValidForNonCa); err != nil { - return diag.FromErr(fmt.Errorf("Error setting basic_constraints_valid_for_non_ca: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting basic_constraints_valid_for_non_ca"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("not_before_duration_seconds", flex.IntValue(configuration.NotBeforeDurationSeconds)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting not_before_duration_seconds: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting not_before_duration_seconds"), PrivateCertConfigTemplateResourceName, "read") + return tfErr.GetDiag() } return nil @@ -543,7 +591,8 @@ func resourceIbmSmPrivateCertificateConfigurationTemplateRead(context context.Co func resourceIbmSmPrivateCertificateConfigurationTemplateUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertConfigTemplateResourceName, "update") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -802,7 +851,8 @@ func resourceIbmSmPrivateCertificateConfigurationTemplateUpdate(context context. _, response, err := secretsManagerClient.UpdateConfigurationWithContext(context, updateConfigurationOptions) if err != nil { log.Printf("[DEBUG] UpdateConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateConfigurationWithContext failed %s\n%s", err, response), PrivateCertConfigTemplateResourceName, "update") + return tfErr.GetDiag() } } @@ -812,7 +862,8 @@ func resourceIbmSmPrivateCertificateConfigurationTemplateUpdate(context context. func resourceIbmSmPrivateCertificateConfigurationTemplateDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PrivateCertConfigTemplateResourceName, "delete") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -828,7 +879,8 @@ func resourceIbmSmPrivateCertificateConfigurationTemplateDelete(context context. response, err := secretsManagerClient.DeleteConfigurationWithContext(context, deleteConfigurationOptions) if err != nil { log.Printf("[DEBUG] DeleteConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("DeleteConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("DeleteConfigurationWithContext failed %s\n%s", err, response), PrivateCertConfigTemplateResourceName, "delete") + return tfErr.GetDiag() } d.SetId("") diff --git a/ibm/service/secretsmanager/resource_ibm_sm_public_certificate.go b/ibm/service/secretsmanager/resource_ibm_sm_public_certificate.go index 8cbd049687..17aa926c7d 100644 --- a/ibm/service/secretsmanager/resource_ibm_sm_public_certificate.go +++ b/ibm/service/secretsmanager/resource_ibm_sm_public_certificate.go @@ -409,7 +409,8 @@ func ResourceIbmSmPublicCertificate() *schema.Resource { func resourceIbmSmPublicCertificateCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PublicCertSecretResourceName, "create") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -420,14 +421,16 @@ func resourceIbmSmPublicCertificateCreate(context context.Context, d *schema.Res secretPrototypeModel, err := resourceIbmSmPublicCertificateMapToSecretPrototype(d) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PublicCertSecretResourceName, "create") + return tfErr.GetDiag() } createSecretOptions.SetSecretPrototype(secretPrototypeModel) secretIntf, response, err := secretsManagerClient.CreateSecretWithContext(context, createSecretOptions) if err != nil { log.Printf("[DEBUG] CreateSecretWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateSecretWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateSecretWithContext failed: %s\n%s", err.Error(), response), PublicCertSecretResourceName, "create") + return tfErr.GetDiag() } secret := secretIntf.(*secretsmanagerv2.PublicCertificate) @@ -441,8 +444,8 @@ func resourceIbmSmPublicCertificateCreate(context context.Context, d *schema.Res } if err != nil { - return diag.FromErr(fmt.Errorf( - "error waiting for resource IbmSmPublicCertificate (%s) to be created: %s", d.Id(), err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error waiting for resource IbmSmPublicCertificate (%s) to be created: %s", d.Id(), err.Error()), PublicCertSecretResourceName, "create") + return tfErr.GetDiag() } return resourceIbmSmPublicCertificateRead(context, d, meta) @@ -484,12 +487,14 @@ func waitForIbmSmPublicCertificateCreate(secretsManagerClient *secretsmanagerv2. func resourceIbmSmPublicCertificateRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") if len(id) != 3 { - return diag.Errorf("Wrong format of resource ID. To import a secret use the format `//`") + tfErr := flex.TerraformErrorf(nil, "Wrong format of resource ID. To import a secret use the format `//`", PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } region := id[0] instanceId := id[1] @@ -507,133 +512,170 @@ func resourceIbmSmPublicCertificateRead(context context.Context, d *schema.Resou return nil } log.Printf("[DEBUG] GetSecretWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretWithContext failed %s\n%s", err, response), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } secret := secretIntf.(*secretsmanagerv2.PublicCertificate) if err = d.Set("secret_id", secretId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_id"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("instance_id", instanceId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting instance_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting instance_id"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("created_by", secret.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(secret.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("crn", secret.Crn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crn"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("downloaded", secret.Downloaded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting downloaded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting downloaded"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("locks_total", flex.IntValue(secret.LocksTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locks_total"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("name", secret.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("secret_group_id", secret.SecretGroupID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_group_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_group_id"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", secret.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("state", flex.IntValue(secret.State)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("state_description", secret.StateDescription); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state_description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state_description"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(secret.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("versions_total", flex.IntValue(secret.VersionsTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting versions_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting versions_total"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("common_name", secret.CommonName); err != nil { - return diag.FromErr(fmt.Errorf("Error setting common_name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting common_name"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if secret.IssuanceInfo != nil { issuanceInfoMap, err := resourceIbmSmPublicCertificateCertificateIssuanceInfoToMap(secret.IssuanceInfo, d) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("issuance_info", []map[string]interface{}{issuanceInfoMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting issuance_info: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting issuance_info"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("key_algorithm", secret.KeyAlgorithm); err != nil { - return diag.FromErr(fmt.Errorf("Error setting key_algorithm: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting key_algorithm"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("ca", secret.Ca); err != nil { - return diag.FromErr(fmt.Errorf("Error setting ca: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting ca"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if d.Get("dns").(string) != "akamai" { if err = d.Set("dns", secret.Dns); err != nil { - return diag.FromErr(fmt.Errorf("Error setting dns: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting dns"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("bundle_certs", secret.BundleCerts); err != nil { - return diag.FromErr(fmt.Errorf("Error setting bundle_certs: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting bundle_certs"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } rotationMap, err := resourceIbmSmPublicCertificateRotationPolicyToMap(secret.Rotation) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("rotation", []map[string]interface{}{rotationMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting rotation: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting rotation"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if secret.CustomMetadata != nil { d.Set("custom_metadata", secret.CustomMetadata) } if err = d.Set("description", secret.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if secret.Labels != nil { if err = d.Set("labels", secret.Labels); err != nil { - return diag.FromErr(fmt.Errorf("Error setting labels: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting labels"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("signing_algorithm", secret.SigningAlgorithm); err != nil { - return diag.FromErr(fmt.Errorf("Error setting signing_algorithm: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting signing_algorithm"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if secret.AltNames != nil { if err = d.Set("alt_names", secret.AltNames); err != nil { - return diag.FromErr(fmt.Errorf("Error setting alt_names: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting alt_names"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("expiration_date", DateTimeToRFC3339(secret.ExpirationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting expiration_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting expiration_date"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("issuer", secret.Issuer); err != nil { - return diag.FromErr(fmt.Errorf("Error setting issuer: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting issuer"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("serial_number", secret.SerialNumber); err != nil { - return diag.FromErr(fmt.Errorf("Error setting serial_number: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting serial_number"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } validityMap, err := resourceIbmSmPublicCertificateCertificateValidityToMap(secret.Validity) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("validity", []map[string]interface{}{validityMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting validity: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting validity"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("certificate", secret.Certificate); err != nil { - return diag.FromErr(fmt.Errorf("Error setting certificate: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting certificate"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("intermediate", secret.Intermediate); err != nil { - return diag.FromErr(fmt.Errorf("Error setting intermediate: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting intermediate"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("private_key", secret.PrivateKey); err != nil { - return diag.FromErr(fmt.Errorf("Error setting private_key: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting private_key"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if *secret.StateDescription == "active" { @@ -645,13 +687,15 @@ func resourceIbmSmPublicCertificateRead(context context.Context, d *schema.Resou versionMetadataIntf, response, err := secretsManagerClient.GetSecretVersionMetadataWithContext(context, getVersionMetdataOptions) if err != nil { log.Printf("[DEBUG] GetSecretVersionMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretVersionMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretVersionMetadataWithContext failed %s\n%s", err, response), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } versionMetadata := versionMetadataIntf.(*secretsmanagerv2.PublicCertificateVersionMetadata) if versionMetadata.VersionCustomMetadata != nil { if err = d.Set("version_custom_metadata", versionMetadata.VersionCustomMetadata); err != nil { - return diag.FromErr(fmt.Errorf("Error setting version_custom_metadata: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting version_custom_metadata"), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } } } @@ -669,7 +713,8 @@ func resourceIbmSmPublicCertificateRead(context context.Context, d *schema.Resou func resourceIbmSmPublicCertificateUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PublicCertSecretResourceName, "update") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -711,7 +756,8 @@ func resourceIbmSmPublicCertificateUpdate(context context.Context, d *schema.Res RotationModel, err := resourceIbmSmPublicCertificateMapToRotationPolicy(d.Get("rotation").([]interface{})[0].(map[string]interface{})) if err != nil { log.Printf("[DEBUG] UpdateSecretMetadataWithContext failed: Reading Rotation parameter failed: %s", err) - return diag.FromErr(fmt.Errorf("UpdateSecretMetadataWithContext failed: Reading Rotation parameter failed: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateSecretMetadataWithContext failed: Reading Rotation parameter failed: %s", err), PublicCertSecretResourceName, "update") + return tfErr.GetDiag() } patchVals.Rotation = RotationModel hasChange = true @@ -722,7 +768,8 @@ func resourceIbmSmPublicCertificateUpdate(context context.Context, d *schema.Res _, response, err := secretsManagerClient.UpdateSecretMetadataWithContext(context, updateSecretMetadataOptions) if err != nil { log.Printf("[DEBUG] UpdateSecretMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateSecretMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateSecretMetadataWithContext failed %s\n%s", err, response), PublicCertSecretResourceName, "update") + return tfErr.GetDiag() } } @@ -743,7 +790,8 @@ func resourceIbmSmPublicCertificateUpdate(context context.Context, d *schema.Res resourceIbmSmPublicCertificateRead(context, d, meta) } log.Printf("[DEBUG] UpdateSecretVersionMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateSecretVersionMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateSecretVersionMetadataWithContext failed %s\n%s", err, response), PublicCertSecretResourceName, "update") + return tfErr.GetDiag() } } @@ -753,7 +801,8 @@ func resourceIbmSmPublicCertificateUpdate(context context.Context, d *schema.Res func resourceIbmSmPublicCertificateDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PublicCertSecretResourceName, "delete") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -769,7 +818,8 @@ func resourceIbmSmPublicCertificateDelete(context context.Context, d *schema.Res response, err := secretsManagerClient.DeleteSecretWithContext(context, deleteSecretOptions) if err != nil { log.Printf("[DEBUG] DeleteSecretWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("DeleteSecretWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("DeleteSecretWithContext failed %s\n%s", err, response), PublicCertSecretResourceName, "delete") + return tfErr.GetDiag() } d.SetId("") @@ -1095,7 +1145,8 @@ func setChallengesWithAkamaiAndValidateManualDns(context context.Context, d *sch for _, challengeItem := range secret.IssuanceInfo.Challenges { if _, exists := successfullySetChallengeDomains[*challengeItem.TxtRecordValue]; !exists { resourceIbmSmPublicCertificateDelete(context, d, meta) - return diag.FromErr(fmt.Errorf("error: a dns record set in Akamai was not created for domain: %s", *challengeItem.Domain)) + tfErr := flex.TerraformErrorf(nil, fmt.Sprintf("error: a dns record set in Akamai was not created for domain: %s", *challengeItem.Domain), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } } @@ -1106,9 +1157,10 @@ func configureAkamai(d *schema.ResourceData) (edgegrid.Config, diag.Diagnostics) var config edgegrid.Config var err error defaultErrMsg := "error configuring Akamai: One or more arguments are missing. Please verify that you provided either a path to your 'edgerc' file or all the config parameters ('host', 'client_secret', 'access_token' and 'client_token')" + defaultTfErr := flex.TerraformErrorf(nil, defaultErrMsg, PublicCertSecretResourceName, "read") if len(d.Get("akamai").([]interface{})) == 0 || d.Get("akamai").([]interface{})[0] == nil { - return config, diag.FromErr(fmt.Errorf(defaultErrMsg)) + return config, defaultTfErr.GetDiag() } akamaiData := d.Get("akamai").([]interface{})[0].(map[string]interface{}) @@ -1116,12 +1168,13 @@ func configureAkamai(d *schema.ResourceData) (edgegrid.Config, diag.Diagnostics) edgercData := akamaiData["edgerc"].([]interface{})[0].(map[string]interface{}) edgerc := edgercData["path_to_edgerc"].(string) if edgerc == "" { - return config, diag.FromErr(fmt.Errorf(defaultErrMsg)) + return config, defaultTfErr.GetDiag() } configSection := edgercData["config_section"].(string) config, err = edgegrid.InitEdgeRc(edgerc, configSection) if err != nil { - return config, diag.FromErr(fmt.Errorf("error initiating edgerc: %s", err)) + tfErr := flex.TerraformErrorf(nil, fmt.Sprintf("error initiating edgerc: %s", err), PublicCertSecretResourceName, "read") + return config, tfErr.GetDiag() } } else if len(akamaiData["config"].([]interface{})) > 0 && akamaiData["config"].([]interface{})[0] != nil { akamaiDataConfig := akamaiData["config"].([]interface{})[0].(map[string]interface{}) @@ -1134,10 +1187,10 @@ func configureAkamai(d *schema.ResourceData) (edgegrid.Config, diag.Diagnostics) config.MaxBody = 131072 } } else { - return config, diag.FromErr(fmt.Errorf(defaultErrMsg)) + return config, defaultTfErr.GetDiag() } } else { - return config, diag.FromErr(fmt.Errorf(defaultErrMsg)) + return config, defaultTfErr.GetDiag() } return config, nil @@ -1147,11 +1200,13 @@ func configureAkamai(d *schema.ResourceData) (edgegrid.Config, diag.Diagnostics) func checkIfRecordExistsInAkamai(config edgegrid.Config, zone string, txtRecordName string) ([]string, diag.Diagnostics) { req, err := client.NewRequest(config, "GET", fmt.Sprintf("/config-dns/v2/zones/%s/names/%s/types/TXT", zone, txtRecordName), nil) if err != nil { - return nil, diag.FromErr(fmt.Errorf("error creating akamai 'GET' request: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("error creating akamai 'GET' request: %s", err), PublicCertSecretResourceName, "read") + return nil, tfErr.GetDiag() } res, err := client.Do(config, req) if err != nil { - return nil, diag.FromErr(fmt.Errorf("error in performing akamai 'GET' request: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("error in performing akamai 'GET' request: %s", err), PublicCertSecretResourceName, "read") + return nil, tfErr.GetDiag() } if res.StatusCode == 404 { // there is no record set, we need to create one return nil, nil @@ -1160,7 +1215,8 @@ func checkIfRecordExistsInAkamai(config edgegrid.Config, zone string, txtRecordN err := json.NewDecoder(res.Body).Decode(&recordData) if err != nil { - diag.FromErr(fmt.Errorf("error in performing akamai 'GET' request: error in decoding JSON: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("error in performing akamai 'GET' request: error in decoding JSON: %s", err), PublicCertSecretResourceName, "read") + return nil, tfErr.GetDiag() } return recordData.Target, nil @@ -1168,9 +1224,11 @@ func checkIfRecordExistsInAkamai(config edgegrid.Config, zone string, txtRecordN body, err := ioutil.ReadAll(res.Body) if err != nil { fmt.Printf("Error reading response: %s\n", err.Error()) - return nil, diag.FromErr(fmt.Errorf("error in performing akamai 'GET' request: error reading error: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("error in performing akamai 'GET' request: error reading error: %s", err), PublicCertSecretResourceName, "read") + return nil, tfErr.GetDiag() } - return nil, diag.FromErr(fmt.Errorf("error in performing akamai 'GET' request: %s", string(body))) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("error in performing akamai 'GET' request: %s", string(body)), PublicCertSecretResourceName, "read") + return nil, tfErr.GetDiag() } } @@ -1191,15 +1249,18 @@ func createOrUpdateAkamaiChallengeRecordSet(config edgegrid.Config, zone string, jsonBody, err := json.Marshal(recordSetBody) if err != nil { - return diag.FromErr(fmt.Errorf("error setting body for akamai request: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("error setting body for akamai request: %s", err), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } req, err := client.NewRequest(config, method, fmt.Sprintf("/config-dns/v2/zones/%s/names/%s/types/TXT", zone, txtRecordName), bytes.NewReader(jsonBody)) if err != nil { - return diag.FromErr(fmt.Errorf("error creating akamai request: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("error creating akamai request: %s", err), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } res, err := client.Do(config, req) if err != nil { - return diag.FromErr(fmt.Errorf("error in akamai request: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("error in akamai request: %s", err), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } if res.StatusCode != 201 && res.StatusCode != 200 { body, err := ioutil.ReadAll(res.Body) @@ -1207,7 +1268,8 @@ func createOrUpdateAkamaiChallengeRecordSet(config edgegrid.Config, zone string, fmt.Printf("Error reading response: %s\n", err.Error()) return nil } - return diag.FromErr(fmt.Errorf("error from akamai in '%s' request: %s", method, string(body))) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("error from akamai in '%s' request: %s", method, string(body)), PublicCertSecretResourceName, "read") + return tfErr.GetDiag() } return nil } @@ -1230,7 +1292,8 @@ func findAllTxtRecordValuesForDomain(domainItem string, txtRecordName string, se if len(txtRecordValues) > 0 { return txtRecordValues, nil } - return nil, diag.FromErr(fmt.Errorf("failed to find a challenge for the domain: %s", domainItem)) + tfErr := flex.TerraformErrorf(nil, fmt.Sprintf("failed to find a challenge for the domain: %s", domainItem), PublicCertSecretResourceName, "read") + return nil, tfErr.GetDiag() } func findTxtRecordValuesDifferences(akamaiValues, challengesValues []string) []string { @@ -1256,16 +1319,19 @@ func findTxtRecordValuesDifferences(akamaiValues, challengesValues []string) []s func getZone(currentZone string, originalDomain string, config edgegrid.Config) (string, diag.Diagnostics) { req, err := client.NewRequest(config, "GET", fmt.Sprintf("/config-dns/v2/zones/%s", currentZone), nil) if err != nil { - return "", diag.FromErr(fmt.Errorf("error creating akamai 'GET' zone request: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("error creating akamai 'GET' zone request: %s", err), PublicCertSecretResourceName, "read") + return "", tfErr.GetDiag() } res, err := client.Do(config, req) if err != nil { - return "", diag.FromErr(fmt.Errorf("error in performing akamai 'GET' zone request: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("error in performing akamai 'GET' zone request: %s", err), PublicCertSecretResourceName, "read") + return "", tfErr.GetDiag() } if res.StatusCode == 404 { zoneSplit := strings.Split(currentZone, ".") if len(zoneSplit) == 2 { - return "", diag.FromErr(fmt.Errorf("could not find a zone in Akamai for the domain: %s", originalDomain)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("could not find a zone in Akamai for the domain: %s", originalDomain), PublicCertSecretResourceName, "read") + return "", tfErr.GetDiag() } newZone := strings.Join(zoneSplit[1:], ".") @@ -1277,8 +1343,10 @@ func getZone(currentZone string, originalDomain string, config edgegrid.Config) body, err := ioutil.ReadAll(res.Body) if err != nil { fmt.Printf("Error reading response: %s\n", err.Error()) - return "", diag.FromErr(fmt.Errorf("error in performing akamai 'GET' zone request for zone: %s: error reading error: %s", currentZone, err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("error in performing akamai 'GET' zone request for zone: %s: error reading error: %s", currentZone, err), PublicCertSecretResourceName, "read") + return "", tfErr.GetDiag() } - return "", diag.FromErr(fmt.Errorf("error in performing akamai 'GET' zone request for zone: %s:: %s", currentZone, string(body))) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("error in performing akamai 'GET' zone request for zone: %s:: %s", currentZone, string(body)), PublicCertSecretResourceName, "read") + return "", tfErr.GetDiag() } } diff --git a/ibm/service/secretsmanager/resource_ibm_sm_public_certificate_action_validate_manual_dns.go b/ibm/service/secretsmanager/resource_ibm_sm_public_certificate_action_validate_manual_dns.go index bc317e7fe4..4180dba347 100644 --- a/ibm/service/secretsmanager/resource_ibm_sm_public_certificate_action_validate_manual_dns.go +++ b/ibm/service/secretsmanager/resource_ibm_sm_public_certificate_action_validate_manual_dns.go @@ -6,6 +6,7 @@ package secretsmanager import ( "context" "fmt" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "log" @@ -40,7 +41,8 @@ func ResourceIbmSmPublicCertificateActionValidateManualDns() *schema.Resource { func resourceIbmSmPublicCertificateActionValidateManualDnsCreateOrUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PublicCertConfigActionValidateManualDNSResourceName, "create/update") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -75,13 +77,14 @@ func validateManualDns(context context.Context, d *schema.ResourceData, secretsM _, response, err := secretsManagerClient.CreateSecretActionWithContext(context, createActionOptions) if err != nil { log.Printf("[DEBUG] CreateSecretActionWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateSecretActionWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateSecretActionWithContext failed: %s\n%s", err.Error(), response), PublicCertConfigActionValidateManualDNSResourceName, "create") + return tfErr.GetDiag() } _, err = waitForIbmSmPublicCertificateCreate(secretsManagerClient, d, "pre_activation", "active") if err != nil { - return diag.FromErr(fmt.Errorf( - "Error waiting for resource IbmSmPublicCertificateActionValidateManualDns (%s) to be created: %s", d.Id(), err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error waiting for resource IbmSmPublicCertificateActionValidateManualDns (%s) to be created: %s", d.Id(), err.Error()), PublicCertConfigActionValidateManualDNSResourceName, "create") + return tfErr.GetDiag() } return nil } diff --git a/ibm/service/secretsmanager/resource_ibm_sm_public_certificate_configuration_ca_lets_encrypt.go b/ibm/service/secretsmanager/resource_ibm_sm_public_certificate_configuration_ca_lets_encrypt.go index 4d23c48659..6719aed8d2 100644 --- a/ibm/service/secretsmanager/resource_ibm_sm_public_certificate_configuration_ca_lets_encrypt.go +++ b/ibm/service/secretsmanager/resource_ibm_sm_public_certificate_configuration_ca_lets_encrypt.go @@ -6,6 +6,7 @@ package secretsmanager import ( "context" "fmt" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "log" @@ -70,7 +71,8 @@ func ResourceIbmSmPublicCertificateConfigurationCALetsEncrypt() *schema.Resource func resourceIbmSmPublicCertificateConfigurationCALetsEncryptCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PublicCertConfigCALetsEncryptResourceName, "create") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -81,14 +83,16 @@ func resourceIbmSmPublicCertificateConfigurationCALetsEncryptCreate(context cont configurationPrototypeModel, err := resourceIbmSmPublicCertificateConfigurationCALetsEncryptMapToConfigurationPrototype(d) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PublicCertConfigCALetsEncryptResourceName, "create") + return tfErr.GetDiag() } createConfigurationOptions.SetConfigurationPrototype(configurationPrototypeModel) configurationIntf, response, err := secretsManagerClient.CreateConfigurationWithContext(context, createConfigurationOptions) if err != nil { log.Printf("[DEBUG] CreateConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateConfigurationWithContext failed: %s\n%s", err.Error(), response), PublicCertConfigCALetsEncryptResourceName, "create") + return tfErr.GetDiag() } configuration := configurationIntf.(*secretsmanagerv2.PublicCertificateConfigurationCALetsEncrypt) d.SetId(fmt.Sprintf("%s/%s/%s", region, instanceId, *configuration.Name)) @@ -99,12 +103,14 @@ func resourceIbmSmPublicCertificateConfigurationCALetsEncryptCreate(context cont func resourceIbmSmPublicCertificateConfigurationCALetsEncryptRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PublicCertConfigCALetsEncryptResourceName, "read") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") if len(id) != 3 { - return diag.Errorf("Wrong format of resource ID. To import a CA configuration use the format `//`") + tfErr := flex.TerraformErrorf(nil, "Wrong format of resource ID. To import a CA configuration use the format `//`", PublicCertConfigCALetsEncryptResourceName, "read") + return tfErr.GetDiag() } region := id[0] instanceId := id[1] @@ -122,34 +128,43 @@ func resourceIbmSmPublicCertificateConfigurationCALetsEncryptRead(context contex return nil } log.Printf("[DEBUG] GetConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetConfigurationWithContext failed %s\n%s", err, response), PublicCertConfigCALetsEncryptResourceName, "read") + return tfErr.GetDiag() } configuration := configurationIntf.(*secretsmanagerv2.PublicCertificateConfigurationCALetsEncrypt) if err = d.Set("instance_id", instanceId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting instance_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting instance_id"), PublicCertConfigCALetsEncryptResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), PublicCertConfigCALetsEncryptResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("config_type", configuration.ConfigType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting config_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting config_type"), PublicCertConfigCALetsEncryptResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("name", configuration.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting config name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), PublicCertConfigCALetsEncryptResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", configuration.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), PublicCertConfigCALetsEncryptResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("lets_encrypt_environment", configuration.LetsEncryptEnvironment); err != nil { - return diag.FromErr(fmt.Errorf("Error setting lets_encrypt_environment: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting lets_encrypt_environment"), PublicCertConfigCALetsEncryptResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("lets_encrypt_preferred_chain", configuration.LetsEncryptPreferredChain); err != nil { - return diag.FromErr(fmt.Errorf("Error setting lets_encrypt_preferred_chain: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting lets_encrypt_preferred_chain"), PublicCertConfigCALetsEncryptResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("lets_encrypt_private_key", configuration.LetsEncryptPrivateKey); err != nil { - return diag.FromErr(fmt.Errorf("Error setting lets_encrypt_private_key: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting lets_encrypt_private_key"), PublicCertConfigCALetsEncryptResourceName, "read") + return tfErr.GetDiag() } return nil @@ -158,7 +173,8 @@ func resourceIbmSmPublicCertificateConfigurationCALetsEncryptRead(context contex func resourceIbmSmPublicCertificateConfigurationCALetsEncryptUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PublicCertConfigCALetsEncryptResourceName, "update") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -196,7 +212,8 @@ func resourceIbmSmPublicCertificateConfigurationCALetsEncryptUpdate(context cont _, response, err := secretsManagerClient.UpdateConfigurationWithContext(context, updateConfigurationOptions) if err != nil { log.Printf("[DEBUG] UpdateConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateConfigurationWithContext failed %s\n%s", err, response), PublicCertConfigCALetsEncryptResourceName, "update") + return tfErr.GetDiag() } } @@ -206,7 +223,8 @@ func resourceIbmSmPublicCertificateConfigurationCALetsEncryptUpdate(context cont func resourceIbmSmPublicCertificateConfigurationCALetsEncryptDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PublicCertConfigCALetsEncryptResourceName, "delete") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -222,7 +240,8 @@ func resourceIbmSmPublicCertificateConfigurationCALetsEncryptDelete(context cont response, err := secretsManagerClient.DeleteConfigurationWithContext(context, deleteConfigurationOptions) if err != nil { log.Printf("[DEBUG] DeleteConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("DeleteConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("DeleteConfigurationWithContext failed %s\n%s", err, response), PublicCertConfigCALetsEncryptResourceName, "delete") + return tfErr.GetDiag() } d.SetId("") diff --git a/ibm/service/secretsmanager/resource_ibm_sm_public_certificate_configuration_dns_cis.go b/ibm/service/secretsmanager/resource_ibm_sm_public_certificate_configuration_dns_cis.go index 4dd008a3a5..4421f09bb4 100644 --- a/ibm/service/secretsmanager/resource_ibm_sm_public_certificate_configuration_dns_cis.go +++ b/ibm/service/secretsmanager/resource_ibm_sm_public_certificate_configuration_dns_cis.go @@ -6,6 +6,7 @@ package secretsmanager import ( "context" "fmt" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "log" "strings" @@ -41,13 +42,13 @@ func ResourceIbmSmConfigurationPublicCertificateDNSCis() *schema.Resource { "cloud_internet_services_apikey": &schema.Schema{ Type: schema.TypeString, Optional: true, - ValidateFunc: validate.InvokeValidator("ibm_sm_public_certificate_configuration_dns_cis", "cloud_internet_services_apikey"), + ValidateFunc: validate.InvokeValidator(PublicCertConfigDnsCISResourceName, "cloud_internet_services_apikey"), Description: "An IBM Cloud API key that can to list domains in your Cloud Internet Services instance.To grant Secrets Manager the ability to view the Cloud Internet Services instance and all of its domains, the API key must be assigned the Reader service role on Internet Services (`internet-svcs`).If you need to manage specific domains, you can assign the Manager role. For production environments, it is recommended that you assign the Reader access role, and then use the[IAM Policy Management API](https://cloud.ibm.com/apidocs/iam-policy-management#create-policy) to control specific domains. For more information, see the [docs](https://cloud.ibm.com/docs/secrets-manager?topic=secrets-manager-prepare-order-certificates#authorize-specific-domains).", }, "cloud_internet_services_crn": &schema.Schema{ Type: schema.TypeString, Required: true, - ValidateFunc: validate.InvokeValidator("ibm_sm_public_certificate_configuration_dns_cis", "cloud_internet_services_crn"), + ValidateFunc: validate.InvokeValidator(PublicCertConfigDnsCISResourceName, "cloud_internet_services_crn"), Description: "A CRN that uniquely identifies an IBM Cloud resource.", }, "secret_type": &schema.Schema{ @@ -97,14 +98,15 @@ func ResourceIbmSmConfigurationPublicCertificateDNSCisValidator() *validate.Reso }, ) - resourceValidator := validate.ResourceValidator{ResourceName: "ibm_sm_public_certificate_configuration_dns_cis", Schema: validateSchema} + resourceValidator := validate.ResourceValidator{ResourceName: PublicCertConfigDnsCISResourceName, Schema: validateSchema} return &resourceValidator } func resourceIbmSmConfigurationPublicCertificateDNSCisCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PublicCertConfigDnsCISResourceName, "create") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -129,14 +131,16 @@ func resourceIbmSmConfigurationPublicCertificateDNSCisCreate(context context.Con } convertedModel, err := resourceIbmSmConfigurationPublicCertificateCisMapToPublicCertificateConfigurationDNSCloudInternetServicesPrototype(bodyModelMap) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PublicCertConfigDnsCISResourceName, "create") + return tfErr.GetDiag() } createConfigurationOptions.SetConfigurationPrototype(convertedModel) configurationIntf, response, err := secretsManagerClient.CreateConfigurationWithContext(context, createConfigurationOptions) if err != nil { log.Printf("[DEBUG] CreateConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateConfigurationWithContext failed: %s\n%s", err.Error(), response), PublicCertConfigDnsCISResourceName, "create") + return tfErr.GetDiag() } configuration := configurationIntf.(*secretsmanagerv2.PublicCertificateConfigurationDNSCloudInternetServices) @@ -148,12 +152,14 @@ func resourceIbmSmConfigurationPublicCertificateDNSCisCreate(context context.Con func resourceIbmSmConfigurationPublicCertificateDNSCisRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PublicCertConfigDnsCISResourceName, "read") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") if len(id) != 3 { - return diag.Errorf("Wrong format of resource ID. To import a DNS configuration use the format `//`") + tfErr := flex.TerraformErrorf(nil, "Wrong format of resource ID. To import a DNS configuration use the format `//`", PublicCertConfigDnsCISResourceName, "read") + return tfErr.GetDiag() } region := id[0] instanceId := id[1] @@ -170,45 +176,56 @@ func resourceIbmSmConfigurationPublicCertificateDNSCisRead(context context.Conte return nil } log.Printf("[DEBUG] GetConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetConfigurationWithContext failed %s\n%s", err, response), PublicCertConfigDnsCISResourceName, "read") + return tfErr.GetDiag() } configuration := configurationIntf.(*secretsmanagerv2.PublicCertificateConfigurationDNSCloudInternetServices) if err = d.Set("instance_id", instanceId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting instance_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting instance_id"), PublicCertConfigDnsCISResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), PublicCertConfigDnsCISResourceName, "read") + return tfErr.GetDiag() } if !core.IsNil(configuration.ConfigType) { if err = d.Set("config_type", configuration.ConfigType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting config_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting config_type"), PublicCertConfigDnsCISResourceName, "read") + return tfErr.GetDiag() } } if !core.IsNil(configuration.CloudInternetServicesApikey) { if err = d.Set("cloud_internet_services_apikey", configuration.CloudInternetServicesApikey); err != nil { - return diag.FromErr(fmt.Errorf("Error setting cloud_internet_services_apikey: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting cloud_internet_services_apikey"), PublicCertConfigDnsCISResourceName, "read") + return tfErr.GetDiag() } } if !core.IsNil(configuration.CloudInternetServicesCrn) { if err = d.Set("cloud_internet_services_crn", configuration.CloudInternetServicesCrn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting cloud_internet_services_crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting cloud_internet_services_crn"), PublicCertConfigDnsCISResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("name", configuration.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting config name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), PublicCertConfigDnsCISResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", configuration.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), PublicCertConfigDnsCISResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("created_by", configuration.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), PublicCertConfigDnsCISResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(configuration.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), PublicCertConfigDnsCISResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(configuration.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), PublicCertConfigDnsCISResourceName, "read") + return tfErr.GetDiag() } return nil @@ -217,7 +234,8 @@ func resourceIbmSmConfigurationPublicCertificateDNSCisRead(context context.Conte func resourceIbmSmConfigurationPublicCertificateDNSCisUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PublicCertConfigDnsCISResourceName, "update") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -248,7 +266,8 @@ func resourceIbmSmConfigurationPublicCertificateDNSCisUpdate(context context.Con _, response, err := secretsManagerClient.UpdateConfigurationWithContext(context, updateConfigurationOptions) if err != nil { log.Printf("[DEBUG] UpdateConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateConfigurationWithContext failed %s\n%s", err, response), PublicCertConfigDnsCISResourceName, "update") + return tfErr.GetDiag() } } @@ -258,7 +277,8 @@ func resourceIbmSmConfigurationPublicCertificateDNSCisUpdate(context context.Con func resourceIbmSmConfigurationPublicCertificateDNSCisDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PublicCertConfigDnsCISResourceName, "delete") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -273,7 +293,8 @@ func resourceIbmSmConfigurationPublicCertificateDNSCisDelete(context context.Con response, err := secretsManagerClient.DeleteConfigurationWithContext(context, deleteConfigurationOptions) if err != nil { log.Printf("[DEBUG] DeleteConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("DeleteConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("DeleteConfigurationWithContext failed %s\n%s", err, response), PublicCertConfigDnsCISResourceName, "delete") + return tfErr.GetDiag() } d.SetId("") diff --git a/ibm/service/secretsmanager/resource_ibm_sm_public_certificate_configuration_dns_classic_infrastructure.go b/ibm/service/secretsmanager/resource_ibm_sm_public_certificate_configuration_dns_classic_infrastructure.go index 9b1f9f8eaf..1fa2028750 100644 --- a/ibm/service/secretsmanager/resource_ibm_sm_public_certificate_configuration_dns_classic_infrastructure.go +++ b/ibm/service/secretsmanager/resource_ibm_sm_public_certificate_configuration_dns_classic_infrastructure.go @@ -6,6 +6,7 @@ package secretsmanager import ( "context" "fmt" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "log" "strings" @@ -41,13 +42,13 @@ func ResourceIbmSmPublicCertificateConfigurationDNSClassicInfrastructure() *sche "classic_infrastructure_username": &schema.Schema{ Type: schema.TypeString, Required: true, - ValidateFunc: validate.InvokeValidator("ibm_sm_public_certificate_configuration_dns_classic_infrastructure", "classic_infrastructure_username"), + ValidateFunc: validate.InvokeValidator(PublicCertConfigDnsClassicInfrastructureResourceName, "classic_infrastructure_username"), Description: "The username that is associated with your classic infrastructure account.In most cases, your classic infrastructure username is your `_`. For more information, see the [docs](https://cloud.ibm.com/docs/account?topic=account-classic_keys).", }, "classic_infrastructure_password": &schema.Schema{ Type: schema.TypeString, Required: true, - ValidateFunc: validate.InvokeValidator("ibm_sm_public_certificate_configuration_dns_classic_infrastructure", "classic_infrastructure_password"), + ValidateFunc: validate.InvokeValidator(PublicCertConfigDnsClassicInfrastructureResourceName, "classic_infrastructure_password"), Description: "Your classic infrastructure API key.For information about viewing and accessing your classic infrastructure API key, see the [docs](https://cloud.ibm.com/docs/account?topic=account-classic_keys).", }, "secret_type": &schema.Schema{ @@ -97,14 +98,15 @@ func ResourceIbmSmPublicCertificateConfigurationDNSClassicInfrastructureValidato }, ) - resourceValidator := validate.ResourceValidator{ResourceName: "ibm_sm_public_certificate_configuration_dns_classic_infrastructure", Schema: validateSchema} + resourceValidator := validate.ResourceValidator{ResourceName: PublicCertConfigDnsClassicInfrastructureResourceName, Schema: validateSchema} return &resourceValidator } func resourceIbmSmPublicCertificateConfigurationDNSClassicInfrastructureCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PublicCertConfigDnsClassicInfrastructureResourceName, "create") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -127,14 +129,16 @@ func resourceIbmSmPublicCertificateConfigurationDNSClassicInfrastructureCreate(c } convertedModel, err := resourceIbmSmConfigurationPublicCertificateClassicInfrastructureMapToPublicCertificateConfigurationDNSClassicInfrastructurePrototype(bodyModelMap) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PublicCertConfigDnsClassicInfrastructureResourceName, "create") + return tfErr.GetDiag() } createConfigurationOptions.SetConfigurationPrototype(convertedModel) configurationIntf, response, err := secretsManagerClient.CreateConfigurationWithContext(context, createConfigurationOptions) if err != nil { log.Printf("[DEBUG] CreateConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateConfigurationWithContext failed: %s\n%s", err.Error(), response), PublicCertConfigDnsClassicInfrastructureResourceName, "create") + return tfErr.GetDiag() } configuration := configurationIntf.(*secretsmanagerv2.PublicCertificateConfigurationDNSClassicInfrastructure) @@ -146,12 +150,14 @@ func resourceIbmSmPublicCertificateConfigurationDNSClassicInfrastructureCreate(c func resourceIbmSmPublicCertificateConfigurationDNSClassicInfrastructureRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PublicCertConfigDnsClassicInfrastructureResourceName, "read") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") if len(id) != 3 { - return diag.Errorf("Wrong format of resource ID. To import a DNS configuration use the format `//`") + tfErr := flex.TerraformErrorf(nil, "Wrong format of resource ID. To import a DNS configuration use the format `//`", PublicCertConfigDnsClassicInfrastructureResourceName, "read") + return tfErr.GetDiag() } region := id[0] instanceId := id[1] @@ -168,45 +174,56 @@ func resourceIbmSmPublicCertificateConfigurationDNSClassicInfrastructureRead(con return nil } log.Printf("[DEBUG] GetConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetConfigurationWithContext failed %s\n%s", err, response), PublicCertConfigDnsClassicInfrastructureResourceName, "read") + return tfErr.GetDiag() } configuration := configurationIntf.(*secretsmanagerv2.PublicCertificateConfigurationDNSClassicInfrastructure) if err = d.Set("instance_id", instanceId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting instance_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting instance_id"), PublicCertConfigDnsClassicInfrastructureResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), PublicCertConfigDnsClassicInfrastructureResourceName, "read") + return tfErr.GetDiag() } if !core.IsNil(configuration.ConfigType) { if err = d.Set("config_type", configuration.ConfigType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting config_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting config_type"), PublicCertConfigDnsClassicInfrastructureResourceName, "read") + return tfErr.GetDiag() } } if !core.IsNil(configuration.ClassicInfrastructureUsername) { if err = d.Set("classic_infrastructure_username", configuration.ClassicInfrastructureUsername); err != nil { - return diag.FromErr(fmt.Errorf("Error setting classic_infrastructure_username: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting classic_infrastructure_username"), PublicCertConfigDnsClassicInfrastructureResourceName, "read") + return tfErr.GetDiag() } } if !core.IsNil(configuration.ClassicInfrastructurePassword) { if err = d.Set("classic_infrastructure_password", configuration.ClassicInfrastructurePassword); err != nil { - return diag.FromErr(fmt.Errorf("Error setting classic_infrastructure_password: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting classic_infrastructure_password"), PublicCertConfigDnsClassicInfrastructureResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("name", configuration.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting config name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), PublicCertConfigDnsClassicInfrastructureResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", configuration.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), PublicCertConfigDnsClassicInfrastructureResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("created_by", configuration.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), PublicCertConfigDnsClassicInfrastructureResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(configuration.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), PublicCertConfigDnsClassicInfrastructureResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(configuration.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), PublicCertConfigDnsClassicInfrastructureResourceName, "read") + return tfErr.GetDiag() } return nil @@ -215,7 +232,8 @@ func resourceIbmSmPublicCertificateConfigurationDNSClassicInfrastructureRead(con func resourceIbmSmPublicCertificateConfigurationDNSClassicInfrastructureUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PublicCertConfigDnsClassicInfrastructureResourceName, "update") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -246,7 +264,8 @@ func resourceIbmSmPublicCertificateConfigurationDNSClassicInfrastructureUpdate(c _, response, err := secretsManagerClient.UpdateConfigurationWithContext(context, updateConfigurationOptions) if err != nil { log.Printf("[DEBUG] UpdateConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateConfigurationWithContext failed %s\n%s", err, response), PublicCertConfigDnsClassicInfrastructureResourceName, "update") + return tfErr.GetDiag() } } @@ -256,7 +275,8 @@ func resourceIbmSmPublicCertificateConfigurationDNSClassicInfrastructureUpdate(c func resourceIbmSmPublicCertificateConfigurationDNSClassicInfrastructureDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", PublicCertConfigDnsClassicInfrastructureResourceName, "delete") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -271,7 +291,8 @@ func resourceIbmSmPublicCertificateConfigurationDNSClassicInfrastructureDelete(c response, err := secretsManagerClient.DeleteConfigurationWithContext(context, deleteConfigurationOptions) if err != nil { log.Printf("[DEBUG] DeleteConfigurationWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("DeleteConfigurationWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("DeleteConfigurationWithContext failed %s\n%s", err, response), PublicCertConfigDnsClassicInfrastructureResourceName, "delete") + return tfErr.GetDiag() } d.SetId("") diff --git a/ibm/service/secretsmanager/resource_ibm_sm_secret_group.go b/ibm/service/secretsmanager/resource_ibm_sm_secret_group.go index 1c04eccab6..0fb9fbcd0b 100644 --- a/ibm/service/secretsmanager/resource_ibm_sm_secret_group.go +++ b/ibm/service/secretsmanager/resource_ibm_sm_secret_group.go @@ -6,6 +6,7 @@ package secretsmanager import ( "context" "fmt" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "log" "strings" @@ -34,13 +35,13 @@ func ResourceIbmSmSecretGroup() *schema.Resource { "name": &schema.Schema{ Type: schema.TypeString, Required: true, - ValidateFunc: validate.InvokeValidator("ibm_sm_secret_group", "name"), + ValidateFunc: validate.InvokeValidator(SecretGroupResourceName, "name"), Description: "The name of your secret group.", }, "description": &schema.Schema{ Type: schema.TypeString, Optional: true, - ValidateFunc: validate.InvokeValidator("ibm_sm_secret_group", "description"), + ValidateFunc: validate.InvokeValidator(SecretGroupResourceName, "description"), Description: "An extended description of your secret group.To protect your privacy, do not use personal data, such as your name or location, as a description for your secret group.", }, "created_at": &schema.Schema{ @@ -80,14 +81,15 @@ func ResourceIbmSmSecretGroupValidator() *validate.ResourceValidator { }, ) - resourceValidator := validate.ResourceValidator{ResourceName: "ibm_sm_secret_group", Schema: validateSchema} + resourceValidator := validate.ResourceValidator{ResourceName: SecretGroupResourceName, Schema: validateSchema} return &resourceValidator } func resourceIbmSmSecretGroupCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", SecretGroupResourceName, "create") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -104,7 +106,8 @@ func resourceIbmSmSecretGroupCreate(context context.Context, d *schema.ResourceD secretGroup, response, err := secretsManagerClient.CreateSecretGroupWithContext(context, createSecretGroupOptions) if err != nil { log.Printf("[DEBUG] CreateSecretGroupWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateSecretGroupWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateSecretGroupWithContext failed: %s\n%s", err.Error(), response), SecretGroupResourceName, "create") + return tfErr.GetDiag() } d.SetId(fmt.Sprintf("%s/%s/%s", region, instanceId, *secretGroup.ID)) @@ -116,12 +119,14 @@ func resourceIbmSmSecretGroupCreate(context context.Context, d *schema.ResourceD func resourceIbmSmSecretGroupRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", SecretGroupResourceName, "read") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") if len(id) != 3 { - return diag.Errorf("Wrong format of resource ID. To import a secret group use the format `//`") + tfErr := flex.TerraformErrorf(nil, "Wrong format of resource ID. To import a secret group use the format `//`", SecretGroupResourceName, "read") + return tfErr.GetDiag() } region := id[0] instanceId := id[1] @@ -139,29 +144,37 @@ func resourceIbmSmSecretGroupRead(context context.Context, d *schema.ResourceDat return nil } log.Printf("[DEBUG] GetSecretGroupWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretGroupWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretGroupWithContext failed %s\n%s", err, response), SecretGroupResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("secret_group_id", secretGroupId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_group_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_group_id"), SecretGroupResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("instance_id", instanceId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting instance_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting instance_id"), SecretGroupResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), SecretGroupResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("name", secretGroup.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), SecretGroupResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("description", secretGroup.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), SecretGroupResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(secretGroup.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), SecretGroupResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(secretGroup.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), SecretGroupResourceName, "read") + return tfErr.GetDiag() } return nil @@ -170,7 +183,8 @@ func resourceIbmSmSecretGroupRead(context context.Context, d *schema.ResourceDat func resourceIbmSmSecretGroupUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", SecretGroupResourceName, "update") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -202,7 +216,8 @@ func resourceIbmSmSecretGroupUpdate(context context.Context, d *schema.ResourceD _, response, err := secretsManagerClient.UpdateSecretGroupWithContext(context, updateSecretGroupOptions) if err != nil { log.Printf("[DEBUG] UpdateSecretGroupWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateSecretGroupWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateSecretGroupWithContext failed %s\n%s", err, response), SecretGroupResourceName, "update") + return tfErr.GetDiag() } } @@ -212,7 +227,8 @@ func resourceIbmSmSecretGroupUpdate(context context.Context, d *schema.ResourceD func resourceIbmSmSecretGroupDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", SecretGroupResourceName, "delete") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -228,7 +244,8 @@ func resourceIbmSmSecretGroupDelete(context context.Context, d *schema.ResourceD response, err := secretsManagerClient.DeleteSecretGroupWithContext(context, deleteSecretGroupOptions) if err != nil { log.Printf("[DEBUG] DeleteSecretGroupWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("DeleteSecretGroupWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("DeleteSecretGroupWithContext failed %s\n%s", err, response), SecretGroupResourceName, "delete") + return tfErr.GetDiag() } d.SetId("") diff --git a/ibm/service/secretsmanager/resource_ibm_sm_service_credentials_secret.go b/ibm/service/secretsmanager/resource_ibm_sm_service_credentials_secret.go index d2f0b337a9..b4dc68f99d 100644 --- a/ibm/service/secretsmanager/resource_ibm_sm_service_credentials_secret.go +++ b/ibm/service/secretsmanager/resource_ibm_sm_service_credentials_secret.go @@ -307,7 +307,8 @@ func ResourceIbmSmServiceCredentialsSecret() *schema.Resource { func resourceIbmSmServiceCredentialsSecretCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", ServiceCredentialsSecretResourceName, "create") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -318,14 +319,16 @@ func resourceIbmSmServiceCredentialsSecretCreate(context context.Context, d *sch secretPrototypeModel, err := resourceIbmSmServiceCredentialsSecretMapToSecretPrototype(d) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", ServiceCredentialsSecretResourceName, "create") + return tfErr.GetDiag() } createSecretOptions.SetSecretPrototype(secretPrototypeModel) secretIntf, response, err := secretsManagerClient.CreateSecretWithContext(context, createSecretOptions) if err != nil { log.Printf("[DEBUG] CreateSecretWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateSecretWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateSecretWithContext failed: %s\n%s", err.Error(), response), ServiceCredentialsSecretResourceName, "create") + return tfErr.GetDiag() } secret := secretIntf.(*secretsmanagerv2.ServiceCredentialsSecret) @@ -338,12 +341,14 @@ func resourceIbmSmServiceCredentialsSecretCreate(context context.Context, d *sch func resourceIbmSmServiceCredentialsSecretRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") if len(id) != 3 { - return diag.Errorf("Wrong format of resource ID. To import a secret use the format `//`") + tfErr := flex.TerraformErrorf(nil, "Wrong format of resource ID. To import a secret use the format `//`", ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } region := id[0] instanceId := id[1] @@ -361,83 +366,105 @@ func resourceIbmSmServiceCredentialsSecretRead(context context.Context, d *schem return nil } log.Printf("[DEBUG] GetSecretWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretWithContext failed %s\n%s", err, response), ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } secret := secretIntf.(*secretsmanagerv2.ServiceCredentialsSecret) if err = d.Set("secret_id", secretId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_id"), ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("instance_id", instanceId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting instance_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting instance_id"), ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("created_by", secret.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(secret.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("crn", secret.Crn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crn"), ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("downloaded", secret.Downloaded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting downloaded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting downloaded"), ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("locks_total", flex.IntValue(secret.LocksTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locks_total"), ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("name", secret.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("secret_group_id", secret.SecretGroupID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_group_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_group_id"), ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", secret.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("state", flex.IntValue(secret.State)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state"), ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("state_description", secret.StateDescription); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state_description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state_description"), ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(secret.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("versions_total", flex.IntValue(secret.VersionsTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting versions_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting versions_total"), ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if secret.CustomMetadata != nil { d.Set("custom_metadata", secret.CustomMetadata) } if err = d.Set("description", secret.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if secret.Labels != nil { if err = d.Set("labels", secret.Labels); err != nil { - return diag.FromErr(fmt.Errorf("Error setting labels: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting labels"), ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } } rotationMap, err := resourceIbmSmServiceCredentialsSecretRotationPolicyToMap(secret.Rotation) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if len(rotationMap) > 0 { if err = d.Set("rotation", []map[string]interface{}{rotationMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting rotation: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting rotation"), ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } } sourceServiceMap, err := resourceIbmSmServiceCredentialsSecretSourceServiceToMap(secret.SourceService) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } if len(sourceServiceMap) > 0 { if err = d.Set("source_service", []map[string]interface{}{sourceServiceMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting source_service: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting source_service"), ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } } if secret.Credentials != nil { @@ -445,11 +472,13 @@ func resourceIbmSmServiceCredentialsSecretRead(context context.Context, d *schem cred, _ := json.Marshal(secret.Credentials) json.Unmarshal(cred, &credInterface) if err = d.Set("credentials", flex.Flatten(credInterface)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting credentials: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting credentials"), ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("next_rotation_date", DateTimeToRFC3339(secret.NextRotationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting next_rotation_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting next_rotation_date"), ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } // Call get version metadata API to get the current version_custom_metadata @@ -460,19 +489,22 @@ func resourceIbmSmServiceCredentialsSecretRead(context context.Context, d *schem versionMetadataIntf, response, err := secretsManagerClient.GetSecretVersionMetadataWithContext(context, getVersionMetdataOptions) if err != nil { log.Printf("[DEBUG] GetSecretVersionMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretVersionMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretVersionMetadataWithContext failed %s\n%s", err, response), ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } versionMetadata := versionMetadataIntf.(*secretsmanagerv2.ServiceCredentialsSecretVersionMetadata) if versionMetadata.VersionCustomMetadata != nil { if err = d.Set("version_custom_metadata", versionMetadata.VersionCustomMetadata); err != nil { - return diag.FromErr(fmt.Errorf("Error setting version_custom_metadata: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting version_custom_metadata"), ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } } if secret.ExpirationDate != nil { if err = d.Set("expiration_date", DateTimeToRFC3339(secret.ExpirationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting expiration_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting expiration_date"), ServiceCredentialsSecretResourceName, "read") + return tfErr.GetDiag() } } @@ -482,7 +514,8 @@ func resourceIbmSmServiceCredentialsSecretRead(context context.Context, d *schem func resourceIbmSmServiceCredentialsSecretUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", ServiceCredentialsSecretResourceName, "update") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -528,7 +561,8 @@ func resourceIbmSmServiceCredentialsSecretUpdate(context context.Context, d *sch RotationModel, err := resourceIbmSmServiceCredentialsSecretMapToRotationPolicy(d.Get("rotation").([]interface{})[0].(map[string]interface{})) if err != nil { log.Printf("[DEBUG] UpdateSecretMetadataWithContext failed: Reading Rotation parameter failed: %s", err) - return diag.FromErr(fmt.Errorf("UpdateSecretMetadataWithContext failed: Reading Rotation parameter failed: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateSecretMetadataWithContext failed: Reading Rotation parameter failed: %s", err), ServiceCredentialsSecretResourceName, "update") + return tfErr.GetDiag() } patchVals.Rotation = RotationModel hasChange = true @@ -540,7 +574,8 @@ func resourceIbmSmServiceCredentialsSecretUpdate(context context.Context, d *sch _, response, err := secretsManagerClient.UpdateSecretMetadataWithContext(context, updateSecretMetadataOptions) if err != nil { log.Printf("[DEBUG] UpdateSecretMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateSecretMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateSecretMetadataWithContext failed %s\n%s", err, response), ServiceCredentialsSecretResourceName, "update") + return tfErr.GetDiag() } } @@ -561,7 +596,8 @@ func resourceIbmSmServiceCredentialsSecretUpdate(context context.Context, d *sch resourceIbmSmServiceCredentialsSecretRead(context, d, meta) } log.Printf("[DEBUG] UpdateSecretVersionMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateSecretVersionMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateSecretMetadataWithContext failed %s\n%s", err, response), ServiceCredentialsSecretResourceName, "update") + return tfErr.GetDiag() } } @@ -571,7 +607,8 @@ func resourceIbmSmServiceCredentialsSecretUpdate(context context.Context, d *sch func resourceIbmSmServiceCredentialsSecretDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", ServiceCredentialsSecretResourceName, "delete") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -587,7 +624,8 @@ func resourceIbmSmServiceCredentialsSecretDelete(context context.Context, d *sch response, err := secretsManagerClient.DeleteSecretWithContext(context, deleteSecretOptions) if err != nil { log.Printf("[DEBUG] DeleteSecretWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("DeleteSecretWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("DeleteSecretWithContext failed %s\n%s", err, response), ServiceCredentialsSecretResourceName, "delete") + return tfErr.GetDiag() } d.SetId("") diff --git a/ibm/service/secretsmanager/resource_ibm_sm_username_password_secret.go b/ibm/service/secretsmanager/resource_ibm_sm_username_password_secret.go index 2a21a8935f..267928197a 100644 --- a/ibm/service/secretsmanager/resource_ibm_sm_username_password_secret.go +++ b/ibm/service/secretsmanager/resource_ibm_sm_username_password_secret.go @@ -9,7 +9,6 @@ import ( "github.com/IBM-Cloud/bluemix-go/bmxerror" "github.com/go-openapi/strfmt" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/pkg/errors" "log" "strings" "time" @@ -219,7 +218,8 @@ func ResourceIbmSmUsernamePasswordSecret() *schema.Resource { func resourceIbmSmUsernamePasswordSecretCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", UsernamePasswordSecretResourceName, "create") + return tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) @@ -230,14 +230,16 @@ func resourceIbmSmUsernamePasswordSecretCreate(context context.Context, d *schem secretPrototypeModel, err := resourceIbmSmUsernamePasswordSecretMapToSecretPrototype(d) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", UsernamePasswordSecretResourceName, "create") + return tfErr.GetDiag() } createSecretOptions.SetSecretPrototype(secretPrototypeModel) secretIntf, response, err := secretsManagerClient.CreateSecretWithContext(context, createSecretOptions) if err != nil { log.Printf("[DEBUG] CreateSecretWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateSecretWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateSecretWithContext failed: %s\n%s", err.Error(), response), UsernamePasswordSecretResourceName, "create") + return tfErr.GetDiag() } secret := secretIntf.(*secretsmanagerv2.UsernamePasswordSecret) d.SetId(fmt.Sprintf("%s/%s/%s", region, instanceId, *secret.ID)) @@ -245,8 +247,8 @@ func resourceIbmSmUsernamePasswordSecretCreate(context context.Context, d *schem _, err = waitForIbmSmUsernamePasswordSecretCreate(secretsManagerClient, d) if err != nil { - return diag.FromErr(fmt.Errorf( - "Error waiting for resource IbmSmUsernamePasswordSecret (%s) to be created: %s", d.Id(), err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error waiting for resource IbmSmUsernamePasswordSecret (%s) to be created: %s", d.Id(), err.Error()), UsernamePasswordSecretResourceName, "create") + return tfErr.GetDiag() } return resourceIbmSmUsernamePasswordSecretRead(context, d, meta) @@ -287,12 +289,14 @@ func waitForIbmSmUsernamePasswordSecretCreate(secretsManagerClient *secretsmanag func resourceIbmSmUsernamePasswordSecretRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") if len(id) != 3 { - return diag.Errorf("Wrong format of resource ID. To import a secret use the format `//`") + tfErr := flex.TerraformErrorf(nil, "Wrong format of resource ID. To import a secret use the format `//`", UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } region := id[0] instanceId := id[1] @@ -310,92 +314,118 @@ func resourceIbmSmUsernamePasswordSecretRead(context context.Context, d *schema. return nil } log.Printf("[DEBUG] GetSecretWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretWithContext failed %s\n%s", err, response), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } secret := secretIntf.(*secretsmanagerv2.UsernamePasswordSecret) if err = d.Set("secret_id", secretId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_id"), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("instance_id", instanceId); err != nil { - return diag.FromErr(fmt.Errorf("Error setting instance_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting instance_id"), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("region", region); err != nil { - return diag.FromErr(fmt.Errorf("Error setting region: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting region"), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("created_by", secret.CreatedBy); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_by: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_by"), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("created_at", DateTimeToRFC3339(secret.CreatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting created_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting created_at"), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("crn", secret.Crn); err != nil { - return diag.FromErr(fmt.Errorf("Error setting crn: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting crn"), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } if secret.CustomMetadata != nil { d.Set("custom_metadata", secret.CustomMetadata) } if err = d.Set("description", secret.Description); err != nil { - return diag.FromErr(fmt.Errorf("Error setting description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting description"), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("downloaded", secret.Downloaded); err != nil { - return diag.FromErr(fmt.Errorf("Error setting downloaded: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting downloaded"), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } if secret.Labels != nil { if err = d.Set("labels", secret.Labels); err != nil { - return diag.FromErr(fmt.Errorf("Error setting labels: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting labels"), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } } if err = d.Set("locks_total", flex.IntValue(secret.LocksTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting locks_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting locks_total"), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("name", secret.Name); err != nil { - return diag.FromErr(fmt.Errorf("Error setting name: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting name"), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("secret_group_id", secret.SecretGroupID); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_group_id: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_group_id"), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("secret_type", secret.SecretType); err != nil { - return diag.FromErr(fmt.Errorf("Error setting secret_type: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting secret_type"), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("state", flex.IntValue(secret.State)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state"), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("state_description", secret.StateDescription); err != nil { - return diag.FromErr(fmt.Errorf("Error setting state_description: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting state_description"), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("updated_at", DateTimeToRFC3339(secret.UpdatedAt)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting updated_at"), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("versions_total", flex.IntValue(secret.VersionsTotal)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting versions_total: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting versions_total"), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } rotationMap, err := resourceIbmSmUsernamePasswordSecretRotationPolicyToMap(secret.Rotation) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("rotation", []map[string]interface{}{rotationMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting rotation: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting rotation"), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("expiration_date", DateTimeToRFC3339(secret.ExpirationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting expiration_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting expiration_date"), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("next_rotation_date", DateTimeToRFC3339(secret.NextRotationDate)); err != nil { - return diag.FromErr(fmt.Errorf("Error setting next_rotation_date: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting next_rotation_date"), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("username", secret.Username); err != nil { - return diag.FromErr(fmt.Errorf("Error setting username: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting username"), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("password", secret.Password); err != nil { - return diag.FromErr(fmt.Errorf("Error setting password: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting password"), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } passwordPolicyMap, err := passwordGenerationPolicyToMap(secret.PasswordGenerationPolicy) if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } if err = d.Set("password_generation_policy", []map[string]interface{}{passwordPolicyMap}); err != nil { - return diag.FromErr(fmt.Errorf("Error setting password generation policy: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting password_generation_policy"), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } // Call get version metadata API to get the current version_custom_metadata @@ -406,13 +436,15 @@ func resourceIbmSmUsernamePasswordSecretRead(context context.Context, d *schema. versionMetadataIntf, response, err := secretsManagerClient.GetSecretVersionMetadataWithContext(context, getVersionMetdataOptions) if err != nil { log.Printf("[DEBUG] GetSecretVersionMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("GetSecretVersionMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretVersionMetadataWithContext failed %s\n%s", err, response), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } versionMetadata := versionMetadataIntf.(*secretsmanagerv2.UsernamePasswordSecretVersionMetadata) if versionMetadata.VersionCustomMetadata != nil { if err = d.Set("version_custom_metadata", versionMetadata.VersionCustomMetadata); err != nil { - return diag.FromErr(fmt.Errorf("Error setting version_custom_metadata: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Error setting version_custom_metadata"), UsernamePasswordSecretResourceName, "read") + return tfErr.GetDiag() } } @@ -422,7 +454,8 @@ func resourceIbmSmUsernamePasswordSecretRead(context context.Context, d *schema. func resourceIbmSmUsernamePasswordSecretUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", UsernamePasswordSecretResourceName, "update") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -464,7 +497,8 @@ func resourceIbmSmUsernamePasswordSecretUpdate(context context.Context, d *schem RotationModel, err := resourceIbmSmUsernamePasswordSecretMapToRotationPolicy(d.Get("rotation").([]interface{})[0].(map[string]interface{})) if err != nil { log.Printf("[DEBUG] UpdateSecretMetadataWithContext failed: Reading Rotation parameter failed: %s", err) - return diag.FromErr(fmt.Errorf("UpdateSecretMetadataWithContext failed: Reading Rotation parameter failed: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateSecretMetadataWithContext failed: Reading Rotation parameter failed: %s", err), UsernamePasswordSecretResourceName, "update") + return tfErr.GetDiag() } patchVals.Rotation = RotationModel hasChange = true @@ -475,13 +509,15 @@ func resourceIbmSmUsernamePasswordSecretUpdate(context context.Context, d *schem layout := time.RFC3339 parseToTime, err := time.Parse(layout, d.Get("expiration_date").(string)) if err != nil { - return diag.FromErr(errors.New(`Failed to get "expiration_date". Error: ` + err.Error())) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf(`Failed to get "expiration_date". Error: %s`, err.Error()), UsernamePasswordSecretResourceName, "update") + return tfErr.GetDiag() } parseToDateTime := strfmt.DateTime(parseToTime) patchVals.ExpirationDate = &parseToDateTime hasChange = true } else { - return diag.FromErr(errors.New(`The "expiration_date" field cannot be removed. To disable expiration set expiration date to a far future date'`)) + tfErr := flex.TerraformErrorf(nil, `The "expiration_date" field cannot be removed. To disable expiration set expiration date to a far future date'`, UsernamePasswordSecretResourceName, "update") + return tfErr.GetDiag() } } @@ -489,7 +525,8 @@ func resourceIbmSmUsernamePasswordSecretUpdate(context context.Context, d *schem passwordPolicyModel, err := mapToPasswordGenerationPolicyPatch(d.Get("password_generation_policy").([]interface{})[0].(map[string]interface{})) if err != nil { log.Printf("[DEBUG] UpdateSecretMetadataWithContext failed: Reading password_generation_policy parameter failed: %s", err) - return diag.FromErr(fmt.Errorf("UpdateSecretMetadataWithContext failed: Reading password_generation_policy parameter failed: %s", err)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateSecretMetadataWithContext failed: Reading password_generation_policy parameter failed: %s", err), UsernamePasswordSecretResourceName, "update") + return tfErr.GetDiag() } patchVals.PasswordGenerationPolicy = passwordPolicyModel hasChange = true @@ -500,7 +537,8 @@ func resourceIbmSmUsernamePasswordSecretUpdate(context context.Context, d *schem _, response, err := secretsManagerClient.UpdateSecretMetadataWithContext(context, updateSecretMetadataOptions) if err != nil { log.Printf("[DEBUG] UpdateSecretMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateSecretMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateSecretMetadataWithContext failed %s\n%s", err, response), UsernamePasswordSecretResourceName, "update") + return tfErr.GetDiag() } } @@ -526,7 +564,8 @@ func resourceIbmSmUsernamePasswordSecretUpdate(context context.Context, d *schem resourceIbmSmUsernamePasswordSecretRead(context, d, meta) } log.Printf("[DEBUG] CreateSecretVersionWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("CreateSecretVersionWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateSecretVersionWithContext failed %s\n%s", err, response), UsernamePasswordSecretResourceName, "update") + return tfErr.GetDiag() } } else if d.HasChange("version_custom_metadata") { // Apply change to version_custom_metadata in current version @@ -545,7 +584,8 @@ func resourceIbmSmUsernamePasswordSecretUpdate(context context.Context, d *schem resourceIbmSmUsernamePasswordSecretRead(context, d, meta) } log.Printf("[DEBUG] UpdateSecretVersionMetadataWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("UpdateSecretVersionMetadataWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateSecretVersionMetadataWithContext failed %s\n%s", err, response), UsernamePasswordSecretResourceName, "update") + return tfErr.GetDiag() } } @@ -555,7 +595,8 @@ func resourceIbmSmUsernamePasswordSecretUpdate(context context.Context, d *schem func resourceIbmSmUsernamePasswordSecretDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", UsernamePasswordSecretResourceName, "delete") + return tfErr.GetDiag() } id := strings.Split(d.Id(), "/") @@ -571,7 +612,8 @@ func resourceIbmSmUsernamePasswordSecretDelete(context context.Context, d *schem response, err := secretsManagerClient.DeleteSecretWithContext(context, deleteSecretOptions) if err != nil { log.Printf("[DEBUG] DeleteSecretWithContext failed %s\n%s", err, response) - return diag.FromErr(fmt.Errorf("DeleteSecretWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("DeleteSecretWithContext failed %s\n%s", err, response), UsernamePasswordSecretResourceName, "delete") + return tfErr.GetDiag() } d.SetId("") diff --git a/ibm/service/secretsmanager/utils.go b/ibm/service/secretsmanager/utils.go index da8e661425..0a481168ff 100644 --- a/ibm/service/secretsmanager/utils.go +++ b/ibm/service/secretsmanager/utils.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" "github.com/IBM/go-sdk-core/v5/core" "github.com/IBM/secrets-manager-go-sdk/v2/secretsmanagerv2" "github.com/go-openapi/strfmt" @@ -26,6 +27,32 @@ const ( ImportedCertSecretType = "imported_cert" PublicCertSecretType = "public_cert" PrivateCertSecretType = "private_cert" + + ArbitrarySecretResourceName = "ibm_sm_arbitrary_secret" + UsernamePasswordSecretResourceName = "ibm_sm_username_password_secret" + IAMCredentialsSecretResourceName = "ibm_sm_iam_credentials_secret" + ServiceCredentialsSecretResourceName = "ibm_sm_service_credentials_secret" + KvSecretResourceName = "ibm_sm_kv_secret" + ImportedCertSecretResourceName = "ibm_sm_imported_certificate" + PublicCertSecretResourceName = "ibm_sm_public_certificate" + PrivateCertSecretResourceName = "ibm_sm_private_certificate" + + EnRegistrationResourceName = "ibm_sm_en_registration" + IAMCredentialsConfigResourceName = "ibm_sm_iam_credentials_configuration" + ConfigurationsResourceName = "ibm_sm_configurations" + PrivateCertConfigIntermediateCAResourceName = "ibm_sm_private_certificate_configuration_intermediate_ca" + PrivateCertConfigRootCAResourceName = "ibm_sm_private_certificate_configuration_root_ca" + PrivateCertConfigTemplateResourceName = "ibm_sm_private_certificate_configuration_template" + PrivateCertConfigActionSetSigned = "ibm_sm_private_certificate_configuration_action_set_signed" + PrivateCertConfigActionSignCsr = "ibm_sm_private_certificate_configuration_action_sign_csr" + PublicCertConfigCALetsEncryptResourceName = "ibm_sm_public_certificate_configuration_ca_lets_encrypt" + PublicCertConfigDnsCISResourceName = "ibm_sm_public_certificate_configuration_dns_cis" + PublicCertConfigDnsClassicInfrastructureResourceName = "ibm_sm_public_certificate_configuration_dns_classic_infrastructure" + PublicCertConfigActionValidateManualDNSResourceName = "ibm_sm_public_certificate_action_validate_manual_dns" + + SecretGroupResourceName = "ibm_sm_secret_group" + SecretGroupsResourceName = "ibm_sm_secret_groups" + SecretsResourceName = "ibm_sm_secrets" ) func getRegion(originalClient *secretsmanagerv2.SecretsManagerV2, d *schema.ResourceData) string { @@ -134,11 +161,12 @@ func DateTimeToRFC3339(dt *strfmt.DateTime) (s string) { return } -func getSecretByIdOrByName(context context.Context, d *schema.ResourceData, meta interface{}, secretType string) (secretsmanagerv2.SecretIntf, string, string, diag.Diagnostics) { +func getSecretByIdOrByName(context context.Context, d *schema.ResourceData, meta interface{}, secretType string, dataSourceName string) (secretsmanagerv2.SecretIntf, string, string, diag.Diagnostics) { secretsManagerClient, err := meta.(conns.ClientSession).SecretsManagerV2() if err != nil { - return nil, "", "", diag.FromErr(err) + tfErr := flex.TerraformErrorf(err, "", fmt.Sprintf("(Data) %s", dataSourceName), "read") + return nil, "", "", tfErr.GetDiag() } region := getRegion(secretsManagerClient, d) instanceId := d.Get("instance_id").(string) @@ -160,7 +188,8 @@ func getSecretByIdOrByName(context context.Context, d *schema.ResourceData, meta secretIntf, response, err = secretsManagerClient.GetSecretWithContext(context, getSecretOptions) if err != nil { log.Printf("[DEBUG] GetSecretWithContext failed %s\n%s", err, response) - return nil, "", "", diag.FromErr(fmt.Errorf("GetSecretWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretWithContext failed %s\n%s", err, response), fmt.Sprintf("(Data) %s", dataSourceName), "read") + return nil, "", "", tfErr.GetDiag() } return secretIntf, region, instanceId, nil } @@ -176,12 +205,14 @@ func getSecretByIdOrByName(context context.Context, d *schema.ResourceData, meta secretIntf, response, err = secretsManagerClient.GetSecretByNameTypeWithContext(context, getSecretByNameOptions) if err != nil { log.Printf("[DEBUG] GetSecretByNameTypeWithContext failed %s\n%s", err, response) - return nil, "", "", diag.FromErr(fmt.Errorf("GetSecretByNameTypeWithContext failed %s\n%s", err, response)) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetSecretByNameTypeWithContext failed %s\n%s", err, response), fmt.Sprintf("(Data) %s", dataSourceName), "read") + return nil, "", "", tfErr.GetDiag() } return secretIntf, region, instanceId, nil } - return nil, "", "", diag.FromErr(fmt.Errorf("Missing required arguments. Please make sure that either \"secret_id\" or \"name\" and \"secret_group_name\" are provided\n")) + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("Missing required arguments. Please make sure that either \"secret_id\" or \"name\" and \"secret_group_name\" are provided\n"), fmt.Sprintf("(Data) %s", dataSourceName), "read") + return nil, "", "", tfErr.GetDiag() } func secretVersionMetadataAsPatchFunction(secretVersionMetadataPatch *secretsmanagerv2.SecretVersionMetadataPatch) (_patch map[string]interface{}, err error) { diff --git a/ibm/service/vpc/data_source_ibm_is_backup_policies.go b/ibm/service/vpc/data_source_ibm_is_backup_policies.go index 9e223abac2..b2681c4a83 100644 --- a/ibm/service/vpc/data_source_ibm_is_backup_policies.go +++ b/ibm/service/vpc/data_source_ibm_is_backup_policies.go @@ -446,7 +446,7 @@ func dataSourceBackupPolicyCollectionBackupPoliciesPlansToMap(plansItem vpcv1.Ba return plansMap } -func dataSourceBackupPolicyCollectionPlansDeletedToMap(deletedItem vpcv1.BackupPolicyPlanReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceBackupPolicyCollectionPlansDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_backup_policy.go b/ibm/service/vpc/data_source_ibm_is_backup_policy.go index 62d152f0ce..8fda012d70 100644 --- a/ibm/service/vpc/data_source_ibm_is_backup_policy.go +++ b/ibm/service/vpc/data_source_ibm_is_backup_policy.go @@ -422,7 +422,7 @@ func dataSourceBackupPolicyPlansToMap(plansItem vpcv1.BackupPolicyPlanReference) return plansMap } -func dataSourceBackupPolicyPlansDeletedToMap(deletedItem vpcv1.BackupPolicyPlanReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceBackupPolicyPlansDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_backup_policy_job.go b/ibm/service/vpc/data_source_ibm_is_backup_policy_job.go index a7aee98b28..0a2defd776 100644 --- a/ibm/service/vpc/data_source_ibm_is_backup_policy_job.go +++ b/ibm/service/vpc/data_source_ibm_is_backup_policy_job.go @@ -447,7 +447,7 @@ func dataSourceBackupPolicyJobBackupPolicyPlanToMap(backupPolicyPlanItem vpcv1.B return backupPolicyPlanMap } -func dataSourceBackupPolicyJobBackupPolicyPlanDeletedToMap(deletedItem vpcv1.BackupPolicyPlanReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceBackupPolicyJobBackupPolicyPlanDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -537,7 +537,7 @@ func resourceIBMIsBackupPolicyPlanRemoteRegionReferenceToMap(model *vpcv1.Region return modelMap, nil } -func dataSourceBackupPolicyJobSourceVolumeDeletedToMap(deletedItem vpcv1.VolumeReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceBackupPolicyJobSourceVolumeDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -578,7 +578,7 @@ func dataSourceBackupPolicyJobSourceInstanceToMap(sourceVolumeItem vpcv1.BackupP return sourceVolumeMap } -func dataSourceBackupPolicyJobSourceInstanceDeletedToMap(deletedItem vpcv1.InstanceReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceBackupPolicyJobSourceInstanceDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -650,7 +650,7 @@ func dataSourceBackupPolicyJobTargetSnapshotToMap(targetSnapshotItem vpcv1.Snaps return targetSnapshotMap } -func dataSourceBackupPolicyJobTargetSnapshotDeletedToMap(deletedItem vpcv1.SnapshotReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceBackupPolicyJobTargetSnapshotDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_backup_policy_jobs.go b/ibm/service/vpc/data_source_ibm_is_backup_policy_jobs.go index 0377373cd2..d90df6531e 100644 --- a/ibm/service/vpc/data_source_ibm_is_backup_policy_jobs.go +++ b/ibm/service/vpc/data_source_ibm_is_backup_policy_jobs.go @@ -571,7 +571,7 @@ func dataSourceBackupPolicyJobCollectionJobsBackupPolicyPlanToMap(backupPolicyPl return backupPolicyPlanMap } -func dataSourceBackupPolicyJobCollectionBackupPolicyPlanDeletedToMap(deletedItem vpcv1.BackupPolicyPlanReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceBackupPolicyJobCollectionBackupPolicyPlanDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -639,7 +639,7 @@ func dataSourceBackupPolicyJobCollectionJobsSourceInstanceToMap(sourceVolumeItem return sourceVolumeMap } -func dataSourceBackupPolicyJobCollectionSourceVolumeDeletedToMap(deletedItem vpcv1.VolumeReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceBackupPolicyJobCollectionSourceVolumeDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -648,7 +648,7 @@ func dataSourceBackupPolicyJobCollectionSourceVolumeDeletedToMap(deletedItem vpc return deletedMap } -func dataSourceBackupPolicyJobCollectionSourceInstanceDeletedToMap(deletedItem vpcv1.InstanceReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceBackupPolicyJobCollectionSourceInstanceDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -702,7 +702,7 @@ func dataSourceBackupPolicyJobCollectionJobsTargetSnapshotToMap(targetSnapshotIt return targetSnapshotMap } -func dataSourceBackupPolicyJobCollectionTargetSnapshotDeletedToMap(deletedItem vpcv1.SnapshotReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceBackupPolicyJobCollectionTargetSnapshotDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_bare_metal_server.go b/ibm/service/vpc/data_source_ibm_is_bare_metal_server.go index 87bc367cfa..529ff295df 100644 --- a/ibm/service/vpc/data_source_ibm_is_bare_metal_server.go +++ b/ibm/service/vpc/data_source_ibm_is_bare_metal_server.go @@ -1205,7 +1205,7 @@ func dataSourceIBMIsBareMetalServerVirtualNetworkInterfaceReferenceAttachmentCon return modelMap, nil } -func dataSourceIBMIsBareMetalServerBareMetalServerNetworkAttachmentReferenceDeletedToMap(model *vpcv1.BareMetalServerNetworkAttachmentReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsBareMetalServerBareMetalServerNetworkAttachmentReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil @@ -1228,7 +1228,7 @@ func dataSourceIBMIsBareMetalServerReservedIPReferenceToMap(model *vpcv1.Reserve return modelMap, nil } -func dataSourceIBMIsBareMetalServerReservedIPReferenceDeletedToMap(model *vpcv1.ReservedIPReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsBareMetalServerReservedIPReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil @@ -1251,7 +1251,7 @@ func dataSourceIBMIsBareMetalServerSubnetReferenceToMap(model *vpcv1.SubnetRefer return modelMap, nil } -func dataSourceIBMIsBareMetalServerSubnetReferenceDeletedToMap(model *vpcv1.SubnetReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsBareMetalServerSubnetReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil diff --git a/ibm/service/vpc/data_source_ibm_is_bare_metal_server_network_attachment.go b/ibm/service/vpc/data_source_ibm_is_bare_metal_server_network_attachment.go index 846656eb1e..a5ce63f9b8 100644 --- a/ibm/service/vpc/data_source_ibm_is_bare_metal_server_network_attachment.go +++ b/ibm/service/vpc/data_source_ibm_is_bare_metal_server_network_attachment.go @@ -346,7 +346,7 @@ func dataSourceIBMIsBareMetalServerNetworkAttachmentReservedIPReferenceToMap(mod return modelMap, nil } -func dataSourceIBMIsBareMetalServerNetworkAttachmentReservedIPReferenceDeletedToMap(model *vpcv1.ReservedIPReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsBareMetalServerNetworkAttachmentReservedIPReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil @@ -369,7 +369,7 @@ func dataSourceIBMIsBareMetalServerNetworkAttachmentSubnetReferenceToMap(model * return modelMap, nil } -func dataSourceIBMIsBareMetalServerNetworkAttachmentSubnetReferenceDeletedToMap(model *vpcv1.SubnetReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsBareMetalServerNetworkAttachmentSubnetReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil diff --git a/ibm/service/vpc/data_source_ibm_is_bare_metal_server_network_attachments.go b/ibm/service/vpc/data_source_ibm_is_bare_metal_server_network_attachments.go index 074e7f8af8..ce3a6647a4 100644 --- a/ibm/service/vpc/data_source_ibm_is_bare_metal_server_network_attachments.go +++ b/ibm/service/vpc/data_source_ibm_is_bare_metal_server_network_attachments.go @@ -346,7 +346,7 @@ func dataSourceIBMIsBareMetalServerNetworkAttachmentsReservedIPReferenceToMap(mo return modelMap, nil } -func dataSourceIBMIsBareMetalServerNetworkAttachmentsReservedIPReferenceDeletedToMap(model *vpcv1.ReservedIPReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsBareMetalServerNetworkAttachmentsReservedIPReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil @@ -369,7 +369,7 @@ func dataSourceIBMIsBareMetalServerNetworkAttachmentsSubnetReferenceToMap(model return modelMap, nil } -func dataSourceIBMIsBareMetalServerNetworkAttachmentsSubnetReferenceDeletedToMap(model *vpcv1.SubnetReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsBareMetalServerNetworkAttachmentsSubnetReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil diff --git a/ibm/service/vpc/data_source_ibm_is_dedicated_host.go b/ibm/service/vpc/data_source_ibm_is_dedicated_host.go index c224e1ddd3..beb0f4160c 100644 --- a/ibm/service/vpc/data_source_ibm_is_dedicated_host.go +++ b/ibm/service/vpc/data_source_ibm_is_dedicated_host.go @@ -587,7 +587,7 @@ func dataSourceDedicatedHostGroupToMap(groupItem vpcv1.DedicatedHostGroupReferen return groupMap } -func dataSourceDedicatedHostGroupDeletedToMap(deletedItem vpcv1.DedicatedHostGroupReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceDedicatedHostGroupDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -630,7 +630,7 @@ func dataSourceDedicatedHostInstancesToMap(instancesItem vpcv1.InstanceReference return instancesMap } -func dataSourceDedicatedHostInstancesDeletedToMap(deletedItem vpcv1.InstanceReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceDedicatedHostInstancesDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -816,7 +816,7 @@ func dataSourceDedicatedHostDisksInstanceDisksToMap(instanceDisksItem vpcv1.Inst return instanceDisksMap } -func dataSourceDedicatedHostInstanceDisksDeletedToMap(deletedItem vpcv1.InstanceDiskReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceDedicatedHostInstanceDisksDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_dedicated_host_disk.go b/ibm/service/vpc/data_source_ibm_is_dedicated_host_disk.go index def4fdae5d..1607b8c5e6 100644 --- a/ibm/service/vpc/data_source_ibm_is_dedicated_host_disk.go +++ b/ibm/service/vpc/data_source_ibm_is_dedicated_host_disk.go @@ -224,7 +224,7 @@ func dataSourceDedicatedHostDiskInstanceDisksToMap(instanceDisksItem vpcv1.Insta return instanceDisksMap } -func dataSourceDedicatedHostDiskInstanceDisksDeletedToMap(deletedItem vpcv1.InstanceDiskReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceDedicatedHostDiskInstanceDisksDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_dedicated_host_disks.go b/ibm/service/vpc/data_source_ibm_is_dedicated_host_disks.go index 756279b3eb..b740557a16 100644 --- a/ibm/service/vpc/data_source_ibm_is_dedicated_host_disks.go +++ b/ibm/service/vpc/data_source_ibm_is_dedicated_host_disks.go @@ -253,7 +253,7 @@ func dataSourceDedicatedHostDiskCollectionDisksInstanceDisksToMap(instanceDisksI return instanceDisksMap } -func dataSourceDedicatedHostDiskCollectionInstanceDisksDeletedToMap(deletedItem vpcv1.InstanceDiskReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceDedicatedHostDiskCollectionInstanceDisksDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_dedicated_host_group.go b/ibm/service/vpc/data_source_ibm_is_dedicated_host_group.go index d0ee6a88d8..1fd670bb0e 100644 --- a/ibm/service/vpc/data_source_ibm_is_dedicated_host_group.go +++ b/ibm/service/vpc/data_source_ibm_is_dedicated_host_group.go @@ -247,7 +247,7 @@ func dataSourceDedicatedHostGroupDedicatedHostsToMap(dedicatedHostsItem vpcv1.De return dedicatedHostsMap } -func dataSourceDedicatedHostGroupDedicatedHostsDeletedToMap(deletedItem vpcv1.DedicatedHostReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceDedicatedHostGroupDedicatedHostsDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_dedicated_host_groups.go b/ibm/service/vpc/data_source_ibm_is_dedicated_host_groups.go index 59475a34da..3d91ec5abf 100644 --- a/ibm/service/vpc/data_source_ibm_is_dedicated_host_groups.go +++ b/ibm/service/vpc/data_source_ibm_is_dedicated_host_groups.go @@ -300,7 +300,7 @@ func dataSourceDedicatedHostGroupCollectionGroupsToMap(groupsItem vpcv1.Dedicate return groupsMap } -func dataSourceDedicatedHostGroupCollectionDedicatedHostsDeletedToMap(deletedItem vpcv1.DedicatedHostReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceDedicatedHostGroupCollectionDedicatedHostsDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_dedicated_hosts.go b/ibm/service/vpc/data_source_ibm_is_dedicated_hosts.go index bf3d709b20..436ed7abb0 100644 --- a/ibm/service/vpc/data_source_ibm_is_dedicated_hosts.go +++ b/ibm/service/vpc/data_source_ibm_is_dedicated_hosts.go @@ -637,7 +637,7 @@ func dataSourceDedicatedHostCollectionDedicatedHostsGroupToMap(groupItem vpcv1.D return groupMap } -func dataSourceDedicatedHostCollectionGroupDeletedToMap(deletedItem vpcv1.DedicatedHostGroupReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceDedicatedHostCollectionGroupDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -647,7 +647,7 @@ func dataSourceDedicatedHostCollectionGroupDeletedToMap(deletedItem vpcv1.Dedica return deletedMap } -func dataSourceDedicatedHostCollectionInstancesDeletedToMap(deletedItem vpcv1.InstanceReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceDedicatedHostCollectionInstancesDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_floating_ip.go b/ibm/service/vpc/data_source_ibm_is_floating_ip.go index c682691637..7608641db8 100644 --- a/ibm/service/vpc/data_source_ibm_is_floating_ip.go +++ b/ibm/service/vpc/data_source_ibm_is_floating_ip.go @@ -379,7 +379,7 @@ func dataSourceFloatingIPCollectionFloatingIpTargetToMap(targetItemIntf vpcv1.Fl return targetId, targetMap } -func dataSourceFloatingIPTargetNicDeletedToMap(deletedItem vpcv1.NetworkInterfaceReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceFloatingIPTargetNicDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -388,7 +388,7 @@ func dataSourceFloatingIPTargetNicDeletedToMap(deletedItem vpcv1.NetworkInterfac return deletedMap } -func dataSourceFloatingIPTargetPgDeletedToMap(deletedItem vpcv1.PublicGatewayReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceFloatingIPTargetPgDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_floating_ips.go b/ibm/service/vpc/data_source_ibm_is_floating_ips.go index b37d86d3cd..f62b12ad16 100644 --- a/ibm/service/vpc/data_source_ibm_is_floating_ips.go +++ b/ibm/service/vpc/data_source_ibm_is_floating_ips.go @@ -502,7 +502,7 @@ func dataSourceFloatingIPCollectionFloatingIpsTargetToMap(targetItemIntf vpcv1.F return targetMap } -func dataSourceFloatingIPCollectionTargetNicDeletedToMap(deletedItem vpcv1.NetworkInterfaceReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceFloatingIPCollectionTargetNicDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -511,7 +511,7 @@ func dataSourceFloatingIPCollectionTargetNicDeletedToMap(deletedItem vpcv1.Netwo return deletedMap } -func dataSourceFloatingIPCollectionTargetPgDeletedToMap(deletedItem vpcv1.PublicGatewayReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceFloatingIPCollectionTargetPgDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_flow_log.go b/ibm/service/vpc/data_source_ibm_is_flow_log.go index a4e54e313d..5f469286c7 100644 --- a/ibm/service/vpc/data_source_ibm_is_flow_log.go +++ b/ibm/service/vpc/data_source_ibm_is_flow_log.go @@ -392,7 +392,7 @@ func dataSourceFlowLogCollectorTargetToMap(targetItem vpcv1.FlowLogCollectorTarg return targetMap } -func dataSourceFlowLogCollectorTargetDeletedToMap(deletedItem vpcv1.NetworkInterfaceReferenceTargetContextDeleted) (deletedMap map[string]interface{}) { +func dataSourceFlowLogCollectorTargetDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -435,7 +435,7 @@ func dataSourceFlowLogCollectorVPCToMap(vpcItem vpcv1.VPCReference) (vpcMap map[ return vpcMap } -func dataSourceFlowLogCollectorVPCDeletedToMap(deletedItem vpcv1.VPCReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceFlowLogCollectorVPCDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_ike_policies.go b/ibm/service/vpc/data_source_ibm_is_ike_policies.go index e14ff6c8e2..b2a351e03a 100644 --- a/ibm/service/vpc/data_source_ibm_is_ike_policies.go +++ b/ibm/service/vpc/data_source_ibm_is_ike_policies.go @@ -283,7 +283,7 @@ func dataSourceIkePolicyCollectionIkePoliciesConnectionsToMap(connectionsItem vp return connectionsMap } -func dataSourceIkePolicyCollectionConnectionsDeletedToMap(deletedItem vpcv1.VPNGatewayConnectionReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceIkePolicyCollectionConnectionsDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_ike_policy.go b/ibm/service/vpc/data_source_ibm_is_ike_policy.go index 16580ea781..37ce857b16 100644 --- a/ibm/service/vpc/data_source_ibm_is_ike_policy.go +++ b/ibm/service/vpc/data_source_ibm_is_ike_policy.go @@ -284,7 +284,7 @@ func dataSourceIkePolicyConnectionsToMap(connectionsItem vpcv1.VPNGatewayConnect return connectionsMap } -func dataSourceIkePolicyConnectionsDeletedToMap(deletedItem vpcv1.VPNGatewayConnectionReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceIkePolicyConnectionsDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_instance.go b/ibm/service/vpc/data_source_ibm_is_instance.go index d2148851a6..0e1aed9a50 100644 --- a/ibm/service/vpc/data_source_ibm_is_instance.go +++ b/ibm/service/vpc/data_source_ibm_is_instance.go @@ -1193,7 +1193,7 @@ func DataSourceIBMISInstance() *schema.Resource { } } -func resourceIbmIsInstanceCatalogOfferingVersionPlanReferenceDeletedToMap(catalogOfferingVersionPlanReferenceDeleted vpcv1.CatalogOfferingVersionPlanReferenceDeleted) map[string]interface{} { +func resourceIbmIsInstanceCatalogOfferingVersionPlanReferenceDeletedToMap(catalogOfferingVersionPlanReferenceDeleted vpcv1.Deleted) map[string]interface{} { catalogOfferingVersionPlanReferenceDeletedMap := map[string]interface{}{} catalogOfferingVersionPlanReferenceDeletedMap["more_info"] = catalogOfferingVersionPlanReferenceDeleted.MoreInfo @@ -1701,7 +1701,7 @@ func instanceGetByName(d *schema.ResourceData, meta interface{}, name string) er } -func dataSourceInstanceReservationDeletedToMap(deletedItem vpcv1.ReservationReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceInstanceReservationDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -1832,7 +1832,7 @@ func dataSourceIBMIsInstanceVirtualNetworkInterfaceReferenceAttachmentContextToM modelMap["resource_type"] = model.ResourceType return modelMap, nil } -func dataSourceIBMIsInstanceInstanceNetworkAttachmentReferenceDeletedToMap(model *vpcv1.InstanceNetworkAttachmentReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsInstanceInstanceNetworkAttachmentReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil @@ -1869,13 +1869,13 @@ func dataSourceIBMIsInstanceSubnetReferenceToMap(model *vpcv1.SubnetReference) ( modelMap["resource_type"] = model.ResourceType return modelMap, nil } -func dataSourceIBMIsInstanceSubnetReferenceDeletedToMap(model *vpcv1.SubnetReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsInstanceSubnetReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil } -func dataSourceIBMIsInstanceReservedIPReferenceDeletedToMap(model *vpcv1.ReservedIPReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsInstanceReservedIPReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil diff --git a/ibm/service/vpc/data_source_ibm_is_instance_groups.go b/ibm/service/vpc/data_source_ibm_is_instance_groups.go index 14c00d3d32..aa5c7106fd 100644 --- a/ibm/service/vpc/data_source_ibm_is_instance_groups.go +++ b/ibm/service/vpc/data_source_ibm_is_instance_groups.go @@ -496,7 +496,7 @@ func DataSourceIBMIsInstanceGroupsInstanceTemplateReferenceToMap(model *vpcv1.In return modelMap, nil } -func DataSourceIBMIsInstanceGroupsInstanceTemplateReferenceDeletedToMap(model *vpcv1.InstanceTemplateReferenceDeleted) (map[string]interface{}, error) { +func DataSourceIBMIsInstanceGroupsInstanceTemplateReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.MoreInfo != nil { modelMap["more_info"] = *model.MoreInfo @@ -525,7 +525,7 @@ func DataSourceIBMIsInstanceGroupsLoadBalancerPoolReferenceToMap(model *vpcv1.Lo return modelMap, nil } -func DataSourceIBMIsInstanceGroupsLoadBalancerPoolReferenceDeletedToMap(model *vpcv1.LoadBalancerPoolReferenceDeleted) (map[string]interface{}, error) { +func DataSourceIBMIsInstanceGroupsLoadBalancerPoolReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.MoreInfo != nil { modelMap["more_info"] = *model.MoreInfo @@ -554,7 +554,7 @@ func DataSourceIBMIsInstanceGroupsInstanceGroupManagerReferenceToMap(model *vpcv return modelMap, nil } -func DataSourceIBMIsInstanceGroupsInstanceGroupManagerReferenceDeletedToMap(model *vpcv1.InstanceGroupManagerReferenceDeleted) (map[string]interface{}, error) { +func DataSourceIBMIsInstanceGroupsInstanceGroupManagerReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.MoreInfo != nil { modelMap["more_info"] = *model.MoreInfo @@ -603,7 +603,7 @@ func DataSourceIBMIsInstanceGroupsSubnetReferenceToMap(model *vpcv1.SubnetRefere return modelMap, nil } -func DataSourceIBMIsInstanceGroupsSubnetReferenceDeletedToMap(model *vpcv1.SubnetReferenceDeleted) (map[string]interface{}, error) { +func DataSourceIBMIsInstanceGroupsSubnetReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.MoreInfo != nil { modelMap["more_info"] = *model.MoreInfo @@ -638,7 +638,7 @@ func DataSourceIBMIsInstanceGroupsVPCReferenceToMap(model *vpcv1.VPCReference) ( return modelMap, nil } -func DataSourceIBMIsInstanceGroupsVPCReferenceDeletedToMap(model *vpcv1.VPCReferenceDeleted) (map[string]interface{}, error) { +func DataSourceIBMIsInstanceGroupsVPCReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.MoreInfo != nil { modelMap["more_info"] = *model.MoreInfo diff --git a/ibm/service/vpc/data_source_ibm_is_instance_network_attachment.go b/ibm/service/vpc/data_source_ibm_is_instance_network_attachment.go index 3764651581..b63fce5671 100644 --- a/ibm/service/vpc/data_source_ibm_is_instance_network_attachment.go +++ b/ibm/service/vpc/data_source_ibm_is_instance_network_attachment.go @@ -302,7 +302,7 @@ func dataSourceIBMIsInstanceNetworkAttachmentReservedIPReferenceToMap(model *vpc return modelMap, nil } -func dataSourceIBMIsInstanceNetworkAttachmentReservedIPReferenceDeletedToMap(model *vpcv1.ReservedIPReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsInstanceNetworkAttachmentReservedIPReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil @@ -325,7 +325,7 @@ func dataSourceIBMIsInstanceNetworkAttachmentSubnetReferenceToMap(model *vpcv1.S return modelMap, nil } -func dataSourceIBMIsInstanceNetworkAttachmentSubnetReferenceDeletedToMap(model *vpcv1.SubnetReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsInstanceNetworkAttachmentSubnetReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil diff --git a/ibm/service/vpc/data_source_ibm_is_instance_network_attachments.go b/ibm/service/vpc/data_source_ibm_is_instance_network_attachments.go index d530da4e44..0b2b66ab98 100644 --- a/ibm/service/vpc/data_source_ibm_is_instance_network_attachments.go +++ b/ibm/service/vpc/data_source_ibm_is_instance_network_attachments.go @@ -294,7 +294,7 @@ func dataSourceIBMIsInstanceNetworkAttachmentsReservedIPReferenceToMap(model *vp return modelMap, nil } -func dataSourceIBMIsInstanceNetworkAttachmentsReservedIPReferenceDeletedToMap(model *vpcv1.ReservedIPReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsInstanceNetworkAttachmentsReservedIPReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil @@ -317,7 +317,7 @@ func dataSourceIBMIsInstanceNetworkAttachmentsSubnetReferenceToMap(model *vpcv1. return modelMap, nil } -func dataSourceIBMIsInstanceNetworkAttachmentsSubnetReferenceDeletedToMap(model *vpcv1.SubnetReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsInstanceNetworkAttachmentsSubnetReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil diff --git a/ibm/service/vpc/data_source_ibm_is_instance_network_interface.go b/ibm/service/vpc/data_source_ibm_is_instance_network_interface.go index bba64f8c06..e33f6c812f 100644 --- a/ibm/service/vpc/data_source_ibm_is_instance_network_interface.go +++ b/ibm/service/vpc/data_source_ibm_is_instance_network_interface.go @@ -409,7 +409,7 @@ func dataSourceNetworkInterfaceFloatingIpsToMap(floatingIpsItem vpcv1.FloatingIP return floatingIpsMap } -func dataSourceNetworkInterfaceFloatingIpsDeletedToMap(deletedItem vpcv1.FloatingIPReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceNetworkInterfaceFloatingIpsDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -452,7 +452,7 @@ func dataSourceNetworkInterfaceSecurityGroupsToMap(securityGroupsItem vpcv1.Secu return securityGroupsMap } -func dataSourceNetworkInterfaceSecurityGroupsDeletedToMap(deletedItem vpcv1.SecurityGroupReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceNetworkInterfaceSecurityGroupsDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -495,7 +495,7 @@ func dataSourceNetworkInterfaceSubnetToMap(subnetItem vpcv1.SubnetReference) (su return subnetMap } -func dataSourceNetworkInterfaceSubnetDeletedToMap(deletedItem vpcv1.SubnetReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceNetworkInterfaceSubnetDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_ipsec_policies.go b/ibm/service/vpc/data_source_ibm_is_ipsec_policies.go index 37fee725c3..72cf4148f4 100644 --- a/ibm/service/vpc/data_source_ibm_is_ipsec_policies.go +++ b/ibm/service/vpc/data_source_ibm_is_ipsec_policies.go @@ -283,7 +283,7 @@ func dataSourceIPsecPolicyCollectionIpsecPoliciesConnectionsToMap(connectionsIte return connectionsMap } -func dataSourceIPsecPolicyCollectionConnectionsDeletedToMap(deletedItem vpcv1.VPNGatewayConnectionReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceIPsecPolicyCollectionConnectionsDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_ipsec_policy.go b/ibm/service/vpc/data_source_ibm_is_ipsec_policy.go index b4a7a64bda..ce2c9e04cd 100644 --- a/ibm/service/vpc/data_source_ibm_is_ipsec_policy.go +++ b/ibm/service/vpc/data_source_ibm_is_ipsec_policy.go @@ -286,7 +286,7 @@ func dataSourceIPsecPolicyConnectionsToMap(connectionsItem vpcv1.VPNGatewayConne return connectionsMap } -func dataSourceIPsecPolicyConnectionsDeletedToMap(deletedItem vpcv1.VPNGatewayConnectionReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceIPsecPolicyConnectionsDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_lb_listener.go b/ibm/service/vpc/data_source_ibm_is_lb_listener.go index cb8fd43cf1..c516c118d0 100644 --- a/ibm/service/vpc/data_source_ibm_is_lb_listener.go +++ b/ibm/service/vpc/data_source_ibm_is_lb_listener.go @@ -352,7 +352,7 @@ func dataSourceLoadBalancerListenerDefaultPoolToMap(defaultPoolItem vpcv1.LoadBa return defaultPoolMap } -func dataSourceLoadBalancerListenerDefaultPoolDeletedToMap(deletedItem vpcv1.LoadBalancerPoolReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceLoadBalancerListenerDefaultPoolDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -408,7 +408,7 @@ func dataSourceLoadBalancerListenerHTTPSRedirectListenerToMap(listenerItem vpcv1 return listenerMap } -func dataSourceLoadBalancerListenerListenerDeletedToMap(deletedItem vpcv1.LoadBalancerListenerReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceLoadBalancerListenerListenerDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -445,7 +445,7 @@ func dataSourceLoadBalancerListenerPoliciesToMap(policiesItem vpcv1.LoadBalancer return policiesMap } -func dataSourceLoadBalancerListenerPoliciesDeletedToMap(deletedItem vpcv1.LoadBalancerListenerPolicyReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceLoadBalancerListenerPoliciesDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_lb_listener_policies.go b/ibm/service/vpc/data_source_ibm_is_lb_listener_policies.go index 4a3232fce1..363400096b 100644 --- a/ibm/service/vpc/data_source_ibm_is_lb_listener_policies.go +++ b/ibm/service/vpc/data_source_ibm_is_lb_listener_policies.go @@ -299,7 +299,7 @@ func dataSourceLoadBalancerListenerPolicyCollectionPoliciesRulesToMap(rulesItem return rulesMap } -func dataSourceLoadBalancerListenerPolicyCollectionRulesDeletedToMap(deletedItem vpcv1.LoadBalancerListenerPolicyRuleReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceLoadBalancerListenerPolicyCollectionRulesDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -346,7 +346,7 @@ func dataSourceLoadBalancerListenerPolicyCollectionPoliciesTargetToMap(targetIte return targetMap } -func dataSourceLoadBalancerListenerPolicyCollectionTargetDeletedToMap(deletedItem vpcv1.LoadBalancerPoolReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceLoadBalancerListenerPolicyCollectionTargetDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -375,7 +375,7 @@ func dataSourceLoadBalancerListenerPolicyCollectionTargetListenerToMap(listenerI return listenerMap } -func dataSourceLoadBalancerListenerPolicyCollectionListenerDeletedToMap(deletedItem vpcv1.LoadBalancerListenerReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceLoadBalancerListenerPolicyCollectionListenerDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_lb_listener_policy.go b/ibm/service/vpc/data_source_ibm_is_lb_listener_policy.go index 9ebd0df2bb..90ba7066f6 100644 --- a/ibm/service/vpc/data_source_ibm_is_lb_listener_policy.go +++ b/ibm/service/vpc/data_source_ibm_is_lb_listener_policy.go @@ -270,7 +270,7 @@ func dataSourceLoadBalancerListenerPolicyRulesToMap(rulesItem vpcv1.LoadBalancer return rulesMap } -func dataSourceLoadBalancerListenerPolicyRulesDeletedToMap(deletedItem vpcv1.LoadBalancerListenerPolicyRuleReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceLoadBalancerListenerPolicyRulesDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -325,7 +325,7 @@ func dataSourceLoadBalancerListenerPolicyTargetToMap(targetItem vpcv1.LoadBalanc return targetMap } -func dataSourceLoadBalancerListenerPolicyTargetDeletedToMap(deletedItem vpcv1.LoadBalancerPoolReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceLoadBalancerListenerPolicyTargetDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -354,7 +354,7 @@ func dataSourceLoadBalancerListenerPolicyTargetListenerToMap(listenerItem vpcv1. return listenerMap } -func dataSourceLoadBalancerListenerPolicyListenerDeletedToMap(deletedItem vpcv1.LoadBalancerListenerReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceLoadBalancerListenerPolicyListenerDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_lb_listeners.go b/ibm/service/vpc/data_source_ibm_is_lb_listeners.go index 97c569fc36..4bde6f70fa 100644 --- a/ibm/service/vpc/data_source_ibm_is_lb_listeners.go +++ b/ibm/service/vpc/data_source_ibm_is_lb_listeners.go @@ -368,7 +368,7 @@ func dataSourceLoadBalancerListenerCollectionListenersDefaultPoolToMap(defaultPo return defaultPoolMap } -func dataSourceLoadBalancerListenerCollectionDefaultPoolDeletedToMap(deletedItem vpcv1.LoadBalancerPoolReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceLoadBalancerListenerCollectionDefaultPoolDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -416,7 +416,7 @@ func dataSourceLoadBalancerListenerCollectionHTTPSRedirectListenerToMap(listener return listenerMap } -func dataSourceLoadBalancerListenerCollectionListenerDeletedToMap(deletedItem vpcv1.LoadBalancerListenerReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceLoadBalancerListenerCollectionListenerDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -445,7 +445,7 @@ func dataSourceLoadBalancerListenerCollectionListenersPoliciesToMap(policiesItem return policiesMap } -func dataSourceLoadBalancerListenerCollectionPoliciesDeletedToMap(deletedItem vpcv1.LoadBalancerListenerPolicyReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceLoadBalancerListenerCollectionPoliciesDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_lb_pool.go b/ibm/service/vpc/data_source_ibm_is_lb_pool.go index 9e1c8870d2..c875c48d2c 100644 --- a/ibm/service/vpc/data_source_ibm_is_lb_pool.go +++ b/ibm/service/vpc/data_source_ibm_is_lb_pool.go @@ -377,7 +377,7 @@ func dataSourceLoadBalancerPoolInstanceGroupToMap(instanceGroupItem vpcv1.Instan return instanceGroupMap } -func dataSourceLoadBalancerPoolInstanceGroupDeletedToMap(deletedItem vpcv1.InstanceGroupReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceLoadBalancerPoolInstanceGroupDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -414,7 +414,7 @@ func dataSourceLoadBalancerPoolMembersToMap(membersItem vpcv1.LoadBalancerPoolMe return membersMap } -func dataSourceLoadBalancerPoolMembersDeletedToMap(deletedItem vpcv1.LoadBalancerPoolMemberReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceLoadBalancerPoolMembersDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_lb_pool_member.go b/ibm/service/vpc/data_source_ibm_is_lb_pool_member.go index 8ccd2550f2..78619eb6bf 100644 --- a/ibm/service/vpc/data_source_ibm_is_lb_pool_member.go +++ b/ibm/service/vpc/data_source_ibm_is_lb_pool_member.go @@ -202,7 +202,7 @@ func dataSourceLoadBalancerPoolMemberTargetToMap(targetItem vpcv1.LoadBalancerPo return targetMap } -func dataSourceLoadBalancerPoolMemberTargetDeletedToMap(deletedItem vpcv1.InstanceReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceLoadBalancerPoolMemberTargetDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_lb_pool_members.go b/ibm/service/vpc/data_source_ibm_is_lb_pool_members.go index 8d07993be8..ee158afe1e 100644 --- a/ibm/service/vpc/data_source_ibm_is_lb_pool_members.go +++ b/ibm/service/vpc/data_source_ibm_is_lb_pool_members.go @@ -231,7 +231,7 @@ func dataSourceLoadBalancerPoolMemberCollectionMembersTargetToMap(targetItem vpc return targetMap } -func dataSourceLoadBalancerPoolMemberCollectionTargetDeletedToMap(deletedItem vpcv1.InstanceReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceLoadBalancerPoolMemberCollectionTargetDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_lb_pools.go b/ibm/service/vpc/data_source_ibm_is_lb_pools.go index 7726246568..1a2595e169 100644 --- a/ibm/service/vpc/data_source_ibm_is_lb_pools.go +++ b/ibm/service/vpc/data_source_ibm_is_lb_pools.go @@ -362,7 +362,7 @@ func dataSourceLoadBalancerPoolCollectionPoolsInstanceGroupToMap(instanceGroupIt return instanceGroupMap } -func dataSourceLoadBalancerPoolCollectionInstanceGroupDeletedToMap(deletedItem vpcv1.InstanceGroupReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceLoadBalancerPoolCollectionInstanceGroupDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -391,7 +391,7 @@ func dataSourceLoadBalancerPoolCollectionPoolsMembersToMap(membersItem vpcv1.Loa return membersMap } -func dataSourceLoadBalancerPoolCollectionMembersDeletedToMap(deletedItem vpcv1.LoadBalancerPoolMemberReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceLoadBalancerPoolCollectionMembersDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_network_acl.go b/ibm/service/vpc/data_source_ibm_is_network_acl.go index 36a52369b3..bfe70ea60f 100644 --- a/ibm/service/vpc/data_source_ibm_is_network_acl.go +++ b/ibm/service/vpc/data_source_ibm_is_network_acl.go @@ -623,7 +623,7 @@ func dataSourceNetworkACLRulesBeforeToMap(beforeItem vpcv1.NetworkACLRuleReferen return beforeMap } -func dataSourceNetworkACLBeforeDeletedToMap(deletedItem vpcv1.NetworkACLRuleReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceNetworkACLBeforeDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -666,7 +666,7 @@ func dataSourceNetworkACLSubnetsToMap(subnetsItem vpcv1.SubnetReference) (subnet return subnetsMap } -func dataSourceNetworkACLSubnetsDeletedToMap(deletedItem vpcv1.SubnetReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceNetworkACLSubnetsDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -709,7 +709,7 @@ func dataSourceNetworkACLVPCToMap(vpcItem vpcv1.VPCReference) (vpcMap map[string return vpcMap } -func dataSourceNetworkACLVPCDeletedToMap(deletedItem vpcv1.VPCReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceNetworkACLVPCDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_network_acls.go b/ibm/service/vpc/data_source_ibm_is_network_acls.go index 5aa14ba041..7d89bcf894 100644 --- a/ibm/service/vpc/data_source_ibm_is_network_acls.go +++ b/ibm/service/vpc/data_source_ibm_is_network_acls.go @@ -502,7 +502,7 @@ func dataSourceNetworkACLCollectionRulesBeforeToMap(beforeItem vpcv1.NetworkACLR return beforeMap } -func dataSourceNetworkACLCollectionBeforeDeletedToMap(deletedItem vpcv1.NetworkACLRuleReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceNetworkACLCollectionBeforeDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -537,7 +537,7 @@ func dataSourceNetworkACLCollectionNetworkAclsSubnetsToMap(subnetsItem vpcv1.Sub return subnetsMap } -func dataSourceNetworkACLCollectionSubnetsDeletedToMap(deletedItem vpcv1.SubnetReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceNetworkACLCollectionSubnetsDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -572,7 +572,7 @@ func dataSourceNetworkACLCollectionNetworkAclsVPCToMap(vpcItem vpcv1.VPCReferenc return vpcMap } -func dataSourceNetworkACLCollectionVPCDeletedToMap(deletedItem vpcv1.VPCReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceNetworkACLCollectionVPCDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_security_group_rule.go b/ibm/service/vpc/data_source_ibm_is_security_group_rule.go index 4226aec4ea..57c30352fc 100644 --- a/ibm/service/vpc/data_source_ibm_is_security_group_rule.go +++ b/ibm/service/vpc/data_source_ibm_is_security_group_rule.go @@ -356,7 +356,7 @@ func dataSourceSecurityGroupRuleLocalToMap(localItem *vpcv1.SecurityGroupRuleLoc return localMap } -func dataSourceSecurityGroupRuleRemoteDeletedToMap(deletedItem *vpcv1.SecurityGroupReferenceDeleted) (resultMap map[string]interface{}) { +func dataSourceSecurityGroupRuleRemoteDeletedToMap(deletedItem *vpcv1.Deleted) (resultMap map[string]interface{}) { resultMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_security_group_rules.go b/ibm/service/vpc/data_source_ibm_is_security_group_rules.go index 0917fd97e5..f99edd4f19 100644 --- a/ibm/service/vpc/data_source_ibm_is_security_group_rules.go +++ b/ibm/service/vpc/data_source_ibm_is_security_group_rules.go @@ -263,7 +263,7 @@ func dataSourceIBMIsSecurityGroupRulesID(d *schema.ResourceData) string { return time.Now().UTC().String() } -func dataSourceSecurityGroupRuleCollectionRemoteDeletedToMap(deletedItem *vpcv1.SecurityGroupReferenceDeleted) (resultMap map[string]interface{}) { +func dataSourceSecurityGroupRuleCollectionRemoteDeletedToMap(deletedItem *vpcv1.Deleted) (resultMap map[string]interface{}) { resultMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_security_groups.go b/ibm/service/vpc/data_source_ibm_is_security_groups.go index a24137927c..791c7fc43f 100644 --- a/ibm/service/vpc/data_source_ibm_is_security_groups.go +++ b/ibm/service/vpc/data_source_ibm_is_security_groups.go @@ -589,7 +589,7 @@ func dataSourceSecurityGroupCollectionSecurityGroupsRulesToMap(rulesItem vpcv1.S return resultMap } -func dataSourceSecurityGroupCollectionRemoteDeletedToMap(deletedItem *vpcv1.SecurityGroupReferenceDeleted) (resultMap map[string]interface{}) { +func dataSourceSecurityGroupCollectionRemoteDeletedToMap(deletedItem *vpcv1.Deleted) (resultMap map[string]interface{}) { resultMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -654,7 +654,7 @@ func dataSourceSecurityGroupCollectionSecurityGroupsTargetsToMap(targetsItem vpc return resultMap } -func dataSourceSecurityGroupCollectionTargetsDeletedToMap(deletedItem *vpcv1.NetworkInterfaceReferenceTargetContextDeleted) (resultMap map[string]interface{}) { +func dataSourceSecurityGroupCollectionTargetsDeletedToMap(deletedItem *vpcv1.Deleted) (resultMap map[string]interface{}) { resultMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -664,7 +664,7 @@ func dataSourceSecurityGroupCollectionTargetsDeletedToMap(deletedItem *vpcv1.Net return resultMap } -func dataSourceSecurityGroupCollectionTargetsDeleted2ToMap(deletedItem *vpcv1.LoadBalancerReferenceDeleted) (resultMap map[string]interface{}) { +func dataSourceSecurityGroupCollectionTargetsDeleted2ToMap(deletedItem *vpcv1.Deleted) (resultMap map[string]interface{}) { resultMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -699,7 +699,7 @@ func dataSourceSecurityGroupCollectionSecurityGroupsVPCToMap(vpcItem *vpcv1.VPCR return resultMap } -func dataSourceSecurityGroupCollectionVPCDeletedToMap(deletedItem *vpcv1.VPCReferenceDeleted) (resultMap map[string]interface{}) { +func dataSourceSecurityGroupCollectionVPCDeletedToMap(deletedItem *vpcv1.Deleted) (resultMap map[string]interface{}) { resultMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_share.go b/ibm/service/vpc/data_source_ibm_is_share.go index 48100560e9..6c321acb33 100644 --- a/ibm/service/vpc/data_source_ibm_is_share.go +++ b/ibm/service/vpc/data_source_ibm_is_share.go @@ -778,7 +778,7 @@ func dataSourceShareTargetsToMap(targetsItem vpcv1.ShareMountTargetReference) (t return targetsMap } -func dataSourceShareTargetsDeletedToMap(deletedItem vpcv1.ShareMountTargetReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceShareTargetsDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -868,7 +868,7 @@ func dataSourceShareReplicaShareToMap(replicaShareItem vpcv1.ShareReference) (re return replicaShareMap } -func dataSourceShareReplicaShareDeletedToMap(deletedItem vpcv1.ShareReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceShareReplicaShareDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -938,7 +938,7 @@ func dataSourceShareSourceShareToMap(sourceShareItem vpcv1.ShareReference) (sour return sourceShareMap } -func dataSourceShareSourceShareDeletedToMap(deletedItem vpcv1.ShareReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceShareSourceShareDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_share_accessor_binding.go b/ibm/service/vpc/data_source_ibm_is_share_accessor_binding.go index 16432fa551..c4030f99c2 100644 --- a/ibm/service/vpc/data_source_ibm_is_share_accessor_binding.go +++ b/ibm/service/vpc/data_source_ibm_is_share_accessor_binding.go @@ -251,7 +251,7 @@ func DataSourceIBMIsShareAccessorBindingShareAccessorBindingAccessorToMap(model } } -func DataSourceIBMIsShareAccessorBindingShareReferenceDeletedToMap(model *vpcv1.ShareReferenceDeleted) (map[string]interface{}, error) { +func DataSourceIBMIsShareAccessorBindingShareReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = *model.MoreInfo return modelMap, nil diff --git a/ibm/service/vpc/data_source_ibm_is_share_accessor_binding_test.go b/ibm/service/vpc/data_source_ibm_is_share_accessor_binding_test.go index ffbadde4a5..70ffb32cbf 100644 --- a/ibm/service/vpc/data_source_ibm_is_share_accessor_binding_test.go +++ b/ibm/service/vpc/data_source_ibm_is_share_accessor_binding_test.go @@ -89,7 +89,7 @@ func TestDataSourceIBMIsShareAccessorBindingShareAccessorBindingAccessorToMap(t assert.Equal(t, result, model) } - shareReferenceDeletedModel := new(vpcv1.ShareReferenceDeleted) + shareReferenceDeletedModel := new(vpcv1.Deleted) shareReferenceDeletedModel.MoreInfo = core.StringPtr("https://cloud.ibm.com/apidocs/vpc#deleted-resources") accountReferenceModel := new(vpcv1.AccountReference) @@ -126,7 +126,7 @@ func TestDataSourceIBMIsShareAccessorBindingShareReferenceDeletedToMap(t *testin assert.Equal(t, result, model) } - model := new(vpcv1.ShareReferenceDeleted) + model := new(vpcv1.Deleted) model.MoreInfo = core.StringPtr("https://cloud.ibm.com/apidocs/vpc#deleted-resources") result, err := vpc.DataSourceIBMIsShareAccessorBindingShareReferenceDeletedToMap(model) @@ -233,7 +233,7 @@ func TestDataSourceIBMIsShareAccessorBindingShareAccessorBindingAccessorShareRef assert.Equal(t, result, model) } - shareReferenceDeletedModel := new(vpcv1.ShareReferenceDeleted) + shareReferenceDeletedModel := new(vpcv1.Deleted) shareReferenceDeletedModel.MoreInfo = core.StringPtr("https://cloud.ibm.com/apidocs/vpc#deleted-resources") accountReferenceModel := new(vpcv1.AccountReference) diff --git a/ibm/service/vpc/data_source_ibm_is_share_accessor_bindings.go b/ibm/service/vpc/data_source_ibm_is_share_accessor_bindings.go index 8649fa6a09..4fefad2bd3 100644 --- a/ibm/service/vpc/data_source_ibm_is_share_accessor_bindings.go +++ b/ibm/service/vpc/data_source_ibm_is_share_accessor_bindings.go @@ -274,7 +274,7 @@ func DataSourceIBMIsShareAccessorBindingsShareAccessorBindingAccessorToMap(model } } -func DataSourceIBMIsShareAccessorBindingsShareReferenceDeletedToMap(model *vpcv1.ShareReferenceDeleted) (map[string]interface{}, error) { +func DataSourceIBMIsShareAccessorBindingsShareReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = *model.MoreInfo return modelMap, nil diff --git a/ibm/service/vpc/data_source_ibm_is_share_accessor_bindings_test.go b/ibm/service/vpc/data_source_ibm_is_share_accessor_bindings_test.go index f717e6b047..6af1a6f07d 100644 --- a/ibm/service/vpc/data_source_ibm_is_share_accessor_bindings_test.go +++ b/ibm/service/vpc/data_source_ibm_is_share_accessor_bindings_test.go @@ -91,7 +91,7 @@ func TestDataSourceIBMIsShareAccessorBindingsShareAccessorBindingToMap(t *testin assert.Equal(t, result, model) } - shareReferenceDeletedModel := new(vpcv1.ShareReferenceDeleted) + shareReferenceDeletedModel := new(vpcv1.Deleted) shareReferenceDeletedModel.MoreInfo = core.StringPtr("https://cloud.ibm.com/apidocs/vpc#deleted-resources") accountReferenceModel := new(vpcv1.AccountReference) @@ -157,7 +157,7 @@ func TestDataSourceIBMIsShareAccessorBindingsShareAccessorBindingAccessorToMap(t assert.Equal(t, result, model) } - shareReferenceDeletedModel := new(vpcv1.ShareReferenceDeleted) + shareReferenceDeletedModel := new(vpcv1.Deleted) shareReferenceDeletedModel.MoreInfo = core.StringPtr("https://cloud.ibm.com/apidocs/vpc#deleted-resources") accountReferenceModel := new(vpcv1.AccountReference) @@ -194,7 +194,7 @@ func TestDataSourceIBMIsShareAccessorBindingsShareReferenceDeletedToMap(t *testi assert.Equal(t, result, model) } - model := new(vpcv1.ShareReferenceDeleted) + model := new(vpcv1.Deleted) model.MoreInfo = core.StringPtr("https://cloud.ibm.com/apidocs/vpc#deleted-resources") result, err := vpc.DataSourceIBMIsShareAccessorBindingsShareReferenceDeletedToMap(model) @@ -301,7 +301,7 @@ func TestDataSourceIBMIsShareAccessorBindingsShareAccessorBindingAccessorShareRe assert.Equal(t, result, model) } - shareReferenceDeletedModel := new(vpcv1.ShareReferenceDeleted) + shareReferenceDeletedModel := new(vpcv1.Deleted) shareReferenceDeletedModel.MoreInfo = core.StringPtr("https://cloud.ibm.com/apidocs/vpc#deleted-resources") accountReferenceModel := new(vpcv1.AccountReference) diff --git a/ibm/service/vpc/data_source_ibm_is_share_mount_target.go b/ibm/service/vpc/data_source_ibm_is_share_mount_target.go index 577f223188..8b2ec5dea9 100644 --- a/ibm/service/vpc/data_source_ibm_is_share_mount_target.go +++ b/ibm/service/vpc/data_source_ibm_is_share_mount_target.go @@ -427,7 +427,7 @@ func dataSourceShareMountTargetVpcToMap(vpcItem vpcv1.VPCReference) (vpcMap map[ return vpcMap } -func dataSourceShareMountTargetVpcDeletedToMap(deletedItem vpcv1.VPCReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceShareMountTargetVpcDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -474,7 +474,7 @@ func dataSourceShareTargetPrimaryIPToMap(primaryIPItem vpcv1.ReservedIPReference return primaryIPMap } -func dataSourceShareTargetPrimaryIPDeletedToMap(deletedItem vpcv1.ReservedIPReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceShareTargetPrimaryIPDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -521,7 +521,7 @@ func dataSourceShareTargetSubnetToMap(subnetItem vpcv1.SubnetReference) (subnetM return subnetMap } -func dataSourceShareTargetSubnetDeletedToMap(deletedItem vpcv1.SubnetReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceShareTargetSubnetDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_snapshot.go b/ibm/service/vpc/data_source_ibm_is_snapshot.go index 3e82882fde..75a3ca6cdc 100644 --- a/ibm/service/vpc/data_source_ibm_is_snapshot.go +++ b/ibm/service/vpc/data_source_ibm_is_snapshot.go @@ -748,7 +748,7 @@ func snapshotGetByNameOrID(d *schema.ResourceData, meta interface{}, name, id st } } -func resourceIbmIsSnapshotCatalogOfferingVersionPlanReferenceDeletedToMap(catalogOfferingVersionPlanReferenceDeleted vpcv1.CatalogOfferingVersionPlanReferenceDeleted) map[string]interface{} { +func resourceIbmIsSnapshotCatalogOfferingVersionPlanReferenceDeletedToMap(catalogOfferingVersionPlanReferenceDeleted vpcv1.Deleted) map[string]interface{} { catalogOfferingVersionPlanReferenceDeletedMap := map[string]interface{}{} catalogOfferingVersionPlanReferenceDeletedMap["more_info"] = catalogOfferingVersionPlanReferenceDeleted.MoreInfo diff --git a/ibm/service/vpc/data_source_ibm_is_snapshot_consistency_group.go b/ibm/service/vpc/data_source_ibm_is_snapshot_consistency_group.go index 6dc6c45c17..9b193fb4b4 100644 --- a/ibm/service/vpc/data_source_ibm_is_snapshot_consistency_group.go +++ b/ibm/service/vpc/data_source_ibm_is_snapshot_consistency_group.go @@ -510,7 +510,7 @@ func dataSourceIBMIsSnapshotConsistencyGroupBackupPolicyPlanReferenceToMap(model return modelMap, nil } -func dataSourceIBMIsSnapshotConsistencyGroupBackupPolicyPlanReferenceDeletedToMap(model *vpcv1.BackupPolicyPlanReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsSnapshotConsistencyGroupBackupPolicyPlanReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil @@ -567,7 +567,7 @@ func dataSourceIBMIsSnapshotConsistencyGroupSnapshotConsistencyGroupSnapshotsIte return modelMap, nil } -func dataSourceIBMIsSnapshotConsistencyGroupSnapshotReferenceDeletedToMap(model *vpcv1.SnapshotReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsSnapshotConsistencyGroupSnapshotReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil diff --git a/ibm/service/vpc/data_source_ibm_is_snapshots.go b/ibm/service/vpc/data_source_ibm_is_snapshots.go index ef227c9250..4689bc75e1 100644 --- a/ibm/service/vpc/data_source_ibm_is_snapshots.go +++ b/ibm/service/vpc/data_source_ibm_is_snapshots.go @@ -802,7 +802,7 @@ func dataSourceIBMIsSnapshotsSnapshotCopiesItemToMap(model *vpcv1.SnapshotCopies return modelMap, nil } -func dataSourceIBMIsSnapshotsSnapshotRemoteReferenceDeletedToMap(model *vpcv1.SnapshotReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsSnapshotsSnapshotRemoteReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.MoreInfo != nil { modelMap["more_info"] = *model.MoreInfo diff --git a/ibm/service/vpc/data_source_ibm_is_subnet.go b/ibm/service/vpc/data_source_ibm_is_subnet.go index 92154b1759..57885ea49c 100644 --- a/ibm/service/vpc/data_source_ibm_is_subnet.go +++ b/ibm/service/vpc/data_source_ibm_is_subnet.go @@ -318,7 +318,7 @@ func subnetGetByNameOrID(d *schema.ResourceData, meta interface{}) error { return nil } -func dataSourcesubnetRoutingTableDeletedToMap(deletedItem vpcv1.RoutingTableReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourcesubnetRoutingTableDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_subnet_reserved_ips.go b/ibm/service/vpc/data_source_ibm_is_subnet_reserved_ips.go index 7777bb175d..6f85003c3e 100644 --- a/ibm/service/vpc/data_source_ibm_is_subnet_reserved_ips.go +++ b/ibm/service/vpc/data_source_ibm_is_subnet_reserved_ips.go @@ -277,7 +277,7 @@ func dataSourceIBMIsReservedIPReservedIPTargetToMap(model vpcv1.ReservedIPTarget } } -func dataSourceIBMIsReservedIPEndpointGatewayReferenceDeletedToMap(model *vpcv1.EndpointGatewayReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsReservedIPEndpointGatewayReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil @@ -326,7 +326,7 @@ func dataSourceIBMIsReservedIPReservedIPTargetNetworkInterfaceReferenceTargetCon return modelMap, nil } -func dataSourceIBMIsReservedIPNetworkInterfaceReferenceTargetContextDeletedToMap(model *vpcv1.NetworkInterfaceReferenceTargetContextDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsReservedIPNetworkInterfaceReferenceTargetContextDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil @@ -348,7 +348,7 @@ func dataSourceIBMIsReservedIPReservedIPTargetBareMetalServerNetworkInterfaceRef return modelMap, nil } -func dataSourceIBMIsReservedIPBareMetalServerNetworkInterfaceReferenceTargetContextDeletedToMap(model *vpcv1.BareMetalServerNetworkInterfaceReferenceTargetContextDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsReservedIPBareMetalServerNetworkInterfaceReferenceTargetContextDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil @@ -371,7 +371,7 @@ func dataSourceIBMIsReservedIPReservedIPTargetLoadBalancerReferenceToMap(model * return modelMap, nil } -func dataSourceIBMIsReservedIPLoadBalancerReferenceDeletedToMap(model *vpcv1.LoadBalancerReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsReservedIPLoadBalancerReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil @@ -394,7 +394,7 @@ func dataSourceIBMIsReservedIPReservedIPTargetVPNGatewayReferenceToMap(model *vp return modelMap, nil } -func dataSourceIBMIsReservedIPVPNGatewayReferenceDeletedToMap(model *vpcv1.VPNGatewayReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsReservedIPVPNGatewayReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil @@ -417,7 +417,7 @@ func dataSourceIBMIsReservedIPReservedIPTargetVPNServerReferenceToMap(model *vpc return modelMap, nil } -func dataSourceIBMIsReservedIPVPNServerReferenceDeletedToMap(model *vpcv1.VPNServerReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsReservedIPVPNServerReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil @@ -437,7 +437,7 @@ func dataSourceIBMIsReservedIPReservedIPTargetGenericResourceReferenceToMap(mode return modelMap, nil } -func dataSourceIBMIsReservedIPGenericResourceReferenceDeletedToMap(model *vpcv1.GenericResourceReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsReservedIPGenericResourceReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil diff --git a/ibm/service/vpc/data_source_ibm_is_virtual_network_interface.go b/ibm/service/vpc/data_source_ibm_is_virtual_network_interface.go index ed62a65983..461876a103 100644 --- a/ibm/service/vpc/data_source_ibm_is_virtual_network_interface.go +++ b/ibm/service/vpc/data_source_ibm_is_virtual_network_interface.go @@ -630,7 +630,7 @@ func dataSourceIBMIsVirtualNetworkInterfaceReservedIPReferenceToMap(model *vpcv1 return modelMap, nil } -func dataSourceIBMIsVirtualNetworkInterfaceReservedIPReferenceDeletedToMap(model *vpcv1.ReservedIPReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsVirtualNetworkInterfaceReservedIPReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.MoreInfo != nil { modelMap["more_info"] = *model.MoreInfo @@ -676,7 +676,7 @@ func dataSourceIBMIsVirtualNetworkInterfaceSecurityGroupReferenceToMap(model *vp return modelMap, nil } -func dataSourceIBMIsVirtualNetworkInterfaceSecurityGroupReferenceDeletedToMap(model *vpcv1.SecurityGroupReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsVirtualNetworkInterfaceSecurityGroupReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.MoreInfo != nil { modelMap["more_info"] = *model.MoreInfo @@ -711,7 +711,7 @@ func dataSourceIBMIsVirtualNetworkInterfaceSubnetReferenceToMap(model *vpcv1.Sub return modelMap, nil } -func dataSourceIBMIsVirtualNetworkInterfaceSubnetReferenceDeletedToMap(model *vpcv1.SubnetReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsVirtualNetworkInterfaceSubnetReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.MoreInfo != nil { modelMap["more_info"] = *model.MoreInfo @@ -750,7 +750,7 @@ func dataSourceIBMIsVirtualNetworkInterfaceVirtualNetworkInterfaceTargetToMap(mo } } -func dataSourceIBMIsVirtualNetworkInterfaceShareMountTargetReferenceDeletedToMap(model *vpcv1.ShareMountTargetReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsVirtualNetworkInterfaceShareMountTargetReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.MoreInfo != nil { modelMap["more_info"] = *model.MoreInfo @@ -809,7 +809,7 @@ func dataSourceIBMIsVirtualNetworkInterfaceVPCReferenceToMap(model *vpcv1.VPCRef return modelMap, nil } -func dataSourceIBMIsVirtualNetworkInterfaceVPCReferenceDeletedToMap(model *vpcv1.VPCReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsVirtualNetworkInterfaceVPCReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.MoreInfo != nil { modelMap["more_info"] = *model.MoreInfo diff --git a/ibm/service/vpc/data_source_ibm_is_volume.go b/ibm/service/vpc/data_source_ibm_is_volume.go index 9994ed1797..95af9adeab 100644 --- a/ibm/service/vpc/data_source_ibm_is_volume.go +++ b/ibm/service/vpc/data_source_ibm_is_volume.go @@ -470,7 +470,7 @@ func volumeGet(d *schema.ResourceData, meta interface{}, name string) error { return nil } -func resourceIbmIsVolumeCatalogOfferingVersionPlanReferenceDeletedToMap(catalogOfferingVersionPlanReferenceDeleted vpcv1.CatalogOfferingVersionPlanReferenceDeleted) map[string]interface{} { +func resourceIbmIsVolumeCatalogOfferingVersionPlanReferenceDeletedToMap(catalogOfferingVersionPlanReferenceDeleted vpcv1.Deleted) map[string]interface{} { catalogOfferingVersionPlanReferenceDeletedMap := map[string]interface{}{} catalogOfferingVersionPlanReferenceDeletedMap["more_info"] = catalogOfferingVersionPlanReferenceDeleted.MoreInfo diff --git a/ibm/service/vpc/data_source_ibm_is_volumes.go b/ibm/service/vpc/data_source_ibm_is_volumes.go index aec47ddeed..8a8e449da4 100644 --- a/ibm/service/vpc/data_source_ibm_is_volumes.go +++ b/ibm/service/vpc/data_source_ibm_is_volumes.go @@ -952,7 +952,7 @@ func dataSourceVolumeCollectionVolumesSourceImageToMap(sourceImageItem vpcv1.Ima return sourceImageMap } -func dataSourceVolumeCollectionSourceImageDeletedToMap(deletedItem vpcv1.ImageReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceVolumeCollectionSourceImageDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -990,7 +990,7 @@ func dataSourceVolumeCollectionVolumesSourceSnapshotToMap(sourceSnapshotItem vpc return sourceSnapshotMap } -func dataSourceVolumeCollectionSourceSnapshotDeletedToMap(deletedItem vpcv1.SnapshotReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceVolumeCollectionSourceSnapshotDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -1072,7 +1072,7 @@ func dataSourceVolumeCollectionVolumesVolumeAttachmentsToMap(volumeAttachmentsIt return volumeAttachmentsMap } -func dataSourceVolumeCollectionVolumeAttachmentsDeletedToMap(deletedItem vpcv1.VolumeAttachmentReferenceVolumeContextDeleted) (deletedMap map[string]interface{}) { +func dataSourceVolumeCollectionVolumeAttachmentsDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -1117,7 +1117,7 @@ func dataSourceVolumeCollectionVolumeAttachmentsInstanceToMap(instanceItem vpcv1 return instanceMap } -func dataSourceVolumeCollectionInstanceDeletedToMap(deletedItem vpcv1.InstanceReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceVolumeCollectionInstanceDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_vpc.go b/ibm/service/vpc/data_source_ibm_is_vpc.go index 8122ec6f4a..1c8b8db382 100644 --- a/ibm/service/vpc/data_source_ibm_is_vpc.go +++ b/ibm/service/vpc/data_source_ibm_is_vpc.go @@ -978,7 +978,7 @@ func dataSourceIBMIsVPCVPCReferenceDnsResolverContextToMap(model *vpcv1.VPCRefer return modelMap, nil } -func dataSourceIBMIsVPCVPCReferenceDnsResolverContextDeletedToMap(model *vpcv1.VPCReferenceDnsResolverContextDeleted) (map[string]interface{}, error) { +func dataSourceIBMIsVPCVPCReferenceDnsResolverContextDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil diff --git a/ibm/service/vpc/data_source_ibm_is_vpc_routing_table.go b/ibm/service/vpc/data_source_ibm_is_vpc_routing_table.go index d80be4197a..30bd93f954 100644 --- a/ibm/service/vpc/data_source_ibm_is_vpc_routing_table.go +++ b/ibm/service/vpc/data_source_ibm_is_vpc_routing_table.go @@ -363,7 +363,7 @@ func dataSourceIBMIBMIsVPCRoutingTableRouteReferenceToMap(model *vpcv1.RouteRefe return modelMap, nil } -func dataSourceIBMIBMIsVPCRoutingTableRouteReferenceDeletedToMap(model *vpcv1.RouteReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIBMIsVPCRoutingTableRouteReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := map[string]interface{}{} if model.MoreInfo != nil { modelMap[rMoreInfo] = *model.MoreInfo @@ -395,7 +395,7 @@ func dataSourceIBMIBMIsVPCRoutingTableSubnetReferenceToMap(model *vpcv1.SubnetRe return modelMap, nil } -func dataSourceIBMIBMIsVPCRoutingTableSubnetReferenceDeletedToMap(model *vpcv1.SubnetReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIBMIsVPCRoutingTableSubnetReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := map[string]interface{}{} if model.MoreInfo != nil { modelMap[rMoreInfo] = *model.MoreInfo diff --git a/ibm/service/vpc/data_source_ibm_is_vpc_routing_table_route.go b/ibm/service/vpc/data_source_ibm_is_vpc_routing_table_route.go index da18a18571..0c487e86dd 100644 --- a/ibm/service/vpc/data_source_ibm_is_vpc_routing_table_route.go +++ b/ibm/service/vpc/data_source_ibm_is_vpc_routing_table_route.go @@ -390,7 +390,7 @@ func dataSourceIBMIBMIsVPCRoutingTableRouteRouteNextHopToMap(model vpcv1.RouteNe } } -func dataSourceIBMIBMIsVPCRoutingTableRouteVPNGatewayConnectionReferenceDeletedToMap(model *vpcv1.VPNGatewayConnectionReferenceDeleted) (map[string]interface{}, error) { +func dataSourceIBMIBMIsVPCRoutingTableRouteVPNGatewayConnectionReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := map[string]interface{}{} if model.MoreInfo != nil { modelMap[rMoreInfo] = *model.MoreInfo diff --git a/ibm/service/vpc/data_source_ibm_is_vpc_routing_table_routes.go b/ibm/service/vpc/data_source_ibm_is_vpc_routing_table_routes.go index 6e723e5db6..b54e85b0ed 100644 --- a/ibm/service/vpc/data_source_ibm_is_vpc_routing_table_routes.go +++ b/ibm/service/vpc/data_source_ibm_is_vpc_routing_table_routes.go @@ -354,7 +354,7 @@ func DataSourceIBMIsRouteCreatorVPNServerReferenceToMap(model *vpcv1.RouteCreato return modelMap, nil } -func DataSourceIBMIsRouteVPNGatewayReferenceDeletedToMap(model *vpcv1.VPNGatewayReferenceDeleted) (map[string]interface{}, error) { +func DataSourceIBMIsRouteVPNGatewayReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.MoreInfo != nil { modelMap["more_info"] = *model.MoreInfo @@ -362,7 +362,7 @@ func DataSourceIBMIsRouteVPNGatewayReferenceDeletedToMap(model *vpcv1.VPNGateway return modelMap, nil } -func DataSourceIBMIsRouteVPNServerReferenceDeletedToMap(model *vpcv1.VPNServerReferenceDeleted) (map[string]interface{}, error) { +func DataSourceIBMIsRouteVPNServerReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.MoreInfo != nil { modelMap["more_info"] = *model.MoreInfo diff --git a/ibm/service/vpc/data_source_ibm_is_vpn_gateway.go b/ibm/service/vpc/data_source_ibm_is_vpn_gateway.go index 9fb96fd3c8..be0f4ce1e7 100644 --- a/ibm/service/vpc/data_source_ibm_is_vpn_gateway.go +++ b/ibm/service/vpc/data_source_ibm_is_vpn_gateway.go @@ -493,7 +493,7 @@ func dataSourceVPNGatewayConnectionsToMap(connectionsItem vpcv1.VPNGatewayConnec return connectionsMap } -func dataSourceVPNGatewayConnectionsDeletedToMap(deletedItem vpcv1.VPNGatewayConnectionReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceVPNGatewayConnectionsDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -584,7 +584,7 @@ func dataSourceVPNGatewaySubnetToMap(subnetItem vpcv1.SubnetReference) (subnetMa return subnetMap } -func dataSourceVPNGatewaySubnetDeletedToMap(deletedItem vpcv1.SubnetReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceVPNGatewaySubnetDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -625,7 +625,7 @@ func dataSourceVPNGatewayVpcToMap(vpcItem vpcv1.VPCReference) (vpcsMap map[strin } -func dataSourceVPNGatewayVpcDeletedToMap(deletedItem vpcv1.VPCReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceVPNGatewayVpcDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_vpn_gateway_connection.go b/ibm/service/vpc/data_source_ibm_is_vpn_gateway_connection.go index bfdbd90d82..d45844768a 100644 --- a/ibm/service/vpc/data_source_ibm_is_vpn_gateway_connection.go +++ b/ibm/service/vpc/data_source_ibm_is_vpn_gateway_connection.go @@ -962,7 +962,7 @@ func dataSourceVPNGatewayConnectionIkePolicyToMap(ikePolicyItem vpcv1.IkePolicyR return ikePolicyMap } -func dataSourceVPNGatewayConnectionIkePolicyDeletedToMap(deletedItem vpcv1.IkePolicyReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceVPNGatewayConnectionIkePolicyDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -1005,7 +1005,7 @@ func dataSourceVPNGatewayConnectionIpsecPolicyToMap(ipsecPolicyItem vpcv1.IPsecP return ipsecPolicyMap } -func dataSourceVPNGatewayConnectionIpsecPolicyDeletedToMap(deletedItem vpcv1.IPsecPolicyReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceVPNGatewayConnectionIpsecPolicyDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_vpn_gateways.go b/ibm/service/vpc/data_source_ibm_is_vpn_gateways.go index 89c8bdde9f..7f1eea5eb5 100644 --- a/ibm/service/vpc/data_source_ibm_is_vpn_gateways.go +++ b/ibm/service/vpc/data_source_ibm_is_vpn_gateways.go @@ -359,7 +359,7 @@ func dataSourceVPNServerCollectionVPNGatewayVpcReferenceToMap(vpcsItem *vpcv1.VP return vpcsMap } -func dataSourceVPNGatewayCollectionVpcsDeletedToMap(deletedItem vpcv1.VPCReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceVPNGatewayCollectionVpcsDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_vpn_server.go b/ibm/service/vpc/data_source_ibm_is_vpn_server.go index 4595cb40ef..cb02d3091a 100644 --- a/ibm/service/vpc/data_source_ibm_is_vpn_server.go +++ b/ibm/service/vpc/data_source_ibm_is_vpn_server.go @@ -707,7 +707,7 @@ func dataSourceVPNServerPrivateIpsToMap(privateIpsItem vpcv1.ReservedIPReference return privateIpsMap } -func dataSourceVPNServerPrivateIpsDeletedToMap(deletedItem vpcv1.ReservedIPReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceVPNServerPrivateIpsDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -774,7 +774,7 @@ func dataSourceVPNServerSecurityGroupsToMap(securityGroupsItem vpcv1.SecurityGro return securityGroupsMap } -func dataSourceVPNServerSecurityGroupsDeletedToMap(deletedItem vpcv1.SecurityGroupReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceVPNServerSecurityGroupsDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -817,7 +817,7 @@ func dataSourceVPNServerSubnetsToMap(subnetsItem vpcv1.SubnetReference) (subnets return subnetsMap } -func dataSourceVPNServerSubnetsDeletedToMap(deletedItem vpcv1.SubnetReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceVPNServerSubnetsDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -857,7 +857,7 @@ func dataSourceVPNServerVpcToMap(vpcItem vpcv1.VPCReference) (vpcsMap map[string return vpcsMap } -func dataSourceVPNServerVpcsDeletedToMap(deletedItem vpcv1.VPCReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceVPNServerVpcsDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_vpn_servers.go b/ibm/service/vpc/data_source_ibm_is_vpn_servers.go index 06a4e29d92..0ba98e781f 100644 --- a/ibm/service/vpc/data_source_ibm_is_vpn_servers.go +++ b/ibm/service/vpc/data_source_ibm_is_vpn_servers.go @@ -733,7 +733,7 @@ func dataSourceVPNServerCollectionVPNServersPrivateIpsToMap(privateIpsItem vpcv1 return privateIpsMap } -func dataSourceVPNServerCollectionPrivateIpsDeletedToMap(deletedItem vpcv1.ReservedIPReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceVPNServerCollectionPrivateIpsDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -784,7 +784,7 @@ func dataSourceVPNServerCollectionVPNServersSecurityGroupsToMap(securityGroupsIt return securityGroupsMap } -func dataSourceVPNServerCollectionSecurityGroupsDeletedToMap(deletedItem vpcv1.SecurityGroupReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceVPNServerCollectionSecurityGroupsDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -822,7 +822,7 @@ func dataSourceVPNServerCollectionVPNServersSubnetsToMap(subnetsItem vpcv1.Subne return subnetsMap } -func dataSourceVPNServerCollectionSubnetsDeletedToMap(deletedItem vpcv1.SubnetReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceVPNServerCollectionSubnetsDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -861,7 +861,7 @@ func dataSourceVPNServerCollectionVPNServersVpcReferenceToMap(vpcsItem *vpcv1.VP return vpcsMap } -func dataSourceVPNServerCollectionVpcsDeletedToMap(deletedItem vpcv1.VPCReferenceDeleted) (deletedMap map[string]interface{}) { +func dataSourceVPNServerCollectionVpcsDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/data_source_ibm_is_zone.go b/ibm/service/vpc/data_source_ibm_is_zone.go index fe89424be4..cf72e45143 100644 --- a/ibm/service/vpc/data_source_ibm_is_zone.go +++ b/ibm/service/vpc/data_source_ibm_is_zone.go @@ -14,6 +14,9 @@ const ( isZoneName = "name" isZoneRegion = "region" isZoneStatus = "status" + + isZoneDataCenter = "data_center" + isZoneUniversalName = "universal_name" ) func DataSourceIBMISZone() *schema.Resource { @@ -36,6 +39,14 @@ func DataSourceIBMISZone() *schema.Resource { Type: schema.TypeString, Computed: true, }, + isZoneDataCenter: { + Type: schema.TypeString, + Computed: true, + }, + isZoneUniversalName: { + Type: schema.TypeString, + Computed: true, + }, }, } } @@ -65,5 +76,11 @@ func zoneGet(d *schema.ResourceData, meta interface{}, regionName, zoneName stri d.Set(isZoneName, *zone.Name) d.Set(isZoneRegion, *zone.Region.Name) d.Set(isZoneStatus, *zone.Status) + if zone.DataCenter != nil { + d.Set(isZoneDataCenter, *zone.DataCenter) + } + if zone.UniversalName != nil { + d.Set(isZoneUniversalName, *zone.UniversalName) + } return nil } diff --git a/ibm/service/vpc/data_source_ibm_is_zone_test.go b/ibm/service/vpc/data_source_ibm_is_zone_test.go index cf7823abe7..6c064551fc 100644 --- a/ibm/service/vpc/data_source_ibm_is_zone_test.go +++ b/ibm/service/vpc/data_source_ibm_is_zone_test.go @@ -23,6 +23,8 @@ func TestAccIBMISZoneDataSource_basic(t *testing.T) { Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.ibm_is_zone.testacc_ds_zone", "name", acc.ISZoneName), resource.TestCheckResourceAttr("data.ibm_is_zone.testacc_ds_zone", "region", acc.RegionName), + resource.TestCheckResourceAttr("data.ibm_is_zone.testacc_ds_zone", "data_center", "DAL10"), + resource.TestCheckResourceAttr("data.ibm_is_zone.testacc_ds_zone", "universal_name", "us-south-dal10-a"), ), }, }, diff --git a/ibm/service/vpc/data_source_ibm_is_zones.go b/ibm/service/vpc/data_source_ibm_is_zones.go index 0772cb4108..0ce5d842f5 100644 --- a/ibm/service/vpc/data_source_ibm_is_zones.go +++ b/ibm/service/vpc/data_source_ibm_is_zones.go @@ -12,6 +12,7 @@ import ( const ( isZoneNames = "zones" + isZonesInfo = "zone_info" ) func DataSourceIBMISZones() *schema.Resource { @@ -35,6 +36,31 @@ func DataSourceIBMISZones() *schema.Resource { Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, + isZonesInfo: { + Type: schema.TypeList, + Computed: true, + Description: "The zones information in the region", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + isZoneName: { + Type: schema.TypeString, + Computed: true, + }, + isZoneUniversalName: { + Type: schema.TypeString, + Computed: true, + }, + isZoneDataCenter: { + Type: schema.TypeString, + Computed: true, + }, + isZoneStatus: { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, }, } } @@ -59,13 +85,25 @@ func zonesList(d *schema.ResourceData, meta interface{}, regionName string) erro } names := make([]string, 0) status := d.Get(isZoneStatus).(string) + zonesList := make([]map[string]interface{}, 0) for _, zone := range availableZones.Zones { + zoneInfo := map[string]interface{}{} if status == "" || *zone.Status == status { names = append(names, *zone.Name) + zoneInfo[isZoneName] = *zone.Name + zoneInfo[isZoneStatus] = *zone.Status + if zone.DataCenter != nil { + zoneInfo[isZoneDataCenter] = *zone.DataCenter + } + if zone.UniversalName != nil { + zoneInfo[isZoneUniversalName] = *zone.UniversalName + } } + zonesList = append(zonesList, zoneInfo) } d.SetId(dataSourceIBMISZonesId(d)) d.Set(isZoneNames, names) + d.Set(isZonesInfo, zonesList) return nil } diff --git a/ibm/service/vpc/resource_ibm_is_bare_metal_server.go b/ibm/service/vpc/resource_ibm_is_bare_metal_server.go index f0e3502abd..766496bdf0 100644 --- a/ibm/service/vpc/resource_ibm_is_bare_metal_server.go +++ b/ibm/service/vpc/resource_ibm_is_bare_metal_server.go @@ -4246,7 +4246,7 @@ func resourceIBMIsBareMetalServerBareMetalServerNetworkAttachmentReferenceToMap( return modelMap, nil } -func resourceIBMIsBareMetalServerBareMetalServerNetworkAttachmentReferenceDeletedToMap(model *vpcv1.BareMetalServerNetworkAttachmentReferenceDeleted) (map[string]interface{}, error) { +func resourceIBMIsBareMetalServerBareMetalServerNetworkAttachmentReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil @@ -4269,7 +4269,7 @@ func resourceIBMIsBareMetalServerReservedIPReferenceToMap(model *vpcv1.ReservedI return modelMap, nil } -func resourceIBMIsBareMetalServerReservedIPReferenceDeletedToMap(model *vpcv1.ReservedIPReferenceDeleted) (map[string]interface{}, error) { +func resourceIBMIsBareMetalServerReservedIPReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil diff --git a/ibm/service/vpc/resource_ibm_is_dedicated_host.go b/ibm/service/vpc/resource_ibm_is_dedicated_host.go index 09d1fec740..5a94188c04 100644 --- a/ibm/service/vpc/resource_ibm_is_dedicated_host.go +++ b/ibm/service/vpc/resource_ibm_is_dedicated_host.go @@ -635,7 +635,7 @@ func resourceIbmIsDedicatedHostInstanceReferenceToMap(instanceReference vpcv1.In return instanceReferenceMap } -func resourceIbmIsDedicatedHostInstanceReferenceDeletedToMap(instanceReferenceDeleted vpcv1.InstanceReferenceDeleted) map[string]interface{} { +func resourceIbmIsDedicatedHostInstanceReferenceDeletedToMap(instanceReferenceDeleted vpcv1.Deleted) map[string]interface{} { instanceReferenceDeletedMap := map[string]interface{}{} instanceReferenceDeletedMap["more_info"] = instanceReferenceDeleted.MoreInfo @@ -866,7 +866,7 @@ func resourceIbmIsDedicatedHostInstanceDiskReferenceToMap(instanceDiskReference return instanceDiskReferenceMap } -func resourceIbmIsDedicatedHostInstanceDiskReferenceDeletedToMap(instanceDiskReferenceDeleted vpcv1.InstanceDiskReferenceDeleted) map[string]interface{} { +func resourceIbmIsDedicatedHostInstanceDiskReferenceDeletedToMap(instanceDiskReferenceDeleted vpcv1.Deleted) map[string]interface{} { instanceDiskReferenceDeletedMap := map[string]interface{}{} instanceDiskReferenceDeletedMap["more_info"] = instanceDiskReferenceDeleted.MoreInfo diff --git a/ibm/service/vpc/resource_ibm_is_dedicated_host_group.go b/ibm/service/vpc/resource_ibm_is_dedicated_host_group.go index 5c769a973e..bfb0974e44 100644 --- a/ibm/service/vpc/resource_ibm_is_dedicated_host_group.go +++ b/ibm/service/vpc/resource_ibm_is_dedicated_host_group.go @@ -366,7 +366,7 @@ func resourceIbmIsDedicatedHostGroupDedicatedHostReferenceToMap(dedicatedHostRef return dedicatedHostReferenceMap } -func resourceIbmIsDedicatedHostGroupDedicatedHostReferenceDeletedToMap(dedicatedHostReferenceDeleted vpcv1.DedicatedHostReferenceDeleted) map[string]interface{} { +func resourceIbmIsDedicatedHostGroupDedicatedHostReferenceDeletedToMap(dedicatedHostReferenceDeleted vpcv1.Deleted) map[string]interface{} { dedicatedHostReferenceDeletedMap := map[string]interface{}{} dedicatedHostReferenceDeletedMap["more_info"] = dedicatedHostReferenceDeleted.MoreInfo diff --git a/ibm/service/vpc/resource_ibm_is_floating_ip.go b/ibm/service/vpc/resource_ibm_is_floating_ip.go index cbed74338c..b4adf1f0d2 100644 --- a/ibm/service/vpc/resource_ibm_is_floating_ip.go +++ b/ibm/service/vpc/resource_ibm_is_floating_ip.go @@ -850,7 +850,7 @@ func floatingIPCollectionFloatingIpTargetToMap(targetItemIntf vpcv1.FloatingIPTa return targetId, targetMap } -func floatingIPTargetNicDeletedToMap(deletedItem vpcv1.NetworkInterfaceReferenceDeleted) (deletedMap map[string]interface{}) { +func floatingIPTargetNicDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { @@ -859,7 +859,7 @@ func floatingIPTargetNicDeletedToMap(deletedItem vpcv1.NetworkInterfaceReference return deletedMap } -func floatingIPTargetPgDeletedToMap(deletedItem vpcv1.PublicGatewayReferenceDeleted) (deletedMap map[string]interface{}) { +func floatingIPTargetPgDeletedToMap(deletedItem vpcv1.Deleted) (deletedMap map[string]interface{}) { deletedMap = map[string]interface{}{} if deletedItem.MoreInfo != nil { diff --git a/ibm/service/vpc/resource_ibm_is_instance.go b/ibm/service/vpc/resource_ibm_is_instance.go index 3260ddc76a..fe23b877e1 100644 --- a/ibm/service/vpc/resource_ibm_is_instance.go +++ b/ibm/service/vpc/resource_ibm_is_instance.go @@ -6325,7 +6325,7 @@ func resourceIbmIsInstanceReservationAffinityPoolToMap(reservationPool vpcv1.Res return resAffPoolMap } -func resourceIbmIsInstanceDedicatedHostGroupReferenceDeletedToMap(dedicatedHostGroupReferenceDeleted vpcv1.DedicatedHostGroupReferenceDeleted) map[string]interface{} { +func resourceIbmIsInstanceDedicatedHostGroupReferenceDeletedToMap(dedicatedHostGroupReferenceDeleted vpcv1.Deleted) map[string]interface{} { dedicatedHostGroupReferenceDeletedMap := map[string]interface{}{} dedicatedHostGroupReferenceDeletedMap["more_info"] = dedicatedHostGroupReferenceDeleted.MoreInfo @@ -6434,7 +6434,7 @@ func resourceIBMIsInstanceInstanceNetworkAttachmentReferenceToMap(model *vpcv1.I return modelMap, nil } -func resourceIBMIsInstanceInstanceNetworkAttachmentReferenceDeletedToMap(model *vpcv1.InstanceNetworkAttachmentReferenceDeleted) (map[string]interface{}, error) { +func resourceIBMIsInstanceInstanceNetworkAttachmentReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil @@ -6460,7 +6460,7 @@ func resourceIBMIsInstanceReservedIPReferenceToMap(model *vpcv1.ReservedIPRefere return modelMap, nil } -func resourceIBMIsInstanceReservedIPReferenceDeletedToMap(model *vpcv1.ReservedIPReferenceDeleted) (map[string]interface{}, error) { +func resourceIBMIsInstanceReservedIPReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil diff --git a/ibm/service/vpc/resource_ibm_is_instance_network_attachment.go b/ibm/service/vpc/resource_ibm_is_instance_network_attachment.go index 5cfdcd1403..a0f76e2833 100644 --- a/ibm/service/vpc/resource_ibm_is_instance_network_attachment.go +++ b/ibm/service/vpc/resource_ibm_is_instance_network_attachment.go @@ -982,7 +982,7 @@ func resourceIBMIsInstanceNetworkAttachmentReservedIPReferenceToMap(model *vpcv1 return modelMap, nil } -func resourceIBMIsInstanceNetworkAttachmentReservedIPReferenceDeletedToMap(model *vpcv1.ReservedIPReferenceDeleted) (map[string]interface{}, error) { +func resourceIBMIsInstanceNetworkAttachmentReservedIPReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil @@ -1005,7 +1005,7 @@ func resourceIBMIsInstanceNetworkAttachmentSubnetReferenceToMap(model *vpcv1.Sub return modelMap, nil } -func resourceIBMIsInstanceNetworkAttachmentSubnetReferenceDeletedToMap(model *vpcv1.SubnetReferenceDeleted) (map[string]interface{}, error) { +func resourceIBMIsInstanceNetworkAttachmentSubnetReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil diff --git a/ibm/service/vpc/resource_ibm_is_instance_network_interface.go b/ibm/service/vpc/resource_ibm_is_instance_network_interface.go index 053a474f82..a6fc8256af 100644 --- a/ibm/service/vpc/resource_ibm_is_instance_network_interface.go +++ b/ibm/service/vpc/resource_ibm_is_instance_network_interface.go @@ -514,7 +514,7 @@ func resourceIBMIsInstanceNetworkInterfaceFloatingIPReferenceToMap(floatingIPRef return floatingIPReferenceMap } -func resourceIBMIsInstanceNetworkInterfaceFloatingIPReferenceDeletedToMap(floatingIPReferenceDeleted vpcv1.FloatingIPReferenceDeleted) map[string]interface{} { +func resourceIBMIsInstanceNetworkInterfaceFloatingIPReferenceDeletedToMap(floatingIPReferenceDeleted vpcv1.Deleted) map[string]interface{} { floatingIPReferenceDeletedMap := map[string]interface{}{} floatingIPReferenceDeletedMap["more_info"] = floatingIPReferenceDeleted.MoreInfo diff --git a/ibm/service/vpc/resource_ibm_is_lb_listener.go b/ibm/service/vpc/resource_ibm_is_lb_listener.go index 667c382d6c..889811dacd 100644 --- a/ibm/service/vpc/resource_ibm_is_lb_listener.go +++ b/ibm/service/vpc/resource_ibm_is_lb_listener.go @@ -939,7 +939,7 @@ func resourceIBMIsLbListenerLoadBalancerListenerReferenceToMap(model *vpcv1.Load modelMap["id"] = model.ID return modelMap, nil } -func resourceIBMIsLbListenerLoadBalancerListenerReferenceDeletedToMap(model *vpcv1.LoadBalancerListenerReferenceDeleted) (map[string]interface{}, error) { +func resourceIBMIsLbListenerLoadBalancerListenerReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil diff --git a/ibm/service/vpc/resource_ibm_is_lb_listener_policy.go b/ibm/service/vpc/resource_ibm_is_lb_listener_policy.go index 5c5ba0da2f..8e11b8d777 100644 --- a/ibm/service/vpc/resource_ibm_is_lb_listener_policy.go +++ b/ibm/service/vpc/resource_ibm_is_lb_listener_policy.go @@ -1223,7 +1223,7 @@ func resourceIBMIsLbListenerPolicyLoadBalancerListenerPolicyTargetToMap(model vp } } -func resourceIBMIsLbListenerPolicyLoadBalancerPoolReferenceDeletedToMap(model *vpcv1.LoadBalancerPoolReferenceDeleted) (map[string]interface{}, error) { +func resourceIBMIsLbListenerPolicyLoadBalancerPoolReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil @@ -1243,7 +1243,7 @@ func resourceIBMIsLbListenerPolicyLoadBalancerListenerReferenceToMap(model *vpcv return modelMap, nil } -func resourceIBMIsLbListenerPolicyLoadBalancerListenerReferenceDeletedToMap(model *vpcv1.LoadBalancerListenerReferenceDeleted) (map[string]interface{}, error) { +func resourceIBMIsLbListenerPolicyLoadBalancerListenerReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil diff --git a/ibm/service/vpc/resource_ibm_is_lb_pool_member.go b/ibm/service/vpc/resource_ibm_is_lb_pool_member.go index 02d1edf43b..cde8f6c29b 100644 --- a/ibm/service/vpc/resource_ibm_is_lb_pool_member.go +++ b/ibm/service/vpc/resource_ibm_is_lb_pool_member.go @@ -333,7 +333,9 @@ func lbpmemberGet(d *schema.ResourceData, meta interface{}, lbID, lbPoolID, lbPo if target.ID != nil { d.Set(isLBPoolMemberTargetID, *target.ID) } - d.Set(isLBPoolMemberWeight, *lbPoolMem.Weight) + if lbPoolMem.Weight != nil { + d.Set(isLBPoolMemberWeight, *lbPoolMem.Weight) + } d.Set(isLBPoolMemberProvisioningStatus, *lbPoolMem.ProvisioningStatus) d.Set(isLBPoolMemberHealth, *lbPoolMem.Health) d.Set(isLBPoolMemberHref, *lbPoolMem.Href) diff --git a/ibm/service/vpc/resource_ibm_is_share.go b/ibm/service/vpc/resource_ibm_is_share.go index e48458c171..219185463c 100644 --- a/ibm/service/vpc/resource_ibm_is_share.go +++ b/ibm/service/vpc/resource_ibm_is_share.go @@ -1096,23 +1096,24 @@ func resourceIbmIsShareCreate(context context.Context, d *schema.ResourceData, m sharePrototype.SourceShare = &vpcv1.ShareIdentity{ ID: &sourceShare, } - } else { - sourceShareCRN := d.Get("source_share_crn").(string) - if sourceShareCRN != "" { - sharePrototype.SourceShare = &vpcv1.ShareIdentity{ - CRN: &sourceShareCRN, - } + } + replicationCronSpec := d.Get("replication_cron_spec").(string) + sharePrototype.ReplicationCronSpec = &replicationCronSpec + } else if sourceShareCrnIntf, sShareCrnok := d.GetOk("source_share_crn"); sShareCrnok { + sourceShareCRN := sourceShareCrnIntf.(string) + if sourceShareCRN != "" { + sharePrototype.SourceShare = &vpcv1.ShareIdentity{ + CRN: &sourceShareCRN, } } - replicationCronSpec := d.Get("replication_cron_spec").(string) sharePrototype.ReplicationCronSpec = &replicationCronSpec } else { originShare := d.Get("origin_share") - OriginShareModel := ResourceIBMIsShareMapToShareIdentity(originShare.([]interface{})[0].(map[string]interface{})) - - sharePrototype.OriginShare = OriginShareModel - + if len(originShare.([]interface{})) > 0 { + OriginShareModel := ResourceIBMIsShareMapToShareIdentity(originShare.([]interface{})[0].(map[string]interface{})) + sharePrototype.OriginShare = OriginShareModel + } } if iopsIntf, ok := d.GetOk("iops"); ok { @@ -2204,7 +2205,7 @@ func ResourceIBMIsShareRegionReferenceToMap(model *vpcv1.RegionReference) map[st modelMap["name"] = *model.Name return modelMap } -func ResourceIBMIsShareShareReferenceDeletedToMap(model *vpcv1.ShareReferenceDeleted) map[string]interface{} { +func ResourceIBMIsShareShareReferenceDeletedToMap(model *vpcv1.Deleted) map[string]interface{} { modelMap := make(map[string]interface{}) modelMap["more_info"] = *model.MoreInfo return modelMap diff --git a/ibm/service/vpc/resource_ibm_is_share_test.go b/ibm/service/vpc/resource_ibm_is_share_test.go index a9f5ce9eb2..e3f0b678cf 100644 --- a/ibm/service/vpc/resource_ibm_is_share_test.go +++ b/ibm/service/vpc/resource_ibm_is_share_test.go @@ -137,6 +137,32 @@ func TestAccIbmIsShareAllArgs(t *testing.T) { }, }) } +func TestAccIbmIsShareAllArgs_EmptyCheck(t *testing.T) { + var conf vpcv1.Share + + name := fmt.Sprintf("tf-fs-name-%d", acctest.RandIntRange(10, 100)) + name2 := fmt.Sprintf("tf-fs-name2-%d", acctest.RandIntRange(10, 100)) + name3 := fmt.Sprintf("tf-fs-name3-%d", acctest.RandIntRange(10, 100)) + name4 := fmt.Sprintf("tf-fs-name4-%d", acctest.RandIntRange(10, 100)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + CheckDestroy: testAccCheckIbmIsShareDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckIbmIsShareAllConfigEmptyCheckConfig(name, name2, name3, name4), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckIbmIsShareExists("ibm_is_share.test-share", conf), + resource.TestCheckResourceAttr("ibm_is_share.test-share", "name", name), + resource.TestCheckResourceAttr("ibm_is_share.test-share2", "name", name2), + resource.TestCheckResourceAttr("ibm_is_share.test-share-replica", "name", name3), + resource.TestCheckResourceAttr("ibm_is_share.test-share2-replica-crn", "name", name4), + ), + }, + }, + }) +} func TestAccIbmIsShareReplicaMain(t *testing.T) { var conf vpcv1.Share @@ -432,6 +458,37 @@ func testAccCheckIbmIsShareConfig(vpcName, name string, size int, shareTergetNam } `, vpcName, name, acc.ShareProfileName, size, shareTergetName) } +func testAccCheckIbmIsShareAllConfigEmptyCheckConfig(sharename1, sharename2, sharename3, sharename4 string) string { + return fmt.Sprintf(` + + resource "ibm_is_share" "test-share" { + name = "%s" + size = 200 + profile = "%s" + zone = "%s" + } + resource "ibm_is_share" "test-share2" { + name = "%s" + size = 200 + profile = "%s" + zone = "%s" + } + resource "ibm_is_share" "test-share-replica" { + name = "%s" + profile = "%s" + zone = "%s" + source_share = ibm_is_share.test-share.id + replication_cron_spec = "0 */6 * * *" + } + resource "ibm_is_share" "test-share2-replica-crn" { + name = "%s" + profile = "%s" + zone = "%s" + source_share_crn = ibm_is_share.test-share2.crn + replication_cron_spec = "0 */5 * * *" + } + `, sharename1, acc.ShareProfileName, acc.ISZoneName, sharename2, acc.ShareProfileName, acc.ISZoneName, sharename3, acc.ShareProfileName, acc.ISZoneName2, sharename4, acc.ShareProfileName, acc.ISZoneName3) +} func testAccCheckIbmIsShareConfigReplica(vpcName, vpcName1, name string, size int, shareTergetName, shareTergetName1, replicaName string) string { return fmt.Sprintf(` diff --git a/ibm/service/vpc/resource_ibm_is_snapshot_consistency_group.go b/ibm/service/vpc/resource_ibm_is_snapshot_consistency_group.go index b7c38774e4..432f3ac224 100644 --- a/ibm/service/vpc/resource_ibm_is_snapshot_consistency_group.go +++ b/ibm/service/vpc/resource_ibm_is_snapshot_consistency_group.go @@ -746,7 +746,7 @@ func resourceIBMIsSnapshotConsistencyGroupSnapshotConsistencyGroupSnapshotsItemT return modelMap, nil } -func resourceIBMIsSnapshotConsistencyGroupSnapshotReferenceDeletedToMap(model *vpcv1.SnapshotReferenceDeleted) (map[string]interface{}, error) { +func resourceIBMIsSnapshotConsistencyGroupSnapshotReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) if model.MoreInfo != nil { modelMap["more_info"] = model.MoreInfo @@ -796,7 +796,7 @@ func resourceIBMIsSnapshotConsistencyGroupBackupPolicyPlanReferenceToMap(model * return modelMap, nil } -func resourceIBMIsSnapshotConsistencyGroupBackupPolicyPlanReferenceDeletedToMap(model *vpcv1.BackupPolicyPlanReferenceDeleted) (map[string]interface{}, error) { +func resourceIBMIsSnapshotConsistencyGroupBackupPolicyPlanReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil diff --git a/ibm/service/vpc/resource_ibm_is_subnet_reserved_ip_patch.go b/ibm/service/vpc/resource_ibm_is_subnet_reserved_ip_patch.go new file mode 100644 index 0000000000..1a6be955ed --- /dev/null +++ b/ibm/service/vpc/resource_ibm_is_subnet_reserved_ip_patch.go @@ -0,0 +1,279 @@ +// Copyright IBM Corp. 2017, 2021 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package vpc + +import ( + "fmt" + "reflect" + "time" + + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate" + "github.com/IBM/go-sdk-core/v5/core" + "github.com/IBM/vpc-go-sdk/vpcv1" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func ResourceIBMISReservedIPPatch() *schema.Resource { + return &schema.Resource{ + Create: resourceIBMISReservedIPPatchCreate, + Read: resourceIBMISReservedIPPatchRead, + Update: resourceIBMISReservedIPPatchUpdate, + Delete: resourceIBMISReservedIPPatchDelete, + Exists: resourceIBMISReservedIPPatchExists, + Importer: &schema.ResourceImporter{}, + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(10 * time.Minute), + Delete: schema.DefaultTimeout(10 * time.Minute), + }, + Schema: map[string]*schema.Schema{ + /* + Request Parameters + ================== + These are mandatory req parameters + */ + isSubNetID: { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: "The subnet identifier.", + }, + isReservedIPAutoDelete: { + Type: schema.TypeBool, + Default: nil, + AtLeastOneOf: []string{isReservedIPAutoDelete, isReservedIPName}, + Computed: true, + Optional: true, + Description: "If set to true, this reserved IP will be automatically deleted", + }, + isReservedIPName: { + Type: schema.TypeString, + Optional: true, + AtLeastOneOf: []string{isReservedIPAutoDelete, isReservedIPName}, + Computed: true, + ValidateFunc: validate.InvokeValidator("ibm_is_subnet_reserved_ip", isReservedIPName), + Description: "The user-defined or system-provided name for this reserved IP.", + }, + isReservedIPTarget: { + Type: schema.TypeString, + Computed: true, + Optional: true, + Description: "The unique identifier for target.", + }, + isReservedIPTargetCrn: { + Type: schema.TypeString, + Computed: true, + Optional: true, + Description: "The crn for target.", + }, + isReservedIPLifecycleState: { + Type: schema.TypeString, + Computed: true, + Description: "The lifecycle state of the reserved IP", + }, + isReservedIPAddress: { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Computed: true, + Description: "The address for this reserved IP.", + }, + isReservedIP: { + Type: schema.TypeString, + Required: true, + Description: "The unique identifier of the reserved IP.", + }, + isReservedIPCreatedAt: { + Type: schema.TypeString, + Computed: true, + Description: "The date and time that the reserved IP was created.", + }, + isReservedIPhref: { + Type: schema.TypeString, + Computed: true, + Description: "The URL for this reserved IP.", + }, + isReservedIPOwner: { + Type: schema.TypeString, + Computed: true, + Description: "The owner of a reserved IP, defining whether it is managed by the user or the provider.", + }, + isReservedIPType: { + Type: schema.TypeString, + Computed: true, + Description: "The resource type.", + }, + }, + } +} + +// resourceIBMISReservedIPCreate Creates a reserved IP given a subnet ID +func resourceIBMISReservedIPPatchCreate(d *schema.ResourceData, meta interface{}) error { + sess, err := vpcClient(meta) + if err != nil { + return err + } + + subnetID := d.Get(isSubNetID).(string) + reservedIPID := d.Get(isReservedIP).(string) + name := d.Get(isReservedIPName).(string) + reservedIPPatchModel := &vpcv1.ReservedIPPatch{} + if name != "" { + reservedIPPatchModel.Name = &name + } + if autoDeleteBoolOk, ok := d.GetOkExists(isReservedIPAutoDelete); ok { + autoDeleteBool := autoDeleteBoolOk.(bool) + reservedIPPatchModel.AutoDelete = &autoDeleteBool + } + reservedIPPatch, err := reservedIPPatchModel.AsPatch() + if err != nil { + return fmt.Errorf("[ERROR] Error updating the reserved IP %s", err) + } + + options := sess.NewUpdateSubnetReservedIPOptions(subnetID, reservedIPID, reservedIPPatch) + + rip, response, err := sess.UpdateSubnetReservedIP(options) + if err != nil || response == nil || rip == nil { + return fmt.Errorf("[ERROR] Error updating the reserved ip patch: %s\n%s", err, response) + } + + // Set id for the reserved IP as combination of subnet ID and reserved IP ID + d.SetId(fmt.Sprintf("%s/%s", subnetID, *rip.ID)) + return resourceIBMISReservedIPPatchRead(d, meta) +} + +func resourceIBMISReservedIPPatchRead(d *schema.ResourceData, meta interface{}) error { + rip, err := get(d, meta) + if err != nil { + return err + } + + allIDs, err := flex.IdParts(d.Id()) + if err != nil { + return fmt.Errorf("[ERROR] The ID can not be split into subnet ID and reserved IP ID in patch. %s", err) + } + subnetID := allIDs[0] + + if rip != nil { + d.Set(isReservedIPAddress, *rip.Address) + d.Set(isReservedIP, *rip.ID) + d.Set(isSubNetID, subnetID) + if rip.LifecycleState != nil { + d.Set(isReservedIPLifecycleState, *rip.LifecycleState) + } + d.Set(isReservedIPAutoDelete, *rip.AutoDelete) + d.Set(isReservedIPCreatedAt, (*rip.CreatedAt).String()) + d.Set(isReservedIPhref, *rip.Href) + d.Set(isReservedIPName, *rip.Name) + d.Set(isReservedIPOwner, *rip.Owner) + d.Set(isReservedIPType, *rip.ResourceType) + if rip.Target != nil { + targetIntf := rip.Target + switch reflect.TypeOf(targetIntf).String() { + case "*vpcv1.ReservedIPTargetEndpointGatewayReference": + { + target := targetIntf.(*vpcv1.ReservedIPTargetEndpointGatewayReference) + d.Set(isReservedIPTarget, target.ID) + d.Set(isReservedIPTargetCrn, target.CRN) + } + case "*vpcv1.ReservedIPTargetGenericResourceReference": + { + target := targetIntf.(*vpcv1.ReservedIPTargetGenericResourceReference) + d.Set(isReservedIPTargetCrn, target.CRN) + } + case "*vpcv1.ReservedIPTargetNetworkInterfaceReferenceTargetContext": + { + target := targetIntf.(*vpcv1.ReservedIPTargetNetworkInterfaceReferenceTargetContext) + d.Set(isReservedIPTarget, target.ID) + } + case "*vpcv1.ReservedIPTargetLoadBalancerReference": + { + target := targetIntf.(*vpcv1.ReservedIPTargetLoadBalancerReference) + d.Set(isReservedIPTarget, target.ID) + d.Set(isReservedIPTargetCrn, target.CRN) + } + case "*vpcv1.ReservedIPTargetVPNGatewayReference": + { + target := targetIntf.(*vpcv1.ReservedIPTargetVPNGatewayReference) + d.Set(isReservedIPTarget, target.ID) + d.Set(isReservedIPTargetCrn, target.CRN) + } + case "*vpcv1.ReservedIPTarget": + { + target := targetIntf.(*vpcv1.ReservedIPTarget) + d.Set(isReservedIPTarget, target.ID) + d.Set(isReservedIPTargetCrn, target.CRN) + } + } + } + } + return nil +} + +func resourceIBMISReservedIPPatchUpdate(d *schema.ResourceData, meta interface{}) error { + + // For updating the name + nameChanged := d.HasChange(isReservedIPName) + autoDeleteChanged := d.HasChange(isReservedIPAutoDelete) + + if nameChanged || autoDeleteChanged { + sess, err := vpcClient(meta) + if err != nil { + return err + } + + allIDs, err := flex.IdParts(d.Id()) + if err != nil { + return err + } + subnetID := allIDs[0] + reservedIPID := allIDs[1] + + options := &vpcv1.UpdateSubnetReservedIPOptions{ + SubnetID: &subnetID, + ID: &reservedIPID, + } + + patch := new(vpcv1.ReservedIPPatch) + + if nameChanged { + name := d.Get(isReservedIPName).(string) + patch.Name = core.StringPtr(name) + } + + if autoDeleteChanged { + autoDelete := d.Get(isReservedIPAutoDelete).(bool) + patch.AutoDelete = core.BoolPtr(autoDelete) + } + + reservedIPPatch, err := patch.AsPatch() + if err != nil { + return fmt.Errorf("[ERROR] Error updating the reserved IP %s", err) + } + + options.ReservedIPPatch = reservedIPPatch + + _, response, err := sess.UpdateSubnetReservedIP(options) + if err != nil { + return fmt.Errorf("[ERROR] Error updating the reserved ip patch %s\n%s", err, response) + } + } + return resourceIBMISReservedIPPatchRead(d, meta) +} + +func resourceIBMISReservedIPPatchDelete(d *schema.ResourceData, meta interface{}) error { + d.SetId("") + return nil +} + +func resourceIBMISReservedIPPatchExists(d *schema.ResourceData, meta interface{}) (bool, error) { + rip, err := get(d, meta) + if err != nil { + return false, err + } + if err == nil && rip == nil { + return false, nil + } + return true, nil +} diff --git a/ibm/service/vpc/resource_ibm_is_subnet_reserved_ip_patch_test.go b/ibm/service/vpc/resource_ibm_is_subnet_reserved_ip_patch_test.go new file mode 100644 index 0000000000..3819662017 --- /dev/null +++ b/ibm/service/vpc/resource_ibm_is_subnet_reserved_ip_patch_test.go @@ -0,0 +1,138 @@ +// Copyright IBM Corp. 2017, 2021 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package vpc_test + +import ( + "fmt" + "testing" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +func TestAccIBMISSubnetReservedIPPatchResource_basic(t *testing.T) { + var reservedIPID string + vpcName := fmt.Sprintf("tfresip-vpc-%d", acctest.RandIntRange(10, 100)) + vniName := fmt.Sprintf("tfresip-vni-%d", acctest.RandIntRange(10, 100)) + subnetName := fmt.Sprintf("tfresip-subnet-%d", acctest.RandIntRange(10, 100)) + reservedIPName := fmt.Sprintf("tfresip-reservedip-%d", acctest.RandIntRange(10, 100)) + reservedIPName3 := fmt.Sprintf("tfresip-reservedip-%d", acctest.RandIntRange(10, 100)) + terraformTag1 := "ibm_is_subnet_reserved_ip_patch.resIP1" + terraformTag2 := "ibm_is_subnet_reserved_ip_patch.resIP2" + terraformTag3 := "ibm_is_subnet_reserved_ip_patch.resIP3" + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + { + // Tests create + Config: testAccCheckISSubnetReservedIPPatchConfigBasic(vpcName, subnetName, vniName, reservedIPName, reservedIPName3), + Check: resource.ComposeTestCheckFunc( + testAccCheckISSubnetReservedIPPatchExists(terraformTag1, &reservedIPID), + testAccCheckISSubnetReservedIPPatchExists(terraformTag2, &reservedIPID), + testAccCheckISSubnetReservedIPPatchExists(terraformTag3, &reservedIPID), + resource.TestCheckResourceAttrSet(terraformTag1, "name"), + resource.TestCheckResourceAttrSet(terraformTag2, "name"), + resource.TestCheckResourceAttrSet(terraformTag3, "name"), + resource.TestCheckResourceAttr(terraformTag1, "name", reservedIPName), + resource.TestCheckResourceAttr(terraformTag1, "auto_delete", "true"), + resource.TestCheckResourceAttr(terraformTag2, "auto_delete", "false"), + resource.TestCheckResourceAttr(terraformTag3, "name", reservedIPName3), + ), + }, + }, + }) +} + +func testAccCheckISSubnetReservedIPPatchExists(resIPName string, reservedIPID *string) resource.TestCheckFunc { + return func(s *terraform.State) error { + + rs, ok := s.RootModule().Resources[resIPName] + if !ok { + return fmt.Errorf("Not Found (reserved IP patch): %s", resIPName) + } + if rs.Primary.ID == "" { + return fmt.Errorf("[ERROR] No reserved IP ID is set") + } + + sess, err := acc.TestAccProvider.Meta().(conns.ClientSession).VpcV1API() + if err != nil { + return err + } + parts, err := flex.IdParts(rs.Primary.ID) + if err != nil { + return err + } + opt := sess.NewGetSubnetReservedIPOptions(parts[0], parts[1]) + result, response, err := sess.GetSubnetReservedIP(opt) + if err != nil { + return fmt.Errorf("Reserved IP does not exist: %s", response) + } + *reservedIPID = *result.ID + return nil + } +} + +func testAccCheckISSubnetReservedIPPatchConfigBasic(vpcName, subnetName, vniname, resIPName1, resIPName2 string) string { + return fmt.Sprintf(` + resource "ibm_is_vpc" "vpc1" { + name = "%s" + } + + resource "ibm_is_subnet" "subnet1" { + name = "%s" + vpc = ibm_is_vpc.vpc1.id + zone = "us-south-1" + total_ipv4_address_count = 256 + } + + resource "ibm_is_virtual_endpoint_gateway" "endpoint_gateway" { + name = "my-endpoint-gateway-1" + target { + name = "ibm-ntp-server" + resource_type = "provider_infrastructure_service" + } + vpc = ibm_is_vpc.vpc1.id + } + resource "ibm_is_virtual_network_interface" "testacc_vni"{ + name = "%s" + subnet = ibm_is_subnet.subnet1.id + } + resource "ibm_is_subnet_reserved_ip" "resIP1" { + subnet = ibm_is_subnet.subnet1.id + target = ibm_is_virtual_endpoint_gateway.endpoint_gateway.id + } + resource "ibm_is_subnet_reserved_ip" "resIP2" { + subnet = ibm_is_subnet.subnet1.id + } + resource "ibm_is_virtual_network_interface_ip" "testacc_vni_reservedip" { + virtual_network_interface = ibm_is_virtual_network_interface.testacc_vni.id + reserved_ip = ibm_is_subnet_reserved_ip.resIP2.reserved_ip + } + resource "ibm_is_subnet_reserved_ip" "resIP3" { + subnet = ibm_is_subnet.subnet1.id + } + resource "ibm_is_subnet_reserved_ip_patch" "resIP1" { + subnet = ibm_is_subnet.subnet1.id + name = "%s" + auto_delete = true + reserved_ip = ibm_is_subnet_reserved_ip.resIP1.reserved_ip + } + resource "ibm_is_subnet_reserved_ip_patch" "resIP2" { + subnet = ibm_is_subnet.subnet1.id + auto_delete = false + reserved_ip = ibm_is_subnet_reserved_ip.resIP2.reserved_ip + } + resource "ibm_is_subnet_reserved_ip_patch" "resIP3" { + subnet = ibm_is_subnet.subnet1.id + name = "%s" + reserved_ip = ibm_is_subnet_reserved_ip.resIP3.reserved_ip + } + `, vpcName, subnetName, vniname, resIPName1, resIPName2) +} diff --git a/ibm/service/vpc/resource_ibm_is_virtual_network_interface.go b/ibm/service/vpc/resource_ibm_is_virtual_network_interface.go index b860dd2180..afa651f220 100644 --- a/ibm/service/vpc/resource_ibm_is_virtual_network_interface.go +++ b/ibm/service/vpc/resource_ibm_is_virtual_network_interface.go @@ -996,7 +996,7 @@ func resourceIBMIsVirtualNetworkInterfaceReservedIPReferenceToMap(model *vpcv1.R return modelMap, nil } -func resourceIBMIsVirtualNetworkInterfaceReservedIPReferenceDeletedToMap(model *vpcv1.ReservedIPReferenceDeleted) (map[string]interface{}, error) { +func resourceIBMIsVirtualNetworkInterfaceReservedIPReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil @@ -1018,7 +1018,7 @@ func resourceIBMIsVirtualNetworkInterfaceSecurityGroupReferenceToMap(model *vpcv return modelMap, nil } -func resourceIBMIsVirtualNetworkInterfaceSecurityGroupReferenceDeletedToMap(model *vpcv1.SecurityGroupReferenceDeleted) (map[string]interface{}, error) { +func resourceIBMIsVirtualNetworkInterfaceSecurityGroupReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil @@ -1059,7 +1059,7 @@ func resourceIBMIsVirtualNetworkInterfaceVirtualNetworkInterfaceTargetToMap(mode } } -func resourceIBMIsVirtualNetworkInterfaceShareMountTargetReferenceDeletedToMap(model *vpcv1.ShareMountTargetReferenceDeleted) (map[string]interface{}, error) { +func resourceIBMIsVirtualNetworkInterfaceShareMountTargetReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil @@ -1209,7 +1209,7 @@ func resourceIBMIsVirtualNetworkInterfaceVPCReferenceToMap(model *vpcv1.VPCRefer return modelMap, nil } -func resourceIBMIsVirtualNetworkInterfaceVPCReferenceDeletedToMap(model *vpcv1.VPCReferenceDeleted) (map[string]interface{}, error) { +func resourceIBMIsVirtualNetworkInterfaceVPCReferenceDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil diff --git a/ibm/service/vpc/resource_ibm_is_vpc.go b/ibm/service/vpc/resource_ibm_is_vpc.go index da9104f86c..9123b356f1 100644 --- a/ibm/service/vpc/resource_ibm_is_vpc.go +++ b/ibm/service/vpc/resource_ibm_is_vpc.go @@ -1849,7 +1849,7 @@ func resourceIBMIsVPCVPCReferenceDnsResolverContextToMap(model *vpcv1.VPCReferen return modelMap, nil } -func resourceIBMIsVPCVPCReferenceDnsResolverContextDeletedToMap(model *vpcv1.VPCReferenceDnsResolverContextDeleted) (map[string]interface{}, error) { +func resourceIBMIsVPCVPCReferenceDnsResolverContextDeletedToMap(model *vpcv1.Deleted) (map[string]interface{}, error) { modelMap := make(map[string]interface{}) modelMap["more_info"] = model.MoreInfo return modelMap, nil diff --git a/ibm/service/vpc/resource_ibm_is_vpc_routing_table_route.go b/ibm/service/vpc/resource_ibm_is_vpc_routing_table_route.go index dd5c23d053..bb7b4319f3 100644 --- a/ibm/service/vpc/resource_ibm_is_vpc_routing_table_route.go +++ b/ibm/service/vpc/resource_ibm_is_vpc_routing_table_route.go @@ -231,12 +231,12 @@ func resourceIBMISVPCRoutingTableRouteCreate(d *schema.ResourceData, meta interf if add, ok := d.GetOk(rNextHop); ok { item := add.(string) if net.ParseIP(item) == nil { - nhConnectionID := &vpcv1.RoutePrototypeNextHopRouteNextHopPrototypeVPNGatewayConnectionIdentity{ + nhConnectionID := &vpcv1.RouteNextHopPrototype{ ID: core.StringPtr(item), } createVpcRoutingTableRouteOptions.SetNextHop(nhConnectionID) } else { - nh := &vpcv1.RoutePrototypeNextHopRouteNextHopPrototypeRouteNextHopIP{ + nh := &vpcv1.RouteNextHopPrototype{ Address: core.StringPtr(item), } createVpcRoutingTableRouteOptions.SetNextHop(nh) diff --git a/ibm/service/vpc/resource_ibm_is_vpn_server.go b/ibm/service/vpc/resource_ibm_is_vpn_server.go index fa0042b9af..5c6713d25a 100644 --- a/ibm/service/vpc/resource_ibm_is_vpn_server.go +++ b/ibm/service/vpc/resource_ibm_is_vpn_server.go @@ -791,7 +791,7 @@ func resourceIBMIsVPNServerReservedIPReferenceToMap(reservedIPReference vpcv1.Re return reservedIPReferenceMap } -func resourceIBMIsVPNServerReservedIPReferenceDeletedToMap(reservedIPReferenceDeleted vpcv1.ReservedIPReferenceDeleted) map[string]interface{} { +func resourceIBMIsVPNServerReservedIPReferenceDeletedToMap(reservedIPReferenceDeleted vpcv1.Deleted) map[string]interface{} { reservedIPReferenceDeletedMap := map[string]interface{}{} reservedIPReferenceDeletedMap["more_info"] = reservedIPReferenceDeleted.MoreInfo @@ -817,7 +817,7 @@ func resourceIBMIsVPNServerVPCReferenceToMap(vpcRef vpcv1.VPCReference) map[stri return vpcMap } -func resourceIBMIsVPNServerVPCReferenceDeletedToMap(vpcRefDeleted vpcv1.VPCReferenceDeleted) map[string]interface{} { +func resourceIBMIsVPNServerVPCReferenceDeletedToMap(vpcRefDeleted vpcv1.Deleted) map[string]interface{} { vpcRefDeletedMap := map[string]interface{}{} vpcRefDeletedMap["more_info"] = vpcRefDeleted.MoreInfo return vpcRefDeletedMap diff --git a/ibm/validate/validators.go b/ibm/validate/validators.go index dd9df34b11..775ed53962 100644 --- a/ibm/validate/validators.go +++ b/ibm/validate/validators.go @@ -79,6 +79,24 @@ func ValidBucketLifecycleTimestamp(v interface{}, k string) (ws []string, errors return } +func ValidateUTCFormat(v interface{}, k string) (ws []string, errors []error) { + // Assert v to be a string + value, ok := v.(string) + if !ok { + errors = append(errors, fmt.Errorf("value must be a string, got %T", v)) + return + } + + // Parse the string as RFC3339 time format + _, err := time.Parse(time.RFC3339, value) + if err != nil { + errors = append(errors, fmt.Errorf("value must be in RFC3339 format %q. Example: %s", time.RFC3339, err)) + return + } + + return +} + func validateRegexpLen(min, max int, regex string) schema.SchemaValidateFunc { return func(v interface{}, k string) (ws []string, errors []error) { value := v.(string) diff --git a/version/version.go b/version/version.go index b25b667ab2..3f91a3b5bb 100644 --- a/version/version.go +++ b/version/version.go @@ -5,7 +5,7 @@ import ( ) // Version is the current provider main version -const Version = "1.69.1" +const Version = "1.70.0-beta0" // GitCommit is the git commit that was compiled. This will be filled in by the compiler. var GitCommit string diff --git a/website/allowed-subcategories.txt b/website/allowed-subcategories.txt index 09d6aa3a2a..eabfa032b2 100644 --- a/website/allowed-subcategories.txt +++ b/website/allowed-subcategories.txt @@ -8,6 +8,7 @@ Cloud Database Cloud Foundry Cloudant Databases Code Engine +Configuration Aggregator Container Registry Context Based Restrictions CD Tekton Pipeline diff --git a/website/docs/d/code_engine_function.html.markdown b/website/docs/d/code_engine_function.html.markdown new file mode 100644 index 0000000000..350dbb3fdd --- /dev/null +++ b/website/docs/d/code_engine_function.html.markdown @@ -0,0 +1,114 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_code_engine_function" +description: |- + Get information about code_engine_function +subcategory: "Code Engine" +--- + +# ibm_code_engine_function + +Provides a read-only data source to retrieve information about a code_engine_function. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. + +## Example Usage + +```hcl +data "ibm_code_engine_function" "code_engine_function" { + name = ibm_code_engine_function.code_engine_function_instance.name + project_id = ibm_code_engine_function.code_engine_function_instance.project_id +} +``` + +## Argument Reference + +You can specify the following arguments for this data source. + +* `name` - (Required, Forces new resource, String) The name of your function. + * Constraints: The maximum length is `63` characters. The minimum length is `1` character. The value must match regular expression `/^[a-z]([-a-z0-9]*[a-z0-9])?$/`. +* `project_id` - (Required, Forces new resource, String) The ID of the project. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$/`. + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the code_engine_function. + +* `function_id` - (String) The identifier of the resource. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$/`. + +* `code_binary` - (Boolean) Specifies whether the code is binary or not. Defaults to false when `code_reference` is set to a data URL. When `code_reference` is set to a code bundle URL, this field is always true. + +* `code_main` - (String) Specifies the name of the function that should be invoked. + * Constraints: The default value is `main`. The maximum length is `63` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z_][a-zA-Z0-9_]*$/`. + +* `code_reference` - (String) Specifies either a reference to a code bundle or the source code itself. To specify the source code, use the data URL scheme and include the source code as base64 encoded. The data URL scheme is defined in [RFC 2397](https://tools.ietf.org/html/rfc2397). + * Constraints: The maximum length is `1048576` characters. The minimum length is `1` character. The value must match regular expression `/^([a-z0-9][a-z0-9\\-_.]+[a-z0-9][\/])?([a-z0-9][a-z0-9\\-_]+[a-z0-9][\/])?[a-z0-9][a-z0-9\\-_.\/]+[a-z0-9](:[\\w][\\w.\\-]{0,127})?(@sha256:[a-fA-F0-9]{64})?$|data:([-\\w]+\/[-+\\w.]+)?(;?\\w+=[-\\w]+)*;base64,.*/`. + +* `code_secret` - (String) The name of the secret that is used to access the specified `code_reference`. The secret is used to authenticate with a non-public endpoint that is specified as`code_reference`. + * Constraints: The maximum length is `253` characters. The minimum length is `1` character. The value must match regular expression `/^[a-z0-9]([\\-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([\\-a-z0-9]*[a-z0-9])?)*$/`. + +* `created_at` - (String) The timestamp when the resource was created. + +* `endpoint` - (String) URL to invoke the function. + * Constraints: The maximum length is `2048` characters. The minimum length is `0` characters. The value must match regular expression `/(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/`. + +* `endpoint_internal` - (String) URL to function that is only visible within the project. + * Constraints: The maximum length is `2048` characters. The minimum length is `0` characters. The value must match regular expression `/(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/`. + +* `entity_tag` - (String) The version of the function instance, which is used to achieve optimistic locking. + * Constraints: The maximum length is `63` characters. The minimum length is `1` character. The value must match regular expression `/^[\\*\\-a-z0-9]+$/`. + +* `href` - (String) When you provision a new function, a relative URL path is created identifying the location of the instance. + * Constraints: The maximum length is `2048` characters. The minimum length is `0` characters. The value must match regular expression `/(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/`. + +* `managed_domain_mappings` - (String) Optional value controlling which of the system managed domain mappings will be setup for the function. Valid values are 'local_public', 'local_private' and 'local'. Visibility can only be 'local_private' if the project supports function private visibility. + * Constraints: The default value is `local_public`. Allowable values are: `local`, `local_private`, `local_public`. + +* `region` - (String) The region of the project the resource is located in. Possible values: 'au-syd', 'br-sao', 'ca-tor', 'eu-de', 'eu-gb', 'jp-osa', 'jp-tok', 'us-east', 'us-south'. + +* `resource_type` - (String) The type of the function. + * Constraints: Allowable values are: `function_v2`. + +* `run_env_variables` - (List) References to config maps, secrets or literal values, which are defined by the function owner and are exposed as environment variables in the function. + * Constraints: The maximum length is `100` items. The minimum length is `0` items. +Nested schema for **run_env_variables**: + * `key` - (String) The key to reference as environment variable. + * Constraints: The maximum length is `253` characters. The minimum length is `1` character. The value must match regular expression `/^[\\-._a-zA-Z0-9]+$/`. + * `name` - (String) The name of the environment variable. + * Constraints: The maximum length is `253` characters. The minimum length is `1` character. The value must match regular expression `/^[\\-._a-zA-Z0-9]+$/`. + * `prefix` - (String) A prefix that can be added to all keys of a full secret or config map reference. + * Constraints: The maximum length is `253` characters. The minimum length is `0` characters. The value must match regular expression `/^[a-zA-Z_][a-zA-Z0-9_]*$/`. + * `reference` - (String) The name of the secret or config map. + * Constraints: The maximum length is `253` characters. The minimum length is `1` character. The value must match regular expression `/^[a-z0-9]([\\-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([\\-a-z0-9]*[a-z0-9])?)*$/`. + * `type` - (String) Specify the type of the environment variable. + * Constraints: The default value is `literal`. Allowable values are: `literal`, `config_map_full_reference`, `secret_full_reference`, `config_map_key_reference`, `secret_key_reference`. The value must match regular expression `/^(literal|config_map_full_reference|secret_full_reference|config_map_key_reference|secret_key_reference)$/`. + * `value` - (String) The literal value of the environment variable. + * Constraints: The maximum length is `253` characters. The minimum length is `1` character. The value must match regular expression `/^[\\-._a-zA-Z0-9]+$/`. + +* `runtime` - (String) The managed runtime used to execute the injected code. + * Constraints: The maximum length is `63` characters. The minimum length is `1` character. The value must match regular expression `/^[a-z]*\\-[0-9]*(\\.[0-9]*)?$/`. + +* `scale_concurrency` - (Integer) Number of parallel requests handled by a single instance, supported only by Node.js, default is `1`. + * Constraints: The default value is `1`. The maximum value is `100`. The minimum value is `1`. + +* `scale_cpu_limit` - (String) Optional amount of CPU set for the instance of the function. For valid values see [Supported memory and CPU combinations](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo). + * Constraints: The default value is `1`. The maximum length is `10` characters. The minimum length is `0` characters. The value must match regular expression `/^([0-9.]+)([eEinumkKMGTPB]*)$/`. + +* `scale_down_delay` - (Integer) Optional amount of time in seconds that delays the scale down behavior for a function. + * Constraints: The default value is `1`. The maximum value is `600`. The minimum value is `0`. + +* `scale_max_execution_time` - (Integer) Timeout in secs after which the function is terminated. + * Constraints: The default value is `60`. The maximum value is `120`. The minimum value is `1`. + +* `scale_memory_limit` - (String) Optional amount of memory set for the instance of the function. For valid values see [Supported memory and CPU combinations](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo). The units for specifying memory are Megabyte (M) or Gigabyte (G), whereas G and M are the shorthand expressions for GB and MB. For more information see [Units of measurement](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo#unit-measurements). + * Constraints: The default value is `4G`. The maximum length is `10` characters. The minimum length is `0` characters. The value must match regular expression `/^([0-9.]+)([eEinumkKMGTPB]*)$/`. + +* `status` - (String) The current status of the function. + * Constraints: Allowable values are: `offline`, `deploying`, `ready`, `failed`. + +* `status_details` - (List) The detailed status of the function. +Nested schema for **status_details**: + * `reason` - (String) Provides additional information about the status of the function. + * Constraints: Allowable values are: `offline`, `deploying_configuring_routes`, `ready_update_in_progress`, `deploying`, `ready_last_update_failed`, `ready`, `unknown_reason`, `no_code_bundle`. + diff --git a/website/docs/d/config_aggregator_configurations.html.markdown b/website/docs/d/config_aggregator_configurations.html.markdown new file mode 100644 index 0000000000..817349a86e --- /dev/null +++ b/website/docs/d/config_aggregator_configurations.html.markdown @@ -0,0 +1,70 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_config_aggregator_configurations" +description: |- + Get information about config_aggregator_configurations +subcategory: "Configuration Aggregator" +--- + +# ibm_config_aggregator_configurations + +Provides a read-only data source to retrieve information about config_aggregator_configurations. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. + +## Example Usage + +```hcl +data "ibm_config_aggregator_configurations" "config_aggregator_configurations" { +} +``` + +## Argument Reference + +You can specify the following arguments for this data source. + +* `config_type` - (Optional, String) The type of resource configuration that are to be retrieved. + * Constraints: The maximum length is `1024` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9 ,\\-_]+$/`. +* `location` - (Optional, String) The location or region in which the resources are created. + * Constraints: The maximum length is `32` characters. The minimum length is `0` characters. The value must match regular expression `/^$|[a-z]-[a-z]/`. +* `resource_crn` - (Optional, String) The crn of the resource. + * Constraints: The maximum length is `1000` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9.\\:\/-]+$/`. +* `resource_group_id` - (Optional, String) The resource group id of the resources. + * Constraints: The maximum length is `32` characters. The minimum length is `0` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. +* `service_name` - (Optional, String) The name of the IBM Cloud service for which resources are to be retrieved. + * Constraints: The maximum length is `1024` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9 ,\\-_]+$/`. + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the config_aggregator_configurations. +* `configs` - (List) Array of resource configurations. + * Constraints: The maximum length is `100` items. The minimum length is `0` items. +Nested schema for **configs**: + * `about` - (List) The basic metadata fetched from the query API. + Nested schema for **about**: + * `account_id` - (String) The account ID in which the resource exists. + * Constraints: The maximum length is `32` characters. The minimum length is `0` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. + * `config_type` - (String) The type of configuration of the retrieved resource. + * Constraints: The maximum length is `1000` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9.\\:\/-]+$/`. + * `last_config_refresh_time` - (String) Date/time stamp identifying when the information was last collected. Must be in the RFC 3339 format. + * `location` - (String) Location of the resource specified. + * Constraints: The maximum length is `1000` characters. The minimum length is `0` characters. The value must match regular expression `/^$|[a-z]-[a-z]/`. + * `resource_crn` - (String) The unique CRN of the IBM Cloud resource. + * Constraints: The maximum length is `1000` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9.\\:\/-]+$/`. + * `resource_group_id` - (String) The account ID. + * Constraints: The maximum length is `32` characters. The minimum length is `0` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. + * `resource_name` - (String) User defined name of the resource. + * Constraints: The maximum length is `1000` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9.\\:\/-]+$/`. + * `service_name` - (String) The name of the service to which the resources belongs. + * Constraints: The maximum length is `1000` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z0-9.\\:\/-]+$/`. + * `tags` - (List) Tags associated with the resource. + Nested schema for **tags**: + * `tag` - (String) The name of the tag. + * Constraints: The maximum length is `32` characters. The minimum length is `0` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. + * `config` - (List) The configuration of the resource. + Nested schema for **config**: +* `prev` - (List) The reference to the previous page of entries. +Nested schema for **prev**: + * `href` - (String) The reference to the previous page of entries. + * `start` - (String) the start string for the query to view the page. + diff --git a/website/docs/d/config_aggregator_resource_collection_status.html.markdown b/website/docs/d/config_aggregator_resource_collection_status.html.markdown new file mode 100644 index 0000000000..47ab80ae7b --- /dev/null +++ b/website/docs/d/config_aggregator_resource_collection_status.html.markdown @@ -0,0 +1,29 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_config_aggregator_resource_collection_status" +description: |- + Get information about config_aggregator_resource_collection_status +subcategory: "Configuration Aggregator" +--- + +# ibm_config_aggregator_resource_collection_status + +Provides a read-only data source to retrieve information about config_aggregator_resource_collection_status. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. + +## Example Usage + +```hcl +data "ibm_config_aggregator_resource_collection_status" "config_aggregator_resource_collection_status" { +} +``` + + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the config_aggregator_resource_collection_status. +* `last_config_refresh_time` - (String) The timestamp at which the configuration was last refreshed. +* `status` - (String) Status of the resource collection. + * Constraints: Allowable values are: `initiated`, `inprogress`, `complete`. + diff --git a/website/docs/d/config_aggregator_settings.html.markdown b/website/docs/d/config_aggregator_settings.html.markdown new file mode 100644 index 0000000000..43053c82ca --- /dev/null +++ b/website/docs/d/config_aggregator_settings.html.markdown @@ -0,0 +1,45 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_config_aggregator_settings" +description: |- + Get information about config_aggregator_settings +subcategory: "Configuration Aggregator" +--- + +# ibm_config_aggregator_settings + +Provides a read-only data source to retrieve information about config_aggregator_settings. You can then reference the fields of the data source in other resources within the same configuration by using interpolation syntax. + +## Example Usage + +```hcl +data "ibm_config_aggregator_settings" "config_aggregator_settings" { +} +``` + + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the config_aggregator_settings. +* `additional_scope` - (List) The additional scope that enables resource collection for Enterprise acccounts. + * Constraints: The maximum length is `10` items. The minimum length is `0` items. +Nested schema for **additional_scope**: + * `enterprise_id` - (String) The Enterprise ID. + * Constraints: The maximum length is `32` characters. The minimum length is `0` characters. The value must match regular expression `/[a-zA-Z0-9]/`. + * `profile_template` - (List) The Profile Template details applied on the enterprise account. + Nested schema for **profile_template**: + * `id` - (String) The Profile Template ID created in the enterprise account that provides access to App Configuration instance for resource collection. + * Constraints: The maximum length is `52` characters. The minimum length is `52` characters. The value must match regular expression `/[a-zA-Z0-9-]/`. + * `trusted_profile_id` - (String) The trusted profile ID that provides access to App Configuration instance to retrieve template information. + * Constraints: The maximum length is `44` characters. The minimum length is `44` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. + * `type` - (String) The type of scope. Currently allowed value is Enterprise. + * Constraints: The maximum length is `64` characters. The minimum length is `0` characters. The value must match regular expression `/[a-zA-Z0-9]/`. +* `last_updated` - (String) The last time the settings was last updated. +* `regions` - (List) Regions for which the resource collection is enabled. + * Constraints: The list items must match regular expression `/^[a-zA-Z0-9-]*$/`. The maximum length is `10` items. The minimum length is `0` items. +* `resource_collection_enabled` - (Boolean) The field to check if the resource collection is enabled. +* `trusted_profile_id` - (String) The trusted profile ID that provides access to App Configuration instance to retrieve resource metadata. + * Constraints: The maximum length is `44` characters. The minimum length is `44` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. + diff --git a/website/docs/d/en_destination_slack.html.markdown b/website/docs/d/en_destination_slack.html.markdown index 44c4e4eede..a534fc3e5b 100644 --- a/website/docs/d/en_destination_slack.html.markdown +++ b/website/docs/d/en_destination_slack.html.markdown @@ -52,6 +52,8 @@ In addition to all argument references listed, you can access the following attr Nested scheme for **params**: + - `type` - (String) The type of slack destination. The supported values are incoming_webhook and direct_message - `url` - (String) Slack Webhook url. + - `token`- (String) Token of slack application - `updated_at` - (String) Last updated time. diff --git a/website/docs/d/en_subscription_slack.html.markdown b/website/docs/d/en_subscription_slack.html.markdown index 9702c90df6..3fa73022f5 100644 --- a/website/docs/d/en_subscription_slack.html.markdown +++ b/website/docs/d/en_subscription_slack.html.markdown @@ -50,5 +50,7 @@ In addition to all argument references listed, you can access the following attr - `attributes` - (Required, List) - `attachment_color` - (String) The color code for slack attachment . + - `template_id_notification` - (String) The templete id for notification + - `channels` - (List) List of channels - `updated_at` - (String) Last updated time. diff --git a/website/docs/d/iam_policy_assignment.html.markdown b/website/docs/d/iam_policy_assignment.html.markdown index a309ddb4cf..19bfcbce60 100644 --- a/website/docs/d/iam_policy_assignment.html.markdown +++ b/website/docs/d/iam_policy_assignment.html.markdown @@ -19,6 +19,14 @@ data "ibm_iam_policy_assignments" "policy_assignment" { ## Argument Reference +## Timeouts section + +The resource includes default timeout settings for the following operations: + +* `create` - (Timeout) Defaults to 30 minutes. +* `update` - (Timeout) Defaults to 30 minutes. +* `delete` - (Timeout) Defaults to 30 minutes. + ## Attribute Reference diff --git a/website/docs/d/is_zone.html.markdown b/website/docs/d/is_zone.html.markdown index 68790a88fc..ee547e134f 100644 --- a/website/docs/d/is_zone.html.markdown +++ b/website/docs/d/is_zone.html.markdown @@ -41,3 +41,5 @@ Review the argument references that you can specify for your data source. In addition to all argument reference list, you can access the following attribute references after your data source is created. - `status` - (String) The status of the zone. +- `data_center` - (String) The physical data center assigned to this logical zone. If absent, no physical data center has been assigned. +- `universal_name` - (String) The universal name for this zone. Will be absent if this zone has a status of unassigned. diff --git a/website/docs/d/is_zones.html.markdown b/website/docs/d/is_zones.html.markdown index 057f859e6a..d23589d5e2 100644 --- a/website/docs/d/is_zones.html.markdown +++ b/website/docs/d/is_zones.html.markdown @@ -38,3 +38,9 @@ Review the argument references that you can specify for your data source. In addition to all argument reference list, you can access the following attribute references after your data source is created. - `zones` - (String) The list of zones in an IBM Cloud region. For example, **us-south-1**,**us-south-2**. +- `zone_info` - (List) Collection of zones. + Nested schema for **zone_info**: + - `data_center` - (String) The physical data center assigned to this logical zone. If absent, no physical data center has been assigned. + - `name` - (String) The name of the zone. + - `status` - (String) The status of the zone. + - `universal_name` - (String) The universal name for this zone. Will be absent if this zone has a status of unassigned. diff --git a/website/docs/d/logs-router_targets.html.markdown b/website/docs/d/logs-router_targets.html.markdown index 893f08f47a..435d3c2b00 100644 --- a/website/docs/d/logs-router_targets.html.markdown +++ b/website/docs/d/logs-router_targets.html.markdown @@ -15,7 +15,7 @@ Provides a read-only data source to retrieve information about logs_router_targe ```hcl data "ibm_logs_router_targets" "logs_router_targets" { tenant_id = "9fab83da-98cb-4f18-a7ba-b6f0435c9673" - name = "my-target" + region = "us-east" } ``` @@ -25,6 +25,8 @@ You can specify the following arguments for this data source. * `name` - (Optional, String) Optional: Name of the tenant target. * Constraints: The maximum length is `35` characters. The minimum length is `1` character. The value must match regular expression `/[A-F,0-9,-]/`. +* `region` - (Required, Forces new resource, String) The region where the tenant for this target exists. + * Constraints: The value must match one of the available regions. For a list of regions, see the available [IBM Cloud Logs Router Endpoints](https://cloud.ibm.com/docs/logs-router?topic=logs-router-locations). * `tenant_id` - (Required, Forces new resource, String) The instance ID of the tenant. * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/[A-F,0-9,-]/`. diff --git a/website/docs/d/logs-router_tenants.html.markdown b/website/docs/d/logs-router_tenants.html.markdown index 412e74341c..3a2a5d66bf 100644 --- a/website/docs/d/logs-router_tenants.html.markdown +++ b/website/docs/d/logs-router_tenants.html.markdown @@ -15,6 +15,7 @@ Provides a read-only data source to retrieve information about logs_router_tenan ```hcl data "ibm_logs_router_tenants" "logs_router_tenants" { name = ibm_logs_router_tenant.logs_router_tenant_instance.name + region = ibm_logs_router_tenant.logs_router_tenant_instance.region } ``` @@ -24,6 +25,8 @@ You can specify the following arguments for this data source. * `name` - (Required, String) Optional: The name of a tenant. * Constraints: The maximum length is `35` characters. The minimum length is `1` character. The value must match regular expression `/[A-F,0-9,-]/`. +* `region` - (Required, Forces new resource, String) The region where the tenant for this target exists. + * Constraints: The value must match one of the available regions. For a list of regions, see the available [IBM Cloud Logs Router Endpoints](https://cloud.ibm.com/docs/logs-router?topic=logs-router-locations). ## Attribute Reference diff --git a/website/docs/d/resource_key.html.markdown b/website/docs/d/resource_key.html.markdown index 53b46d268c..6709ae8fde 100644 --- a/website/docs/d/resource_key.html.markdown +++ b/website/docs/d/resource_key.html.markdown @@ -57,7 +57,7 @@ Review the argument references that you can specify for your data source. - `most_recent` - (Optional, Bool) If there are multiple resource keys, you can set this argument to `true` to import only the most recently created key. - `name` - (Required, String) The name of the resource key. You can retrieve the value by executing the `ibmcloud resource service-keys` command in the [IBM Cloud CLI](https://cloud.ibm.com/docs/cli?topic=cloud-cli-getting-started). - `resource_instance_id` - (Optional, string) The ID of the resource instance that the resource key is associated with. You can retrieve the value by executing the `ibmcloud resource service-instances` command in the [IBM Cloud CLI](https://cloud.ibm.com/docs/cli?topic=cloud-cli-getting-started). **Note**: Conflicts with `resource_alias_id`. -- `resource_alias_id` - (Optional, String) The ID of the resource alias that the resource key is associated with. You can retrieve the value by executing the `ibmcloud resource service-alias` command in the [IBM Cloud CLI](https://cloud.ibm.com/docs/cli?topic=cloud-cli-getting-started). **Note** Conflicts with `resource_instance_id`. +- `resource_alias_id` - (Optional, String, Deprecated) The ID of the resource alias that the resource key is associated with. You can retrieve the value by executing the `ibmcloud resource service-alias` command in the [IBM Cloud CLI](https://cloud.ibm.com/docs/cli?topic=cloud-cli-getting-started). **Note** Conflicts with `resource_instance_id`. ## Attribute reference In addition to all argument reference list, you can access the following attribute references after your data source is created. diff --git a/website/docs/guides/binding-services.html.md b/website/docs/guides/binding-services.html.md new file mode 100644 index 0000000000..0ffb16fdb9 --- /dev/null +++ b/website/docs/guides/binding-services.html.md @@ -0,0 +1,51 @@ +--- +subcategory: "" +layout: "ibm" +page_title: "Binding a Service to a Cluster" +description: |- + Bind an IBM Cloud service to an IBM Cloud Kubernetes Service cluster. +--- + +# Binding a Service to a Cluster + +Bind an IBM Cloud service to an IBM Cloud Kubernetes Service cluster. Service binding is a quick way to create service credentials for an IBM Cloud service by using its public service endpoint and storing these credentials in a Kubernetes secret in your cluster. The Kubernetes secret is automatically encrypted in etcd to protect your data. + +To bind a service to your cluster, you need to: + +1. Create a resource key for the service +2. Use the target cluster's config as the `kubernetes` provider's configuration +3. Create a kubernetes secret, using the resource key's credentials + +## Example + +In the following example, we bind the `ibm_resource_instance.kms` service to `ibm_container_cluster.cluster`. + +```terraform +// create resource key +resource "ibm_resource_key" "kms_key" { + name = "kms_key" + resource_instance_id = ibm_resource_instance.kms.id +} + +// get cluster config by cluster ID +data "ibm_container_cluster_config" "cluster_config" { + cluster_name_id = ibm_container_cluster.cluster.id +} + +// use kubernetes provider configuration from cluster +provider "kubernetes" { + host = data.ibm_container_cluster_config.cluster_config.host + token = data.ibm_container_cluster_config.cluster_config.token + cluster_ca_certificate = data.ibm_container_cluster_config.cluster_config.ca_certificate +} + +// create kubernetes secret from resource key's credentials +resource "kubernetes_secret_v1" "kms_secret" { + metadata { + name = "kms-secret" + namespace = "default" + } + + data = ibm_resource_key.kms_key.credentials +} +``` diff --git a/website/docs/r/code_engine_function.html.markdown b/website/docs/r/code_engine_function.html.markdown new file mode 100644 index 0000000000..91ec786350 --- /dev/null +++ b/website/docs/r/code_engine_function.html.markdown @@ -0,0 +1,117 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_code_engine_function" +description: |- + Manages code_engine_function. +subcategory: "Code Engine" +--- + +# ibm_code_engine_function + +Create, update, and delete code_engine_functions with this resource. + +## Example Usage + +```hcl +resource "ibm_code_engine_function" "code_engine_function_instance" { + project_id = ibm_code_engine_project.code_engine_project_instance.project_id + name = "my-function" + runtime = "nodejs-20" + code_reference = "icr.io/codeengine/samples/function-nodejs-codebundle" +} +``` + +## Timeouts + +code_engine_function provides the following [Timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) configuration options: + +* `create` - (Default 10 minutes) Used for creating a code_engine_function. +* `update` - (Default 10 minutes) Used for updating a code_engine_function. + +## Argument Reference + +You can specify the following arguments for this resource. + +* `code_binary` - (Optional, Boolean) Specifies whether the code is binary or not. Defaults to false when `code_reference` is set to a data URL. When `code_reference` is set to a code bundle URL, this field is always true. +* `code_main` - (Optional, String) Specifies the name of the function that should be invoked. + * Constraints: The default value is `main`. The maximum length is `63` characters. The minimum length is `1` character. The value must match regular expression `/^[a-zA-Z_][a-zA-Z0-9_]*$/`. +* `code_reference` - (Required, String) Specifies either a reference to a code bundle or the source code itself. To specify the source code, use the data URL scheme and include the source code as base64 encoded. The data URL scheme is defined in [RFC 2397](https://tools.ietf.org/html/rfc2397). + * Constraints: The maximum length is `1048576` characters. The minimum length is `1` character. The value must match regular expression `/^([a-z0-9][a-z0-9\\-_.]+[a-z0-9][\/])?([a-z0-9][a-z0-9\\-_]+[a-z0-9][\/])?[a-z0-9][a-z0-9\\-_.\/]+[a-z0-9](:[\\w][\\w.\\-]{0,127})?(@sha256:[a-fA-F0-9]{64})?$|data:([-\\w]+\/[-+\\w.]+)?(;?\\w+=[-\\w]+)*;base64,.*/`. +* `code_secret` - (Optional, String) The name of the secret that is used to access the specified `code_reference`. The secret is used to authenticate with a non-public endpoint that is specified as`code_reference`. + * Constraints: The maximum length is `253` characters. The minimum length is `1` character. The value must match regular expression `/^[a-z0-9]([\\-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([\\-a-z0-9]*[a-z0-9])?)*$/`. +* `managed_domain_mappings` - (Optional, String) Optional value controlling which of the system managed domain mappings will be setup for the function. Valid values are 'local_public', 'local_private' and 'local'. Visibility can only be 'local_private' if the project supports function private visibility. + * Constraints: The default value is `local_public`. Allowable values are: `local`, `local_private`, `local_public`. +* `name` - (Required, Forces new resource, String) The name of the function. + * Constraints: The maximum length is `63` characters. The minimum length is `1` character. The value must match regular expression `/^[a-z]([-a-z0-9]*[a-z0-9])?$/`. +* `project_id` - (Required, Forces new resource, String) The ID of the project. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$/`. +* `run_env_variables` - (Optional, List) References to config maps, secrets or literal values, which are defined by the function owner and are exposed as environment variables in the function. + * Constraints: The maximum length is `100` items. The minimum length is `0` items. +Nested schema for **run_env_variables**: + * `key` - (Optional, String) The key to reference as environment variable. + * Constraints: The maximum length is `253` characters. The minimum length is `1` character. The value must match regular expression `/^[\\-._a-zA-Z0-9]+$/`. + * `name` - (Optional, String) The name of the environment variable. + * Constraints: The maximum length is `253` characters. The minimum length is `1` character. The value must match regular expression `/^[\\-._a-zA-Z0-9]+$/`. + * `prefix` - (Optional, String) A prefix that can be added to all keys of a full secret or config map reference. + * Constraints: The maximum length is `253` characters. The minimum length is `0` characters. The value must match regular expression `/^[a-zA-Z_][a-zA-Z0-9_]*$/`. + * `reference` - (Optional, String) The name of the secret or config map. + * Constraints: The maximum length is `253` characters. The minimum length is `1` character. The value must match regular expression `/^[a-z0-9]([\\-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([\\-a-z0-9]*[a-z0-9])?)*$/`. + * `type` - (Optional, String) Specify the type of the environment variable. + * Constraints: The default value is `literal`. Allowable values are: `literal`, `config_map_full_reference`, `secret_full_reference`, `config_map_key_reference`, `secret_key_reference`. The value must match regular expression `/^(literal|config_map_full_reference|secret_full_reference|config_map_key_reference|secret_key_reference)$/`. When referencing a secret or configmap, the `reference` must be specified. When referencing a secret or configmap key, a `key` must also be specified. + * `value` - (Optional, String) The literal value of the environment variable. + * Constraints: The maximum length is `253` characters. The minimum length is `1` character. The value must match regular expression `/^[\\-._a-zA-Z0-9]+$/`. +* `runtime` - (Required, String) The managed runtime used to execute the injected code. + * Constraints: The maximum length is `63` characters. The minimum length is `1` character. The value must match regular expression `/^[a-z]*\\-[0-9]*(\\.[0-9]*)?$/`. +* `scale_concurrency` - (Optional, Integer) Number of parallel requests handled by a single instance, supported only by Node.js, default is `1`. + * Constraints: The default value is `1`. The maximum value is `100`. The minimum value is `1`. +* `scale_cpu_limit` - (Optional, String) Optional amount of CPU set for the instance of the function. For valid values see [Supported memory and CPU combinations](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo). + * Constraints: The default value is `1`. The maximum length is `10` characters. The minimum length is `0` characters. The value must match regular expression `/^([0-9.]+)([eEinumkKMGTPB]*)$/`. +* `scale_down_delay` - (Optional, Integer) Optional amount of time in seconds that delays the scale down behavior for a function. + * Constraints: The default value is `1`. The maximum value is `600`. The minimum value is `0`. +* `scale_max_execution_time` - (Optional, Integer) Timeout in secs after which the function is terminated. + * Constraints: The default value is `60`. The maximum value is `120`. The minimum value is `1`. +* `scale_memory_limit` - (Optional, String) Optional amount of memory set for the instance of the function. For valid values see [Supported memory and CPU combinations](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo). The units for specifying memory are Megabyte (M) or Gigabyte (G), whereas G and M are the shorthand expressions for GB and MB. For more information see [Units of measurement](https://cloud.ibm.com/docs/codeengine?topic=codeengine-mem-cpu-combo#unit-measurements). + * Constraints: The default value is `4G`. The maximum length is `10` characters. The minimum length is `0` characters. The value must match regular expression `/^([0-9.]+)([eEinumkKMGTPB]*)$/`. + +## Attribute Reference + +After your resource is created, you can read values from the listed arguments and the following attributes. + +* `id` - The unique identifier of the code_engine_function. +* `function_id` - (String) The identifier of the resource. + * Constraints: The maximum length is `36` characters. The minimum length is `36` characters. The value must match regular expression `/^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$/`. +* `created_at` - (String) The timestamp when the resource was created. +* `endpoint` - (String) URL to invoke the function. + * Constraints: The maximum length is `2048` characters. The minimum length is `0` characters. The value must match regular expression `/(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/`. +* `endpoint_internal` - (String) URL to function that is only visible within the project. + * Constraints: The maximum length is `2048` characters. The minimum length is `0` characters. The value must match regular expression `/(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/`. +* `entity_tag` - (String) The version of the function instance, which is used to achieve optimistic locking. + * Constraints: The maximum length is `63` characters. The minimum length is `1` character. The value must match regular expression `/^[\\*\\-a-z0-9]+$/`. +* `href` - (String) When you provision a new function, a relative URL path is created identifying the location of the instance. + * Constraints: The maximum length is `2048` characters. The minimum length is `0` characters. The value must match regular expression `/(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/`. +* `region` - (String) The region of the project the resource is located in. Possible values: 'au-syd', 'br-sao', 'ca-tor', 'eu-de', 'eu-gb', 'jp-osa', 'jp-tok', 'us-east', 'us-south'. +* `resource_type` - (String) The type of the function. + * Constraints: Allowable values are: `function_v2`. +* `status` - (String) The current status of the function. + * Constraints: Allowable values are: `offline`, `deploying`, `ready`, `failed`. +* `status_details` - (List) The detailed status of the function. +Nested schema for **status_details**: + * `reason` - (String) Provides additional information about the status of the function. + * Constraints: Allowable values are: `offline`, `deploying_configuring_routes`, `ready_update_in_progress`, `deploying`, `ready_last_update_failed`, `ready`, `unknown_reason`, `no_code_bundle`. +* `etag` - ETag identifier for code_engine_function. + +## Import + +You can import the `ibm_code_engine_function` resource by using `name`. +The `name` property can be formed from `project_id`, and `name` in the following format: + +
+<project_id>/<name>
+
+* `project_id`: A string in the format `15314cc3-85b4-4338-903f-c28cdee6d005`. The ID of the project. +* `name`: A string in the format `my-function`. The name of the function. + +# Syntax +
+$ terraform import ibm_code_engine_function.code_engine_function <project_id>/<name>
+
diff --git a/website/docs/r/config_aggregator_settings.html.markdown b/website/docs/r/config_aggregator_settings.html.markdown new file mode 100644 index 0000000000..21fc9c8fe2 --- /dev/null +++ b/website/docs/r/config_aggregator_settings.html.markdown @@ -0,0 +1,74 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_config_aggregator_settings" +description: |- + Manages config_aggregator_settings. +subcategory: "Configuration Aggregator" +--- + +# ibm_config_aggregator_settings + +Create, update, and delete config_aggregator_settingss with this resource. + +## Example Usage + +```hcl +resource "ibm_config_aggregator_settings" "config_aggregator_settings_instance" { + additional_scope { + type = "Enterprise" + enterprise_id = "enterprise_id" + profile_template { + id = "ProfileTemplate-adb55769-ae22-4c60-aead-bd1f84f93c57" + trusted_profile_id = "Profile-6bb60124-8fc3-4d18-b63d-0b99560865d3" + } + } + regions = us-south + resource_collection_enabled = true + trusted_profile_id = "Profile-1260aec2-f2fc-44e2-8697-2cc15a447560" +} +``` + +## Argument Reference + +You can specify the following arguments for this resource. + +* `additional_scope` - (Optional, Forces new resource, List) The additional scope that enables resource collection for Enterprise acccounts. + * Constraints: The maximum length is `10` items. The minimum length is `0` items. +Nested schema for **additional_scope**: + * `enterprise_id` - (Optional, String) The Enterprise ID. + * Constraints: The maximum length is `32` characters. The minimum length is `0` characters. The value must match regular expression `/[a-zA-Z0-9]/`. + * `profile_template` - (Optional, List) The Profile Template details applied on the enterprise account. + Nested schema for **profile_template**: + * `id` - (Optional, String) The Profile Template ID created in the enterprise account that provides access to App Configuration instance for resource collection. + * Constraints: The maximum length is `52` characters. The minimum length is `52` characters. The value must match regular expression `/[a-zA-Z0-9-]/`. + * `trusted_profile_id` - (Optional, String) The trusted profile ID that provides access to App Configuration instance to retrieve template information. + * Constraints: The maximum length is `44` characters. The minimum length is `44` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. + * `type` - (Optional, String) The type of scope. Currently allowed value is Enterprise. + * Constraints: The maximum length is `64` characters. The minimum length is `0` characters. The value must match regular expression `/[a-zA-Z0-9]/`. +* `regions` - (Optional, Forces new resource, List) The list of regions across which the resource collection is enabled. + * Constraints: The list items must match regular expression `/^[a-zA-Z0-9-]*$/`. The maximum length is `10` items. The minimum length is `0` items. +* `resource_collection_enabled` - (Optional, Forces new resource, Boolean) The field denoting if the resource collection is enabled. +* `trusted_profile_id` - (Optional, Forces new resource, String) The trusted profile id that provides Reader access to the App Configuration instance to collect resource metadata. + * Constraints: The maximum length is `44` characters. The minimum length is `44` characters. The value must match regular expression `/^[a-zA-Z0-9-]*$/`. + +## Attribute Reference + +After your resource is created, you can read values from the listed arguments and the following attributes. + +* `id` - The unique identifier of the config_aggregator_settings. + + +## Import + +You can import the `ibm_config_aggregator_settings` resource by using `trusted_profile_id`. The trusted profile id that provides Reader access to the App Configuration instance to collect resource metadata. +For more information, see [the documentation](https://cloud.ibm.com/docs/app-configuration) + +# Syntax +
+$ terraform import ibm_config_aggregator_settings.config_aggregator_settings <trusted_profile_id>
+
+ +# Example +``` +$ terraform import ibm_config_aggregator_settings.config_aggregator_settings Profile-6bb60124-8fc3-4d18-b63d-0b99560865d3 +``` diff --git a/website/docs/r/container_bind_service.html.markdown b/website/docs/r/container_bind_service.html.markdown index 51d92c19b4..5687dc314b 100644 --- a/website/docs/r/container_bind_service.html.markdown +++ b/website/docs/r/container_bind_service.html.markdown @@ -8,6 +8,10 @@ description: |- --- # ibm_container_bind_service + +> [!CAUTION] +> This resource will be deprecated, please check [this guide](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs/guides/binding-services) on how to bind services. + Bind an IBM Cloud service to an IBM Cloud Kubernetes Service cluster. Service binding is a quick way to create service credentials for an IBM Cloud service by using its public service endpoint and storing these credentials in a Kubernetes secret in your cluster. The Kubernetes secret is automatically encrypted in etcd to protect your data. To bind a service to your cluster, you must provision an instance of the service first. For more information, about service binding, see [Adding services by using IBM Cloud service binding](https://cloud.ibm.com/docs/containers?topic=containers-service-binding). diff --git a/website/docs/r/cos_bucket.html.markdown b/website/docs/r/cos_bucket.html.markdown index 812d8e93c8..da0e434825 100644 --- a/website/docs/r/cos_bucket.html.markdown +++ b/website/docs/r/cos_bucket.html.markdown @@ -457,11 +457,46 @@ resource "ibm_cos_bucket" "cos_bucket" { } ``` +# ibm_cos_bucket_lifecycle_configuration + +Provides an independent resource to manage the lifecycle configuration for a bucket.For more information please refer to [`ibm_cos_bucket_lifecycle_configuration`](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs/resources/ibm_cos_bucket_lifecycle_configuration) + +## Example usage + +```terraform +resource "ibm_cos_bucket" "cos_bucket" { + bucket_name = var.bucket_name + resource_instance_id = ibm_resource_instance.cos_instance.id + region_location = var.regional_loc + storage_class = var.standard_storage_class + +} +resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.cos_bucket.crn + bucket_location = ibm_cos_bucket.cos_bucket.region_location + lifecycle_rule { + expiration{ + days = 1 + } + filter { + prefix = "foo" + } + rule_id = "id" + status = "Enabled" + + } +} +``` + +**Note:** +To manage changes of Lifecycle rules to an cos bucket, use the ibm_cos_bucket_lifecycle_configuration resource instead. If you use `expire_rule` , `archive_rule` , `noncurrent_version_expiration`, `abort_incomplete_multipart_upload_days` on an ibm_cos_bucket, Terraform will assume management over the full set of Lifecycle rules for the cos bucket, treating additional Lifecycle rules as drift. For this reason, lifecycle_rule cannot be mixed with the external ibm_cos_bucket_lifecycle_configuration resource for a given S3 bucket. ## Argument reference Review the argument references that you can specify for your resource. - `abort_incomplete_multipart_upload_days` (Optional,List) Nested block with the following structure. + +(Recommended) Use `ibm_cos_bucket_lifecycle_configuration` instead of `abort_incomplete_multipart_upload_days` to manage the lifecycle abort incomplete multipart upload days on cos bucket. Nested scheme for `abort_incomplete_multipart_upload_days`: - `days_after_initiation` - (Optional, integer) Specifies the number of days that govern the automatic cancellation of part upload. Clean up incomplete multi-part uploads after a period of time. Must be a value greater than 0 and less than 3650. @@ -486,7 +521,9 @@ Review the argument references that you can specify for your resource. - `management_events`- (Optional, bool) If set to **true**, all bucket management events will be sent to Activity Tracker.This field only applies if `activity_tracker_crn` is not populated. - `archive_rule` - (Required, List) Nested archive_rule block has following structure. - + + (Recommended) Use `ibm_cos_bucket_lifecycle_configuration` instead of `archive rule` to manage the lifecycle archive rule on cos bucket. + Nested scheme for `archive_rule`: - `days` - (Required, integer) Specifies the number of days when the specific rule action takes effect. - `enable` - (Required, bool) Specifies archive rule status either `enable` or `disable` for a bucket. @@ -500,7 +537,8 @@ Review the argument references that you can specify for your resource. - `cross_region_location` - (Optional, string) Specify the cross-regional bucket location. Supported values are `us`, `eu`, and `ap`. If you use this parameter, do not set `single_site_location` or `region_location` at the same time. - `endpoint_type`- (Optional, string) The type of the endpoint either `public` or `private` or `direct` to be used for buckets. Default value is `public`. - `expire_rule` - (Required, List) An expiration rule deletes objects after a defined period (from the object creation date). see [lifecycle actions](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-versioning). Nested expire_rule block has following structure. - + + (Recommended) Use `ibm_cos_bucket_lifecycle_configuration` instead of `expire_rule` to manage the lifecycle expire rule on cos bucket. Nested scheme for `expire_rule`: - `days` - (Optional, integer) Specifies the number of days when the specific rule action takes effect. - `date` - (Optional, string) After the specifies date , the current version of objects in your bucket expires. @@ -537,7 +575,12 @@ Review the argument references that you can specify for your resource. - `request_metrics_enabled` : (Optional, bool) If set to **true**, all request metrics (i.e. `rest.object.head`) will be sent to the monitoring service. - `usage_metrics_enabled` : (Optional, bool) If set to **true**, all usage metrics (i.e. `bytes_used`) will be sent to the monitoring service. -- `noncurrent_version_expiration` - (Required, List) lifecycle has a versioning related expiration action: non-current version expiration. This can remove old versions of objects after they've been non-current for a specified number of days which is specified with a NoncurrentDays parameter on the rule. see [lifecycle actions](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-versioning). Nested noncurrent_version_expiration block has following structure. +- `noncurrent_version_expiration` - (Required, List) lifecycle has a versioning related expiration action: non-current version expiration. This can remove old versions of objects after they've been non-current for a specified number of days which is specified with a NoncurrentDays parameter on the rule. see [lifecycle actions](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-versioning). + + (Recommended) Use `ibm_cos_bucket_lifecycle_configuration` instead of `noncurrent_version_expiration` to manage the lifecycle noncurrent version expiration on cos bucket. + + Nested noncurrent_version_expiration block has following structure. + Nested scheme for `noncurrent_version_expiration`: - `enable` - (Requried, bool) A rule can either be `enabled` or `disabled`. A rule is active only when enabled. diff --git a/website/docs/r/cos_bucket_lifecycle_configuration.markdown b/website/docs/r/cos_bucket_lifecycle_configuration.markdown new file mode 100644 index 0000000000..093f3c1bdc --- /dev/null +++ b/website/docs/r/cos_bucket_lifecycle_configuration.markdown @@ -0,0 +1,324 @@ +--- + +subcategory: "Object Storage" +layout: "ibm" +page_title: "IBM : Cloud Object Storage Lifecycle Configuration" +description: + "Manages IBM Cloud Object Storage Lifecycle Configuration" +--- + +# ibm_cos_bucket_lifecycle_configuration +This is the recommended way of managing the lifecycle configuration for a bucket. This provides an independent resource to manage the lifecycle configuration for a bucket.A lifecycle configuration consists of an lifecycle rule , each rule has a unique id , status and an action. Action can be of 2 types - [transition](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-archive) and [expiration](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-expiry).It also consists of noncurrent version expiration and abort incomplete multipart upload.A lifecycle sonfiguration can have multiple expiration rules but only one transition rule. + + +## Example usage + +# Adding lifecycle configuration with expiration. + +Adding lifecycle configuration with expiration and prefix filter. + +```terraform + + +resource "ibm_cos_bucket" "cos_bucket" { + bucket_name = var.bucket_name + resource_instance_id = ibm_resource_instance.cos_instance.id + region_location = var.regional_loc + storage_class = var.standard_storage_class + +} +resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.cos_bucket.crn + bucket_location = ibm_cos_bucket.cos_bucket.region_location + lifecycle_rule { + expiration{ + days = 1 + } + filter { + prefix = "foo" + } + rule_id = "id" + status = "enable" + + } +} + +``` + +# Adding lifecycle configuration with transition. + +Adding lifecycle configuration with transition. + +```terraform + + +resource "ibm_cos_bucket" "cos_bucket" { + bucket_name = var.bucket_name + resource_instance_id = ibm_resource_instance.cos_instance.id + region_location = var.regional_loc + storage_class = var.standard_storage_class + +} +resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.cos_bucket.crn + bucket_location = ibm_cos_bucket.cos_bucket.region_location + lifecycle_rule { + transition{ + days = 1 + storage_class = "GLACIER" + } + filter { + prefix = "" + } + rule_id = "id" + status = "enable" + + } +} + +``` +# Adding lifecycle configuration with abort incomplete multipart upload. + +```terraform + + +resource "ibm_cos_bucket" "cos_bucket" { + bucket_name = var.bucket_name + resource_instance_id = ibm_resource_instance.cos_instance.id + region_location = var.regional_loc + storage_class = var.standard_storage_class + +} +resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.cos_bucket.crn + bucket_location = ibm_cos_bucket.cos_bucket.region_location + lifecycle_rule { + abort_incomplete_multipart_upload{ + days_after_initiation = 1 + } + filter { + prefix = "" + } + rule_id = "id" + status = "enable" + + } +} + +``` +# Adding lifecycle configuration with non current version expiration. + +```terraform + + +resource "ibm_cos_bucket" "cos_bucket" { + bucket_name = var.bucket_name + resource_instance_id = ibm_resource_instance.cos_instance.id + region_location = var.regional_loc + storage_class = var.standard_storage_class + +} +resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.cos_bucket.crn + bucket_location = ibm_cos_bucket.cos_bucket.region_location + lifecycle_rule { + noncurrent_version_expiration{ + noncurrent_days = "1 + } + filter { + prefix = "" + } + rule_id = "id" + status = "enable" + + } +} + +``` +# Adding lifecycle configuration with multiple rules. + +```terraform + + +resource "ibm_cos_bucket" "cos_bucket" { + bucket_name = var.bucket_name + resource_instance_id = ibm_resource_instance.cos_instance.id + region_location = var.regional_loc + storage_class = var.standard_storage_class + +} +resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.cos_bucket.crn + bucket_location = ibm_cos_bucket.cos_bucket.region_location + lifecycle_rule { + expiration{ + days = 1 + } + filter { + prefix = "foo" + } + rule_id = "id" + status = "enable" + } + lifecycle_rule { + expiration{ + days = 2 + } + filter { + prefix = "bar" + } + rule_id = "id2" + status = "enable" + } +} + +``` + +# Switching from legacy lifecycle rules to ibm_cos_bucket_lifecycle_configuration : + + +**Note:** +If you use legacy `expire_rule` , `archive_rule` , `noncurrent_version_expiration`, `abort_incomplete_multipart_upload_days` on an ibm_cos_bucket, Terraform will assume management over the full set of Lifecycle rules for the bucket, treating additional Lifecycle rules as drift. For this reason, legacy rules cannot be mixed with the external ibm_cos_bucket_lifecycle_configuration resource for a given cos bucket.Users that want to continue using the legacy `expire_rule` , `archive_rule` , `noncurrent_version_expiration`, `abort_incomplete_multipart_upload_days`. + +In case you want to switch from the legacy lifecycle rules to the new resource for an existing cos bucket with existing legacy lifecycle rules , please follow the steps below + +## Example usage +For example if there is a cos bucket existing in the `.tfstate` file with `expire_rule` applied. +```terraform + +# Existing Cos bucket configuration + +resource "ibm_cos_bucket" "cos_bucket" { + bucket_name = var.bucket_name + resource_instance_id = ibm_resource_instance.cos_instance.id + region_location = var.regional_loc + storage_class = var.standard_storage_class + expire_rule { + rule_id = "id" + enable = true + days = 45 + prefix = "foo" + } + +} + +``` +Step 1 : Add new `ibm_cos_bucket_lifecycle_configuration` with same configuration as exisitng. + +```terraform + +resource "ibm_cos_bucket" "cos_bucket" { + bucket_name = var.bucket_name + resource_instance_id = ibm_resource_instance.cos_instance.id + region_location = var.regional_loc + storage_class = var.standard_storage_class + expire_rule { + rule_id = "id" + enable = true + days = 45 + prefix = "foo" + } +} + +resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.cos_bucket.crn + bucket_location = ibm_cos_bucket.cos_bucket.region_location + lifecycle_rule { + expiration{ + days = 45 + } + filter { + prefix = "foo" + } + rule_id = "id" + status = "enable" + + } + } +} + +``` +Step 2 : Run `terraform apply` + +Step 3 : Remove the old configuration from the `ibm_cos_bucket` block + +```terraform + +resource "ibm_cos_bucket" "cos_bucket" { + bucket_name = var.bucket_name + resource_instance_id = ibm_resource_instance.cos_instance.id + region_location = var.regional_loc + storage_class = var.standard_storage_class +} + +resource "ibm_cos_bucket_lifecycle_configuration" "lifecycle" { + bucket_crn = ibm_cos_bucket.cos_bucket.crn + bucket_location = ibm_cos_bucket.cos_bucket.region_location + lifecycle_rule { + expiration{ + days = 45 + } + filter { + prefix = "foo" + } + rule_id = "id" + status = "enable" + + } + } +} + +``` + +## Argument reference +Review the argument references that you can specify for your resource. +- `bucket_crn` - (Required, Forces new resource, String) The CRN of the COS bucket. +- `bucket_location` - (Required, Forces new resource, String) The location of the COS bucket. +- `endpoint_type`- (Optional, String) The type of the endpoint either `public` or `private` or `direct` to be used for buckets. Default value is `public`. +- `lifecycle_rule`- (Required, List) Nested block have the following structure: + + Nested scheme for `lifecycle_rule`: + - `expiration`- (Optional) Configuration block that specifies the expiration for the lifecycle of the object in the form of date, days and, whether the object has a delete marker. + - `transition`- (Optional) Configuration block that specifies the transition for of the object. + - `abort_incomplete_multipart_upload`- (Optional) Configuration block that specifies the days since the initiation of an incomplete multipart upload that Amazon S3 will wait before permanently removing all parts of the upload. + - `noncurrent_version`- (Optinal) Configuration block that specifies when noncurrent object versions expire. + - `id`- (Required) Unique id for the rule. + - `filter`- (Required) Configuration block used to identify objects that a Lifecycle Rule applies to.If not specified, the rule will default to using prefix. + - `status`- (Required) Whether the rule is currently being applied. Valid values: enable or disable. + + Nested scheme for `expiration`: + - `days`- (Optional) Days, of the objects that are subject to the rule. The value must be a non-zero positive integer. + - `date`- (Optional) Date the object is to be deleted. The date value must be in RFC3339 full-date format. + - `expired_object_delete_marker`- (Optional, Conflicts with date and days) Indicates whether ibm will remove a delete marker with no noncurrent versions. + + Nested scheme for `transition`: + - `days`- (Optional) Number of days after creation when objects are transitioned to the specified storage class. The value must be a positive integer. If both days and date are not specified, defaults to 0. + - `date`- (Optional) Date objects are transitioned to the specified storage class. The date value must be in RFC3339 full-date format. + - `storage_class`- (Optional) Class of storage used to store the object. Valid Values: GLACIER,ACCELERATED. + + Nested scheme for `noncurrent_version_expiration`: + - `noncurrent_days` - (Optional) Number of days an object is noncurrent before lifecycle action is performed. Must be a positive integer. + + Nested scheme for `abort_incomplete_multipart_upload`: + - `days_after_initiation` - Number of days after which incomplete multipart uploads are aborted. + + + ## Import IBM COS lifecycle configuration +The lifecycle configurations rules for a bucket can be imported into an `ibm_cos_bucket_lifecycle_configuration` resource for a particular bucket using the bucket id. + +id = `$CRN:meta:$buckettype:$bucketlocation` + +**Syntax** + +``` +$ terraform import ibm_cos_bucket_lifecycle_configuration.lifecycle `$CRN:meta:$buckettype:$bucketlocation` + +``` + +**Example** + +``` + +$ terraform import ibm_cos_bucket_lifecycle_configuration.lifecycle crn:v1:bluemix:public:cloud-object-storage:global:a/4ea1882a2d3401ed1e459979941966ea:31fa970d-51d0-4b05-893e-251cba75a7b3:bucket:mybucketname:meta:crl:eu:public + +``` \ No newline at end of file diff --git a/website/docs/r/database.html.markdown b/website/docs/r/database.html.markdown index 2b151f7d55..d8cec79f7c 100644 --- a/website/docs/r/database.html.markdown +++ b/website/docs/r/database.html.markdown @@ -683,9 +683,10 @@ Review the argument reference that you can specify for your resource. - `remote_leader_id` - (Optional, String) A CRN of the leader database to make the replica(read-only) deployment. The leader database is created by a database deployment with the same service ID. A read-only replica is set up to replicate all of your data from the leader deployment to the replica deployment by using asynchronous replication. For more information, see [Configuring Read-only Replicas](https://cloud.ibm.com/docs/databases-for-postgresql?topic=databases-for-postgresql-read-only-replicas). - `resource_group_id` - (Optional, Forces new resource, String) The ID of the resource group where you want to create the instance. To retrieve this value, run `ibmcloud resource groups` or use the `ibm_resource_group` data source. If no value is provided, the `default` resource group is used. - `service` - (Required, Forces new resource, String) The type of Cloud Databases that you want to create. Only the following services are currently accepted: `databases-for-etcd`, `databases-for-postgresql`, `databases-for-redis`, `databases-for-elasticsearch`, `messages-for-rabbitmq`,`databases-for-mongodb`,`databases-for-mysql`, and `databases-for-enterprisedb`. -- `service_endpoints` - (Optional, String) Specify whether you want to enable the public, private, or both service endpoints. Supported values are `public`, `private`, or `public-and-private`. If you leave `service_endpoints` empty, the default value will be set based on the compliance standard in the region where the instance is being created. Generally, if the region is enabled with FS Cloud/ENS High compliance, then the default would be `private`. Otherwise, the default would be `public`. During any update, if you leave `service_endpoints` empty, it will maintain the previously selected value. +- `service_endpoints` - (Required, String) Specify whether you want to enable the public, private, or both service endpoints. Supported values are `public`, `private`, or `public-and-private`. - `tags` (Optional, Array of Strings) A list of tags that you want to add to your instance. - `version` - (Optional, Forces new resource, String) The version of the database to be provisioned. If omitted, the database is created with the most recent major and minor version. +- `deletion_protection` - (Optional, Boolean) If the DB instance should have deletion protection enabled. The database can't be deleted when this value is set to `true`. The default is `false`. - `users` - (Optional, List of Objects) A list of users that you want to create on the database. Multiple blocks are allowed. Nested scheme for `users`: diff --git a/website/docs/r/en_destination_slack.html.markdown b/website/docs/r/en_destination_slack.html.markdown index c7b3cd8ce5..8c9f36c649 100644 --- a/website/docs/r/en_destination_slack.html.markdown +++ b/website/docs/r/en_destination_slack.html.markdown @@ -12,6 +12,8 @@ Create, update, or delete a Slack destination by using IBM Cloud™ Event Notifi ## Example usage +Destination example for Slack destination type `incoming_webhook` + ```terraform resource "ibm_en_destination_slack" "slack_en_destination" { instance_guid = ibm_resource_instance.en_terraform_test_resource.guid @@ -21,12 +23,29 @@ resource "ibm_en_destination_slack" "slack_en_destination" { description = "Destination slack for event notification" config { params { + type = "incoming_webhook" url = "https://hooks.slack.com/services/G0gyhsush/TYodsjhs/GHTbfidsimkk" } } } ``` +Destination example for Slack destination type `direct_message` +```terraform +resource "ibm_en_destination_slack" "slack_en_destination" { + instance_guid = ibm_resource_instance.en_terraform_test_resource.guid + name = "My Slack Destination" + type = "slack" + collect_failed_events = false + description = "Destination slack for event notification" + config { + params { + type = "direct_message" + url = "dveufewldfwefewlfdweckewweldewfdewd" + } +} +} +``` ## Argument reference Review the argument reference that you can specify for your resource. @@ -49,7 +68,10 @@ Review the argument reference that you can specify for your resource. Nested scheme for **params**: - - `url` - (Required, String) Slack Webhook url. + - `type` - (Required, String) The Slack destination type. The supported type are incoming_webhook and direct_message + - `url` - (Optional, String) Slack Webhook url. + - `token` - (Optional, String) Token of slack application. + ## Attribute reference In addition to all argument references listed, you can access the following attribute references after your resource is created. diff --git a/website/docs/r/en_subscription_slack.html.markdown b/website/docs/r/en_subscription_slack.html.markdown index 87bd032dca..e47ba0e45e 100644 --- a/website/docs/r/en_subscription_slack.html.markdown +++ b/website/docs/r/en_subscription_slack.html.markdown @@ -12,6 +12,24 @@ Create, update, or delete a slack subscription by using IBM Cloud™ Event Notif ## Example usage +Subscription example for Slack Destination type `incoming_webhook` + +```terraform +resource "ibm_en_subscription_slack" "slack_subscription" { + instance_guid = ibm_resource_instance.en_terraform_test_resource.guid + name = "My Slack subscription" + description = "The Slack subscription for slack destination in Event Notifications" + destination_id = ibm_en_destination_slack.destination1.destination_id + topic_id = ibm_en_topic.topic1.topic_id + attributes { + attachment_color = "#FF0000" + template_id_notification = "e40843c8-hgft-4717-8ee4-f923f2786a34" + } +} +``` + +Subscription Create example for Slack Destination type `direct_message` + ```terraform resource "ibm_en_subscription_slack" "slack_subscription" { instance_guid = ibm_resource_instance.en_terraform_test_resource.guid @@ -20,7 +38,35 @@ resource "ibm_en_subscription_slack" "slack_subscription" { destination_id = ibm_en_destination_slack.destination1.destination_id topic_id = ibm_en_topic.topic1.topic_id attributes { - "attachment_color" = "#FF0000" + channels{ + id = "GHUIIIJBBBV" + } + channels{ + id = "TFDDDERRRV" + } + template_id_notification = "e40843c8-hgft-4717-8ee4-f923f2786a34" + } +} +``` + +Subscription Update example for Slack Destination type `direct_message` + +```terraform +resource "ibm_en_subscription_slack" "slack_subscription" { + instance_guid = ibm_resource_instance.en_terraform_test_resource.guid + name = "My Slack subscription" + description = "The Slack subscription for slack destination in Event Notifications" + destination_id = ibm_en_destination_slack.destination1.destination_id + topic_id = ibm_en_topic.topic1.topic_id + attributes { + channels{ + id = "GHUIIIJBBBV" + operation = "remove" + } + channels{ + id = "GGYEXCGHHUU" + operation = "add" + } template_id_notification = "e40843c8-hgft-4717-8ee4-f923f2786a34" } } @@ -47,6 +93,11 @@ Review the argument reference that you can specify for your resource. - `attachment_color` - (Optional, String) The color code for slack attachment. - `template_id_notification` - (Optional, String) The templete id for notification. + + - `channels` - (Optional, List) - List of channels . Channel attributes are + + - `id` - (Required, String)channel id + - `operation` - (Optional, String)The channel operation type . Required in case of slack subscription update. ## Attribute reference In addition to all argument references listed, you can access the following attribute references after your resource is created. diff --git a/website/docs/r/en_topic.html.markdown b/website/docs/r/en_topic.html.markdown index dff19479e6..f427a125c5 100644 --- a/website/docs/r/en_topic.html.markdown +++ b/website/docs/r/en_topic.html.markdown @@ -17,6 +17,15 @@ resource "ibm_en_topic" "en_topic" { instance_guid = ibm_resource_instance.en_terraform_test_resource.guid name = "e2e topic" description = "Topic for EN events routing" + sources { + id = ibm_resource_instance.cloud_logs_instance.crn + + rules { + enabled = true + event_type_filter = "$.*" + notification_filter = "$.data.alert_definition.name == '[${var.environment}]'" + } + } } ``` @@ -38,7 +47,7 @@ Review the argument reference that you can specify for your resource. - `rules` - (Required, List) List of rules. Nested scheme for **rules**: - - `enabled` - (Required, Boolean) Whether the rule is enabled or not. The default value is `true`. + - `enabled` - (Boolean) Whether the rule is enabled or not. The default value is `true`. - `event_type_filter` - (Required, String) Event type filter. The default value is `$.*`. The maximum length is `255`characters. The minimum length is`3`characters. The value must match regular expression`/[a-zA-Z 0-9-_$.=']_/`. diff --git a/website/docs/r/iam_access_tag.html.markdown b/website/docs/r/iam_access_tag.html.markdown new file mode 100644 index 0000000000..b05642a6ca --- /dev/null +++ b/website/docs/r/iam_access_tag.html.markdown @@ -0,0 +1,61 @@ +--- +subcategory: "Global Tagging" +layout: "ibm" +page_title: "IBM : iam_access_tag" +description: |- + Manages iam access tags. +--- + +# ibm_iam_access_tag + +Create or delete IBM Cloud access management tags. For more information, about access tags, see [IBM Cloud access management tags](https://cloud.ibm.com/apidocs/tagging#create-tag). + + +## Example usage +The following example enables you to create access management tags + +```terraform +resource "ibm_iam_access_tag" "example" { + name = "example:tag" +} + +``` + +## Argument reference +Review the argument references that you can specify for your resource. + +- `name` - (Required, String) The name of the access management tag. + + +## Attributes reference +In addition to all argument reference list, you can access the following attribute reference after your resource is created. + +- `id` - (String) The unique identifier of the access tag. Same as `name`. +- `tag_type` - (String) Type of the tag(`access`) + + +## Import + +The `ibm_iam_access_tag` resource can be imported by using the name. + +**Syntax** + +``` +$ terraform import ibm_iam_access_tag.tag tag_name +``` + +**Example** + +Example for importing access tags. + +**Syntax** + +``` +$ terraform import ibm_iam_access_tag.tag tag_name +``` + +**Example** + +``` +$ terraform import ibm_iam_access_tag.tag example:test +``` diff --git a/website/docs/r/is_subnet_reserved_ip_patch.html.markdown b/website/docs/r/is_subnet_reserved_ip_patch.html.markdown new file mode 100644 index 0000000000..488b06074e --- /dev/null +++ b/website/docs/r/is_subnet_reserved_ip_patch.html.markdown @@ -0,0 +1,91 @@ +--- +subcategory: "VPC infrastructure" +layout: "ibm" +page_title: "IBM : ibm_is_subnet_reserved_ip_patch" +description: |- + Manages IBM Subnet reserved IP patch. +--- + +# ibm_is_subnet_reserved_ip_patch +Update name and/or auto_delete of an existing reserved ip. For more information, about associated reserved IP subnet, see [reserved IP subnet](https://cloud.ibm.com/docs/vpc?topic=vpc-troubleshoot-reserved-ip). + +~> NOTE: Use this resource with caution, conflicts with `ibm_is_subnet_reserved_ip` resource if it has `name` attribute, using both will show changes on either of the resources alternatively on each apply. + +**Note:** +VPC infrastructure services are a regional specific based endpoint, by default targets to `us-south`. Please make sure to target right region in the provider block as shown in the `provider.tf` file, if VPC service is created in region other than `us-south`. + +**provider.tf** + +```terraform +provider "ibm" { + region = "eu-gb" +} +``` + +## Example usage +Sample to create a reserved IP: + +```terraform +// Create a VPC +resource "ibm_is_vpc" "example" { + name = "example-vpc" +} + +// Create a subnet +resource "ibm_is_subnet" "example" { + name = "example-subnet" + vpc = ibm_is_vpc.example.id + zone = "us-south-1" + total_ipv4_address_count = 256 +} + +resource "ibm_is_subnet_reserved_ip" "example" { + subnet = ibm_is_subnet.example.id +} + +resource "ibm_is_subnet_reserved_ip_patch" "example" { + subnet = ibm_is_subnet.example.id + reserved_ip = ibm_is_subnet_reserved_ip.example.reserved_ip + + name = "test-reserved-ip" + auto_delete = "true" +} +``` + +## Argument reference +Review the argument references that you can specify for your resource. + +- `auto_delete`- (Optional, Bool) If reserved IP is auto deleted. +- `name` - (Required, String) The name of the reserved IP. + + ~> **NOTE:** raise error if name is given with a prefix `ibm- `. +- `subnet` - (Required, Forces new resource, String) The subnet ID for the reserved IP. +- `reserved_ip` - (Required, Forces new resource, string) The ID for the reserved IP. + +## Attribute reference +In addition to all argument reference list, you can access the following attribute reference after your resource is created. + +- `created_at` - (Timestamp) The date and time that the reserved IP was created.", +- `href` - (String) The URL for this reserved IP. +- `id` - (String) The combination of the subnet ID and reserved IP ID, separated by **/**. +- `lifecycle_state` - (String) The lifecycle state of the reserved IP. [ deleting, failed, pending, stable, suspended, updating, waiting ] +- `owner` - (String) The owner of a reserved IP, defining whether it is managed by the user or the provider. +- `reserved_ip` - (String) The reserved IP. +- `resource_type` - (String) The resource type. +- `target` - (String) The ID for the target for the reserved IP. +- `target_crn` - (String) The crn of the target for the reserved IP. + +## Import +The `ibm_is_subnet_reserved_ip_patch` resource can be imported by using subnet ID and reserved IP ID separated by **/**. + +**Syntax** + +``` +$ terraform import ibm_is_subnet_reserved_ip_patch.example / +``` + +**Example** + +``` +$ terraform import ibm_is_subnet_reserved_ip_patch.example 0716-13315ad8-d355-4041-bb60-62342000423/0716-617de4d8-5e2f-4d4a-b0d6-1000023 +``` diff --git a/website/docs/r/logs-router_tenant.html.markdown b/website/docs/r/logs-router_tenant.html.markdown index ecbc7645d5..c15415eb5d 100644 --- a/website/docs/r/logs-router_tenant.html.markdown +++ b/website/docs/r/logs-router_tenant.html.markdown @@ -13,15 +13,29 @@ Create, update, and delete logs_router_tenants with this resource. ## Example Usage ```hcl +resource "ibm_resource_instance" "logs_instance" { + name = "logs-instance" + service = "logs" + plan = "standard" + location = "eu-de" + parameters = { + retention_period = "14" + logs_bucket_crn = "crn:v1:bluemix:public:cloud-object-storage:global:a/4448261269a14562b839e0a3019ed980:f8b3176e-af8e-4e14-a2f9-7f82634e7f0b:bucket:logs-bucket" + logs_bucket_endpoint = "s3.direct.eu-de.cloud-object-storage.appdomain.cloud" + metrics_bucket_crn = "crn:v1:bluemix:public:cloud-object-storage:global:a/4448261269a14562b839e0a3019ed980:f8b3176e-af8e-4e14-a2f9-7f82634e7f0b:bucket:metrics-bucket" + metrics_bucket_endpoint = "s3.direct.eu-de.cloud-object-storage.appdomain.cloud" + } +} + resource "ibm_logs_router_tenant" "logs_router_tenant_instance" { - name = "my-logging-tenant" + name = "cloud-logs-router-tenant" + region = "eu-de" targets { - log_sink_crn = "crn:v1:bluemix:public:logdna:eu-de:a/3516b8fa0a174a71899f5affa4f18d78:3517d2ed-9429-af34-ad52-34278391cbc8::" - name = "my-log-sink" + log_sink_crn = ibm_resource_instance.logs_instance.target_crn + name = "my-cloud-logs-target" parameters { - host = "www.example.com" - port = 1 - access_credential = "credential" + host = ibm_resource_instance.logs_instance.extensions.external_ingress_private + port = 443 } } } @@ -33,14 +47,16 @@ You can specify the following arguments for this resource. * `name` - (Required, String) The name for this tenant. The name is regionally unique across all tenants in the account. * Constraints: The maximum length is `35` characters. The minimum length is `1` character. The value must match regular expression `/[a-z,A-Z,0-9,-,.]/`. +* `region` - (Required, Forces new resource, String) The region to create the tenant. + * Constraints: The value must match one of the available regions. For a list of regions, see the available [IBM Cloud Logs Router Endpoints](https://cloud.ibm.com/docs/logs-router?topic=logs-router-locations). * `targets` - (Required, List) List of targets. * Constraints: The maximum length is `2` items. The minimum length is `1` item. Nested schema for **targets**: - * `log_sink_crn` - (Optional, String) Cloud resource name of the log-sink target instance. + * `log_sink_crn` - (Required, String) Cloud resource name of the log-sink target instance. * Constraints: The maximum length is `256` characters. The minimum length is `1` character. The value must match regular expression `/[a-z,A-Z,0-9,:,-]/`. * `name` - (Optional, String) The name for this tenant target. The name is unique across all targets for this tenant. * Constraints: The maximum length is `35` characters. The minimum length is `1` character. The value must match regular expression `/[a-z,A-Z,0-9,-,.]/`. - * `parameters` - (Optional, List) List of properties returned from a successful list operation for a log-sink of type IBM Log Analysis (logdna). + * `parameters` - (Required, List) List of properties returned from a successful list operation for a log-sink of type IBM Log Analysis (logdna). Nested schema for **parameters**: * `host` - (Required, String) Host name of the log-sink. * Constraints: The maximum length is `256` characters. The minimum length is `1` character. The value must match regular expression `/[a-z,A-Z,0-9,-,.]/`. @@ -71,15 +87,14 @@ After your resource is created, you can read values from the listed arguments an ## Import -You can import the `ibm_logs_router_tenant` resource by using `id`. Unique ID of the tenant. -For more information, see [the documentation](http://cloud.ibm.com) +You can import the `ibm_logs_router_tenant` resource by using `id`, the unique `id` of the tenant, and `region` where the tenant exists in the format `id/region`. # Syntax
-$ terraform import ibm_logs_router_tenant.logs_router_tenant <id>
+$ terraform import ibm_logs_router_tenant.logs_router_tenant <id/region>
 
# Example ``` -$ terraform import ibm_logs_router_tenant.logs_router_tenant 8717db99-2cfb-4ba6-a033-89c994c2e9f0 +$ terraform import ibm_logs_router_tenant.logs_router_tenant 8717db99-2cfb-4ba6-a033-89c994c2e9f0/us-east ``` diff --git a/website/docs/r/policy_assignment.html.markdown b/website/docs/r/policy_assignment.html.markdown index cea35cb8bc..f65e3c172b 100644 --- a/website/docs/r/policy_assignment.html.markdown +++ b/website/docs/r/policy_assignment.html.markdown @@ -73,6 +73,34 @@ resource "ibm_iam_policy_assignment" "policy_assignment" { } template_version=ibm_iam_policy_template_version.template_version.version } + +resource "ibm_iam_policy_assignment" "policy_assignment" { + version ="1.0" + target ={ + type = "Account Group" + id = "" + } + + templates{ + id = ibm_iam_policy_template.policy_s2s_template.template_id + version = ibm_iam_policy_template.policy_s2s_template.version + } + template_version=ibm_iam_policy_template_version.template_version.version +} + +resource "ibm_iam_policy_assignment" "policy_assignment" { + version ="1.0" + target ={ + type = "Enterprise" + id = "" + } + + templates{ + id = ibm_iam_policy_template.policy_s2s_template.template_id + version = ibm_iam_policy_template.policy_s2s_template.version + } + template_version=ibm_iam_policy_template_version.template_version.version +} ``` **Note**: Above configuration is to create policy template versions and assign to a target enterprise account. Update this parameter(***template_version***) and terraform apply again to update the assignment @@ -94,10 +122,18 @@ Nested schema for **target**: * `id` - (Required, String) ID of the target account. * Constraints: The maximum length is `32` characters. The minimum length is `1` character. The value must match regular expression `/^[A-Za-z0-9-]*$/`. * `type` - (Required, String) Assignment target type. - * Constraints: Allowable values are: `Account`. The maximum length is `30` characters. The minimum length is `1` character. + * Constraints: Allowable values are: `Account`, `Account Group` and `Enterprise`. The maximum length is `30` characters. The minimum length is `1` character. * `version` - (Required, String) specify version of response body format. * Constraints: Allowable values are: `1.0`. The minimum length is `1` character. +## Timeouts section + +The resource includes default timeout settings for the following operations: + +* `create` - (Timeout) Defaults to 30 minutes. +* `update` - (Timeout) Defaults to 30 minutes. +* `delete` - (Timeout) Defaults to 30 minutes. + ## Attribute Reference After your resource is created, you can read values from the listed arguments and the following attributes. diff --git a/website/docs/r/resource_access_tag.html.markdown b/website/docs/r/resource_access_tag.html.markdown index 5500d5105f..8917eae134 100644 --- a/website/docs/r/resource_access_tag.html.markdown +++ b/website/docs/r/resource_access_tag.html.markdown @@ -8,6 +8,9 @@ description: |- # ibm_resource_access_tag + ~>**Deprecated:** + The ability to use the ibm_resource_access_tag resource to create or delete IBM Cloud access management tags in Terraform has been removed in favor of a dedicated ibm_iam_access_tag resource. For more information, check out [here](https://registry.terraform.io/providers/IBM-Cloud/ibm/latest/docs/resources/iam_access_tag) + Create, update, or delete IBM Cloud access management tags. For more information, about tagging, see [IBM Cloud access management tags](https://cloud.ibm.com/apidocs/tagging#create-tag). diff --git a/website/docs/r/resource_instance.html.markdown b/website/docs/r/resource_instance.html.markdown index 06757e0765..234f336a8f 100644 --- a/website/docs/r/resource_instance.html.markdown +++ b/website/docs/r/resource_instance.html.markdown @@ -217,8 +217,8 @@ In addition to all argument reference list, you can access the following attribu - `resource_group_crn` - (String) The long ID (full CRN) of the resource group. - `resource_id` - (String) The unique ID of the offering. This value is provided by and stored in the global catalog. - `resource_plan_id` - (String) The unique ID of the plan associated with the offering. This value is provided by and stored in the global catalog. -- `resource_aliases_url` - (String) The relative path to the resource aliases for the instance. -- `resource_bindings_url` - (String) The relative path to the resource bindings for the instance. +- `resource_aliases_url` - (String, Deprecated) The relative path to the resource aliases for the instance. +- `resource_bindings_url` - (String, Deprecated) The relative path to the resource bindings for the instance. - `resource_keys_url` - (String) The relative path to the resource keys for the instance. - `restored_at` - (Timestamp) The date when the instance under reclamation restored. - `restored_by` - (String) The subject who restored the instance back from reclamation. diff --git a/website/docs/r/resource_key.html.markdown b/website/docs/r/resource_key.html.markdown index bbaf88816c..9ff0e2080a 100644 --- a/website/docs/r/resource_key.html.markdown +++ b/website/docs/r/resource_key.html.markdown @@ -139,7 +139,7 @@ Review the argument references that you can specify for your resource. - `parameters` (Optional, Map) Arbitrary parameters to pass to the resource in JSON format. If you want to create service credentials by using the private service endpoint, include the `service-endpoints = "private"` parameter. - `role` - (Optional, Forces new resource, String) The name of the user role. Valid roles are `NONE`,`Writer`, `Reader`, `Manager`, `Administrator`, `Operator`, `Viewer`, and `Editor`. This argument is Optional only during creation of service credentials for Cloud Databases and other non-IAM-enabled services and is Required for all other IAM-enabled services. - `resource_instance_id` - (Optional, Forces new resource, String) The ID of the resource instance associated with the resource key. **Note** Conflicts with `resource_alias_id`. -- `resource_alias_id` - (Optional, Forces new resource, String) The ID of the resource alias associated with the resource key. **Note** Conflicts with `resource_instance_id`. +- `resource_alias_id` - (Optional, Forces new resource, String, Deprecated) The ID of the resource alias associated with the resource key. **Note** Conflicts with `resource_instance_id`. - `tags` (Optional, Array of strings) Tags associated with the resource key instance. **Note** Tags are managed locally and not stored on the IBM Cloud Service Endpoint at this moment. diff --git a/website/docs/r/resource_tag.html.markdown b/website/docs/r/resource_tag.html.markdown index f67194c701..84cc6f229a 100644 --- a/website/docs/r/resource_tag.html.markdown +++ b/website/docs/r/resource_tag.html.markdown @@ -45,7 +45,7 @@ Review the argument references that you can specify for your resource. - `resource_id` - (Required, String) The CRN of the resource on which the tags is be attached. - `resource_type` - (Optional, String) The resource type on which the tags should be attached. -- `tag_type` - (Optional, String) Type of the tag. Supported values are: `user`, `service`, or `access`. The default value is user. +- `tag_type` - (Optional, String) Type of the tag. Supported values are: `user` or `access`. The default value is user. - `tags` - (Required, Array of strings) List of tags associated with resource instance. - `replace` - (Optional, Bool) If true, it indicates that the attaching operation is a replacement operation