diff --git a/go.mod b/go.mod index ce2154c8a3..22b433fccd 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( github.com/IBM/event-notifications-go-admin-sdk v0.21.0 github.com/IBM/eventstreams-go-sdk v1.4.0 github.com/IBM/go-sdk-core/v5 v5.21.0 - github.com/IBM/ibm-backup-recovery-sdk-go v1.0.5 + github.com/IBM/ibm-backup-recovery-sdk-go v1.1.0 github.com/IBM/ibm-cos-sdk-go v1.12.2 github.com/IBM/ibm-cos-sdk-go-config/v2 v2.3.0 github.com/IBM/ibm-hpcs-tke-sdk v0.0.0-20250305134146-e023c2e84762 @@ -46,7 +46,7 @@ require ( github.com/akamai/AkamaiOPEN-edgegrid-golang/v5 v5.0.0 github.com/apache/openwhisk-client-go v0.0.0-20200201143223-a804fb82d105 github.com/apparentlymart/go-cidr v1.1.0 - github.com/go-openapi/strfmt v0.24.1-0.20250928163735-5c9b6bdeb47c + github.com/go-openapi/strfmt v0.25.0 github.com/golang-jwt/jwt/v5 v5.2.2 github.com/google/go-cmp v0.7.0 github.com/google/uuid v1.6.0 @@ -101,7 +101,7 @@ require ( github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-openapi/analysis v0.23.0 // indirect - github.com/go-openapi/errors v0.22.3 // indirect + github.com/go-openapi/errors v0.22.4 // indirect github.com/go-openapi/jsonpointer v0.21.1 // indirect github.com/go-openapi/jsonreference v0.21.0 // indirect github.com/go-openapi/loads v0.22.0 // indirect @@ -194,7 +194,7 @@ require ( github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect github.com/x448/float16 v0.8.4 // indirect github.com/zclconf/go-cty v1.17.0 // indirect - go.mongodb.org/mongo-driver v1.17.4 // indirect + go.mongodb.org/mongo-driver v1.17.6 // indirect go.opentelemetry.io/auto/sdk v1.1.0 // indirect go.opentelemetry.io/otel v1.37.0 // indirect go.opentelemetry.io/otel/metric v1.37.0 // indirect diff --git a/go.sum b/go.sum index c60d0d6019..7e5982102c 100644 --- a/go.sum +++ b/go.sum @@ -127,8 +127,8 @@ github.com/IBM/go-sdk-core/v5 v5.10.2/go.mod h1:WZPFasUzsKab/2mzt29xPcfruSk5js2y github.com/IBM/go-sdk-core/v5 v5.17.4/go.mod h1:KsAAI7eStAWwQa4F96MLy+whYSh39JzNjklZRbN/8ns= github.com/IBM/go-sdk-core/v5 v5.21.0 h1:DUnYhvC4SoC8T84rx5omnhY3+xcQg/Whyoa3mDPIMkk= github.com/IBM/go-sdk-core/v5 v5.21.0/go.mod h1:Q3BYO6iDA2zweQPDGbNTtqft5tDcEpm6RTuqMlPcvbw= -github.com/IBM/ibm-backup-recovery-sdk-go v1.0.5 h1:bVf67pkGi5dp8SQXMcam8c1JrEwNRkXVcz3FkaalmYg= -github.com/IBM/ibm-backup-recovery-sdk-go v1.0.5/go.mod h1:m+7lHOrXJwYPbrdxMmKl96tT7OJMMhpyKnQgnaCcy+w= +github.com/IBM/ibm-backup-recovery-sdk-go v1.1.0 h1:dIMtzTCUqRpbTANTMWLjqBetULO5mwpo2guKKkle37c= +github.com/IBM/ibm-backup-recovery-sdk-go v1.1.0/go.mod h1:W2qIMaQerMNKtseRFyi+UmYAhRQI+YL1VqgWclnYcsI= github.com/IBM/ibm-cos-sdk-go v1.12.2 h1:71A4tDl8u6BZ548h71ecEe7fw5bBA7ECTVqYmeSQWQA= github.com/IBM/ibm-cos-sdk-go v1.12.2/go.mod h1:ODYcmrmdpjo5hVguq9RbD6xmC8xb1XZMG7NefUbJNcc= github.com/IBM/ibm-cos-sdk-go-config/v2 v2.3.0 h1:956Nqk0eKI3lq+AkzWXZDid4UZHRz0wWh1LwkleBsWk= @@ -413,8 +413,8 @@ github.com/go-openapi/errors v0.19.8/go.mod h1:cM//ZKUKyO06HSwqAelJ5NsEMMcpa6VpX github.com/go-openapi/errors v0.20.0/go.mod h1:cM//ZKUKyO06HSwqAelJ5NsEMMcpa6VpXe8DOa1Mi1M= github.com/go-openapi/errors v0.20.2/go.mod h1:cM//ZKUKyO06HSwqAelJ5NsEMMcpa6VpXe8DOa1Mi1M= github.com/go-openapi/errors v0.21.0/go.mod h1:jxNTMUxRCKj65yb/okJGEtahVd7uvWnuWfj53bse4ho= -github.com/go-openapi/errors v0.22.3 h1:k6Hxa5Jg1TUyZnOwV2Lh81j8ayNw5VVYLvKrp4zFKFs= -github.com/go-openapi/errors v0.22.3/go.mod h1:+WvbaBBULWCOna//9B9TbLNGSFOfF8lY9dw4hGiEiKQ= +github.com/go-openapi/errors v0.22.4 h1:oi2K9mHTOb5DPW2Zjdzs/NIvwi2N3fARKaTJLdNabaM= +github.com/go-openapi/errors v0.22.4/go.mod h1:z9S8ASTUqx7+CP1Q8dD8ewGH/1JWFFLX/2PmAYNQLgk= github.com/go-openapi/jsonpointer v0.0.0-20160704185906-46af16f9f7b1/go.mod h1:+35s3my2LFTysnkMfxsJBAMHj/DoqoB9knIWoYG/Vk0= github.com/go-openapi/jsonpointer v0.17.0/go.mod h1:cOnomiV+CVVwFLk0A/MExoFMjwdsUdVpsRhURCKh+3M= github.com/go-openapi/jsonpointer v0.18.0/go.mod h1:cOnomiV+CVVwFLk0A/MExoFMjwdsUdVpsRhURCKh+3M= @@ -459,8 +459,8 @@ github.com/go-openapi/strfmt v0.20.1/go.mod h1:43urheQI9dNtE5lTZQfuFJvjYJKPrxicA github.com/go-openapi/strfmt v0.21.1/go.mod h1:I/XVKeLc5+MM5oPNN7P6urMOpuLXEcNrCX/rPGuWb0k= github.com/go-openapi/strfmt v0.21.3/go.mod h1:k+RzNO0Da+k3FrrynSNN8F7n/peCmQQqbbXjtDfvmGg= github.com/go-openapi/strfmt v0.22.1/go.mod h1:OfVoytIXJasDkkGvkb1Cceb3BPyMOwk1FgmyyEw7NYg= -github.com/go-openapi/strfmt v0.24.1-0.20250928163735-5c9b6bdeb47c h1:2qXCCFMLfKkjdZF/87VmmKUYafETRXdSE/OxrghKAfA= -github.com/go-openapi/strfmt v0.24.1-0.20250928163735-5c9b6bdeb47c/go.mod h1:MXNXmOAf2skBOkUyTR/pzp5/DYMJTE/VHx8zA8kPq1c= +github.com/go-openapi/strfmt v0.25.0 h1:7R0RX7mbKLa9EYCTHRcCuIPcaqlyQiWNPTXwClK0saQ= +github.com/go-openapi/strfmt v0.25.0/go.mod h1:nNXct7OzbwrMY9+5tLX4I21pzcmE6ccMGXl3jFdPfn8= github.com/go-openapi/swag v0.0.0-20160704191624-1d0bd113de87/go.mod h1:DXUve3Dpr1UfpPtxFw+EFuQ41HhCWZfha5jSVRG7C7I= github.com/go-openapi/swag v0.17.0/go.mod h1:AByQ+nYG6gQg71GINrmuDXCPWdL640yX49/kXLo40Tg= github.com/go-openapi/swag v0.18.0/go.mod h1:AByQ+nYG6gQg71GINrmuDXCPWdL640yX49/kXLo40Tg= @@ -468,6 +468,8 @@ github.com/go-openapi/swag v0.19.2/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= github.com/go-openapi/swag v0.23.1 h1:lpsStH0n2ittzTnbaSloVZLuB5+fvSY/+hnagBjSNZU= github.com/go-openapi/swag v0.23.1/go.mod h1:STZs8TbRvEQQKUA+JZNAm3EWlgaOBGpyFDqQnDHMef0= +github.com/go-openapi/testify/v2 v2.0.2 h1:X999g3jeLcoY8qctY/c/Z8iBHTbwLz7R2WXd6Ub6wls= +github.com/go-openapi/testify/v2 v2.0.2/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54= github.com/go-openapi/validate v0.18.0/go.mod h1:Uh4HdOzKt19xGIGm1qHf/ofbX1YQ4Y+MYsct2VUrAJ4= github.com/go-openapi/validate v0.19.2/go.mod h1:1tRCw7m3jtI8eNWEEliiAqUIcBztB2KDnRCRMUi7GTA= github.com/go-openapi/validate v0.19.5/go.mod h1:8DJv2CVJQ6kGNpFW6eV9N3JviE1C85nY1c2z52x1Gk4= @@ -1237,8 +1239,8 @@ go.mongodb.org/mongo-driver v1.7.0/go.mod h1:Q4oFMbo1+MSNqICAdYMlC/zSTrwCogR4R8N go.mongodb.org/mongo-driver v1.7.5/go.mod h1:VXEWRZ6URJIkUq2SCAyapmhH0ZLRBP+FT4xhp5Zvxng= go.mongodb.org/mongo-driver v1.10.0/go.mod h1:wsihk0Kdgv8Kqu1Anit4sfK+22vSFbUrAVEYRhCXrA8= go.mongodb.org/mongo-driver v1.14.0/go.mod h1:Vzb0Mk/pa7e6cWw85R4F/endUC3u0U9jGcNU603k65c= -go.mongodb.org/mongo-driver v1.17.4 h1:jUorfmVzljjr0FLzYQsGP8cgN/qzzxlY9Vh0C9KFXVw= -go.mongodb.org/mongo-driver v1.17.4/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ= +go.mongodb.org/mongo-driver v1.17.6 h1:87JUG1wZfWsr6rIz3ZmpH90rL5tea7O3IHuSwHUpsss= +go.mongodb.org/mongo-driver v1.17.6/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= diff --git a/ibm/conns/config.go b/ibm/conns/config.go index 43bbf5b360..6f09ea9a29 100644 --- a/ibm/conns/config.go +++ b/ibm/conns/config.go @@ -257,6 +257,7 @@ type ClientSession interface { ResourceControllerAPIV2() (controllerv2.ResourceControllerAPIV2, error) BackupRecoveryV1() (*backuprecoveryv1.BackupRecoveryV1, error) BackupRecoveryV1Connector() (*backuprecoveryv1.BackupRecoveryV1Connector, error) + BackupRecoveryManagerV1() (*backuprecoveryv1.BackupRecoveryManagementSreApiV1, error) IBMCloudLogsRoutingV0() (*ibmcloudlogsroutingv0.IBMCloudLogsRoutingV0, error) SoftLayerSession() *slsession.Session IBMPISession() (*ibmpisession.IBMPISession, error) @@ -596,6 +597,9 @@ type clientSession struct { backupRecoveryConnectorClient *backuprecoveryv1.BackupRecoveryV1Connector backupRecoveryConnectorClientErr error + backupRecoveryManagerClient *backuprecoveryv1.BackupRecoveryManagementSreApiV1 + backupRecoveryManagerClientErr error + secretsManagerClient *secretsmanagerv2.SecretsManagerV2 secretsManagerClientErr error @@ -1210,6 +1214,10 @@ func (session clientSession) BackupRecoveryV1Connector() (*backuprecoveryv1.Back return session.backupRecoveryConnectorClient, session.backupRecoveryConnectorClientErr } +func (session clientSession) BackupRecoveryManagerV1() (*backuprecoveryv1.BackupRecoveryManagementSreApiV1, error) { + return session.backupRecoveryManagerClient, session.backupRecoveryManagerClientErr +} + // IBM Cloud Secrets Manager V2 Basic API func (session clientSession) SecretsManagerV2() (*secretsmanagerv2.SecretsManagerV2, error) { return session.secretsManagerClient, session.secretsManagerClientErr @@ -1408,6 +1416,8 @@ func (c *Config) ClientSession() (interface{}, error) { session.resourceControllerErr = errEmptyBluemixCredentials session.backupRecoveryClientErr = errEmptyBluemixCredentials session.backupRecoveryConnectorClientErr = errEmptyBluemixCredentials + session.backupRecoveryManagerClientErr = errEmptyBluemixCredentials + session.backupRecoveryManagerClientErr = errEmptyBluemixCredentials session.catalogManagementClientErr = errEmptyBluemixCredentials session.partnerCenterSellClientErr = errEmptyBluemixCredentials session.ibmpiConfigErr = errEmptyBluemixCredentials @@ -1662,10 +1672,12 @@ func (c *Config) ClientSession() (interface{}, error) { // Construct the service options. var backupRecoveryURL string = "https://default.backup-recovery.cloud.ibm.com/v2" var backupRecoveryConnectorURL string + var backupRecoveryManagerURL string = "https://manager.backup-recovery.cloud.ibm.com/v2" if fileMap != nil && c.Visibility != "public-and-private" { backupRecoveryURL = fileFallBack(fileMap, c.Visibility, "IBMCLOUD_BACKUP_RECOVERY_ENDPOINT", c.Region, backupRecoveryURL) backupRecoveryConnectorURL = fileFallBack(fileMap, c.Visibility, "IBMCLOUD_BACKUP_RECOVERY_CONNECTOR_ENDPOINT", c.Region, backupRecoveryConnectorURL) + backupRecoveryManagerURL = fileFallBack(fileMap, c.Visibility, "IBMCLOUD_BACKUP_RECOVERY_MANAGER_ENDPOINT", c.Region, backupRecoveryConnectorURL) } backupRecoveryClientOptions := &backuprecoveryv1.BackupRecoveryV1Options{ @@ -1710,6 +1722,27 @@ func (c *Config) ClientSession() (interface{}, error) { }) } + var backupRecoveryManagerClientAuthenticator core.Authenticator + backupRecoveryManagerClientAuthenticator = &core.NoAuthAuthenticator{} + + backupRecoveryManagerClientOptions := &backuprecoveryv1.BackupRecoveryManagementSreApiV1Options{ + Authenticator: backupRecoveryManagerClientAuthenticator, + URL: EnvFallBack([]string{"IBMCLOUD_BACKUP_RECOVERY_MANAGER_ENDPOINT"}, backupRecoveryManagerURL), + } + // Construct the service client. + session.backupRecoveryManagerClient, err = backuprecoveryv1.NewBackupRecoveryManagementSreApiV1(backupRecoveryManagerClientOptions) + if err != nil { + session.backupRecoveryManagerClientErr = fmt.Errorf("Error occurred while configuring IBM Backup recovery API service: %q", err) + } + if session.backupRecoveryManagerClient != nil && session.backupRecoveryManagerClient.Service != nil { + // Enable retries for API calls + session.backupRecoveryManagerClient.Service.EnableRetries(c.RetryCount, c.RetryDelay) + // Add custom header for analytics + session.backupRecoveryManagerClient.SetDefaultHeaders(gohttp.Header{ + "X-Original-User-Agent": {fmt.Sprintf("terraform-provider-ibm/%s", version.Version)}, + }) + } + projectEndpoint := project.DefaultServiceURL // Construct an "options" struct for creating the service client. if fileMap != nil && c.Visibility != "public-and-private" { diff --git a/ibm/provider/provider.go b/ibm/provider/provider.go index 34d83422ef..7edf1a8e66 100644 --- a/ibm/provider/provider.go +++ b/ibm/provider/provider.go @@ -267,31 +267,41 @@ func Provider() *schema.Provider { "ibm_config_aggregator_resource_collection_status": configurationaggregator.AddConfigurationAggregatorInstanceFields(configurationaggregator.DataSourceIbmConfigAggregatorResourceCollectionStatus()), // // BackupAndRecovery - "ibm_backup_recovery_agent_upgrade_tasks": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryAgentUpgradeTasks()), - "ibm_backup_recovery_download_agent": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryDownloadAgent()), - "ibm_backup_recovery_search_indexed_object": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoverySearchIndexedObject()), - "ibm_backup_recovery_object_snapshots": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryObjectSnapshots()), - "ibm_backup_recovery_connectors_metadata": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryConnectorsMetadata()), - "ibm_backup_recovery_connector_logs": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryConnectorLogs()), - "ibm_backup_recovery_connector_status": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryConnectorStatus()), - "ibm_backup_recovery_data_source_connections": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryDataSourceConnections()), - "ibm_backup_recovery_data_source_connectors": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryDataSourceConnectors()), - "ibm_backup_recovery_search_objects": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoverySearchObjects()), - "ibm_backup_recovery_search_protected_objects": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoverySearchProtectedObjects()), - "ibm_backup_recovery_protection_group": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryProtectionGroup()), - "ibm_backup_recovery_protection_groups": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryProtectionGroups()), - "ibm_backup_recovery_protection_group_runs": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryProtectionGroupRuns()), - "ibm_backup_recovery_protection_policies": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryProtectionPolicies()), - "ibm_backup_recovery_protection_policy": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryProtectionPolicy()), - "ibm_backup_recovery": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecovery()), - "ibm_backup_recoveries": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveries()), - "ibm_backup_recovery_download_files": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryDownloadFiles()), - "ibm_backup_recovery_source_registrations": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoverySourceRegistrations()), - "ibm_backup_recovery_source_registration": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoverySourceRegistration()), - "ibm_backup_recovery_download_indexed_files": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryDownloadIndexedFiles()), - "ibm_backup_recovery_protection_sources": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryProtectionSources()), - "ibm_backup_recovery_connector_get_users": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryConnectorGetUsers()), - "ibm_backup_recovery_registration_info": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryRegistrationInfo()), + "ibm_backup_recovery_agent_upgrade_tasks": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryAgentUpgradeTasks()), + "ibm_backup_recovery_download_agent": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryDownloadAgent()), + "ibm_backup_recovery_search_indexed_object": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoverySearchIndexedObject()), + "ibm_backup_recovery_object_snapshots": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryObjectSnapshots()), + "ibm_backup_recovery_connectors_metadata": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryConnectorsMetadata()), + "ibm_backup_recovery_connector_logs": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryConnectorLogs()), + "ibm_backup_recovery_connector_status": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryConnectorStatus()), + "ibm_backup_recovery_data_source_connections": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryDataSourceConnections()), + "ibm_backup_recovery_data_source_connectors": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryDataSourceConnectors()), + "ibm_backup_recovery_search_objects": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoverySearchObjects()), + "ibm_backup_recovery_search_protected_objects": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoverySearchProtectedObjects()), + "ibm_backup_recovery_protection_group": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryProtectionGroup()), + "ibm_backup_recovery_protection_groups": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryProtectionGroups()), + "ibm_backup_recovery_protection_group_runs": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryProtectionGroupRuns()), + "ibm_backup_recovery_protection_policies": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryProtectionPolicies()), + "ibm_backup_recovery_protection_policy": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryProtectionPolicy()), + "ibm_backup_recovery": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecovery()), + "ibm_backup_recoveries": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveries()), + "ibm_backup_recovery_download_files": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryDownloadFiles()), + "ibm_backup_recovery_source_registrations": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoverySourceRegistrations()), + "ibm_backup_recovery_source_registration": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoverySourceRegistration()), + "ibm_backup_recovery_download_indexed_files": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryDownloadIndexedFiles()), + "ibm_backup_recovery_protection_sources": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryProtectionSources()), + "ibm_backup_recovery_connector_get_users": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryConnectorGetUsers()), + "ibm_backup_recovery_registration_info": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryRegistrationInfo()), + "ibm_backup_recovery_manager_get_management_alerts": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryManagerGetManagementAlerts()), + "ibm_backup_recovery_manager_get_alerts_stats": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryManagerGetAlertsStats()), + "ibm_backup_recovery_manager_get_alerts_resolution": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryManagerGetAlertsResolution()), + "ibm_backup_recovery_manager_get_alerts_summary": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryManagerGetAlertsSummary()), + "ibm_backup_recovery_manager_get_management_alerts_summary": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryManagerGetManagementAlertsSummary()), + "ibm_backup_recovery_manager_get_alerts": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryManagerGetAlerts()), + "ibm_backup_recovery_manager_get_upgrades_info": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryManagerGetUpgradesInfo()), + "ibm_backup_recovery_manager_get_compatible_clusters": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryManagerGetCompatibleClusters()), + "ibm_backup_recovery_manager_get_cluster_info": backuprecovery.AddInstanceFields(backuprecovery.DataSourceIbmBackupRecoveryManagerGetClusterInfo()), + // // AppID "ibm_appid_action_url": appid.DataSourceIBMAppIDActionURL(), "ibm_appid_apm": appid.DataSourceIBMAppIDAPM(), @@ -1170,6 +1180,9 @@ func Provider() *schema.Provider { "ibm_backup_recovery_connector_registration": backuprecovery.AddInstanceFields(backuprecovery.ResourceIbmBackupRecoveryConnectorRegistration()), "ibm_backup_recovery_connector_access_token": backuprecovery.AddInstanceFields(backuprecovery.ResourceIbmBackupRecoveryConnectorAccessToken()), "ibm_backup_recovery_connector_update_user": backuprecovery.AddInstanceFields(backuprecovery.ResourceIbmBackupRecoveryConnectorUpdateUser()), + "ibm_backup_recovery_manager_create_cluster_upgrades": backuprecovery.AddInstanceFields(backuprecovery.ResourceIbmBackupRecoveryManagerCreateClusterUpgrades()), + "ibm_backup_recovery_manager_update_cluster_upgrades": backuprecovery.AddInstanceFields(backuprecovery.ResourceIbmBackupRecoveryManagerUpdateClusterUpgrades()), + "ibm_backup_recovery_manager_cancel_cluster_upgrades": backuprecovery.AddInstanceFields(backuprecovery.ResourceIbmBackupRecoveryManagerCancelClusterUpgrades()), "ibm_app": cloudfoundry.ResourceIBMApp(), "ibm_app_domain_private": cloudfoundry.ResourceIBMAppDomainPrivate(), diff --git a/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_alerts.go b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_alerts.go new file mode 100644 index 0000000000..b77fdaab0f --- /dev/null +++ b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_alerts.go @@ -0,0 +1,681 @@ +// Copyright IBM Corp. 2025 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.96.1-5136e54a-20241108-203028 + */ + +package backuprecovery + +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-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" + "github.com/IBM/ibm-backup-recovery-sdk-go/backuprecoveryv1" +) + +func DataSourceIbmBackupRecoveryManagerGetAlerts() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmBackupRecoveryManagerGetAlertsRead, + + Schema: map[string]*schema.Schema{ + "alert_ids": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Filter by list of alert ids.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "alert_types": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Filter by list of alert types.", + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "alert_categories": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Filter by list of alert categories.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "alert_states": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Filter by list of alert states.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "alert_severities": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Filter by list of alert severity types.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "alert_type_buckets": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Filter by list of alert type buckets.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "start_time_usecs": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Description: "Specifies start time Unix epoch time in microseconds to filter alerts by.", + }, + "end_time_usecs": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Description: "Specifies end time Unix epoch time in microseconds to filter alerts by.", + }, + "max_alerts": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Description: "Specifies maximum number of alerts to return.The default value is 100 and maximum allowed value is 1000.", + }, + "property_key": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "Specifies name of the property to filter alerts by.", + }, + "property_value": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "Specifies value of the property to filter alerts by.", + }, + "alert_name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "Specifies name of alert to filter alerts by.", + }, + "resolution_ids": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Specifies alert resolution ids to filter alerts by.", + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "tenant_ids": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Filter by tenant ids.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "all_under_hierarchy": &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + Description: "Filter by objects of all the tenants under the hierarchy of the logged in user's organization.", + }, + "x_scope_identifier": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "This field uniquely represents a service instance. Please specify the values as \"service-instance-id: \".", + }, + "alerts": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies the list of alerts.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "alert_category": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the alert category.", + }, + "alert_code": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies a unique code that categorizes the Alert, for example: CE00200014, where CE stands for IBM Error, the alert state next 3 digits is the id of the Alert Category (e.g. 002 for 'kNode') and the last 5 digits is the id of the Alert Type (e.g. 00014 for 'kNodeHighCpuUsage').", + }, + "alert_document": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies the fields of alert document.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "alert_cause": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the cause of alert.", + }, + "alert_description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the description of alert.", + }, + "alert_help_text": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the help text for alert.", + }, + "alert_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the name of alert.", + }, + "alert_summary": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Short description for the alert.", + }, + }, + }, + }, + "alert_state": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the alert state.", + }, + "alert_type": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the alert type.", + }, + "alert_type_bucket": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the Alert type bucket.", + }, + "cluster_id": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Id of the cluster which the alert is associated.", + }, + "cluster_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the name of cluster which alert is raised from.", + }, + "dedup_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the dedup count of alert.", + }, + "dedup_timestamps": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies Unix epoch Timestamps (in microseconds) for the last 25 occurrences of duplicated Alerts that are stored with the original/primary Alert. Alerts are grouped into one Alert if the Alerts are the same type, are reporting on the same Object and occur within one hour. 'dedupCount' always reports the total count of duplicated Alerts even if there are more than 25 occurrences. For example, if there are 100 occurrences of this Alert, dedupTimestamps stores the timestamps of the last 25 occurrences and dedupCount equals 100.", + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "event_source": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies source where the event occurred.", + }, + "first_timestamp_usecs": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies Unix epoch Timestamp (in microseconds) of the first occurrence of the Alert.", + }, + "id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies unique id of the alert.", + }, + "label_ids": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies the labels for which this alert has been raised.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "latest_timestamp_usecs": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies Unix epoch Timestamp (in microseconds) of the most recent occurrence of the Alert.", + }, + "property_list": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "List of property key and values associated with alert.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "key": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Key of the Label.", + }, + "value": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Value of the Label, multiple values should be joined by '|'.", + }, + }, + }, + }, + "region_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the region id of the alert.", + }, + "resolution_details": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies information about the Alert Resolution.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "resolution_details": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies detailed notes about the Resolution.", + }, + "resolution_id": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the unique resolution id assigned in management console.", + }, + "resolution_summary": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies short description about the Resolution.", + }, + "timestamp_usecs": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies unix epoch timestamp (in microseconds) when the Alert was resolved.", + }, + "user_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies name of the IBM Cluster user who resolved the Alerts.", + }, + }, + }, + }, + "resolution_id_string": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Resolution Id String.", + }, + "resolved_timestamp_usecs": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies Unix epoch Timestamps in microseconds when alert is resolved.", + }, + "severity": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the alert severity.", + }, + "suppression_id": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies unique id generated when the Alert is suppressed by the admin.", + }, + "tenant_ids": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies the tenants for which this alert has been raised.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "vaults": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies information about vaults where source object associated with alert is vaulted. This could be empty if alert is not related to any source object or it is not vaulted.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "global_vault_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies Global vault id.", + }, + "region_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies id of region where vault resides.", + }, + "region_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies name of region where vault resides.", + }, + "vault_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies name of vault.", + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func dataSourceIbmBackupRecoveryManagerGetAlertsRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + managementApiClient, err := meta.(conns.ClientSession).BackupRecoveryManagerV1() + if err != nil { + tfErr := flex.DiscriminatedTerraformErrorf(err, err.Error(), "(Data) ibm_backup_recovery_manager_get_alerts", "read", "initialize-client") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + bmxsession, err := meta.(conns.ClientSession).BluemixSession() + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("unable to get clientSession"), "ibm_backup_recovery_manager_get_alerts", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + endpointType := d.Get("endpoint_type").(string) + instanceId, region := getInstanceIdAndRegion(d) + managementApiClient, err = setManagerClientAuth(managementApiClient, bmxsession, region, endpointType) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("unable to set authenticator for clientSession: %s", err), "ibm_backup_recovery_manager_get_alerts", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + if instanceId != "" { + managementApiClient = getManagerClientWithInstanceEndpoint(managementApiClient, bmxsession, instanceId, region, endpointType) + } + + getAlertsOptions := &backuprecoveryv1.GetAlertsOptions{} + + if _, ok := d.GetOk("alert_ids"); ok { + var alertIds []string + for _, v := range d.Get("alert_ids").([]interface{}) { + alertIdsItem := v.(string) + alertIds = append(alertIds, alertIdsItem) + } + getAlertsOptions.SetAlertIds(alertIds) + } + if _, ok := d.GetOk("alert_types"); ok { + var alertTypes []int64 + for _, v := range d.Get("alert_types").([]interface{}) { + alertTypesItem := int64(v.(int)) + alertTypes = append(alertTypes, alertTypesItem) + } + getAlertsOptions.SetAlertTypes(alertTypes) + } + if _, ok := d.GetOk("alert_categories"); ok { + var alertCategories []string + for _, v := range d.Get("alert_categories").([]interface{}) { + alertCategoriesItem := v.(string) + alertCategories = append(alertCategories, alertCategoriesItem) + } + getAlertsOptions.SetAlertCategories(alertCategories) + } + if _, ok := d.GetOk("alert_states"); ok { + var alertStates []string + for _, v := range d.Get("alert_states").([]interface{}) { + alertStatesItem := v.(string) + alertStates = append(alertStates, alertStatesItem) + } + getAlertsOptions.SetAlertStates(alertStates) + } + if _, ok := d.GetOk("alert_severities"); ok { + var alertSeverities []string + for _, v := range d.Get("alert_severities").([]interface{}) { + alertSeveritiesItem := v.(string) + alertSeverities = append(alertSeverities, alertSeveritiesItem) + } + getAlertsOptions.SetAlertSeverities(alertSeverities) + } + if _, ok := d.GetOk("alert_type_buckets"); ok { + var alertTypeBuckets []string + for _, v := range d.Get("alert_type_buckets").([]interface{}) { + alertTypeBucketsItem := v.(string) + alertTypeBuckets = append(alertTypeBuckets, alertTypeBucketsItem) + } + getAlertsOptions.SetAlertTypeBuckets(alertTypeBuckets) + } + if _, ok := d.GetOk("start_time_usecs"); ok { + getAlertsOptions.SetStartTimeUsecs(int64(d.Get("start_time_usecs").(int))) + } + if _, ok := d.GetOk("end_time_usecs"); ok { + getAlertsOptions.SetEndTimeUsecs(int64(d.Get("end_time_usecs").(int))) + } + if _, ok := d.GetOk("max_alerts"); ok { + getAlertsOptions.SetMaxAlerts(int64(d.Get("max_alerts").(int))) + } + if _, ok := d.GetOk("property_key"); ok { + getAlertsOptions.SetPropertyKey(d.Get("property_key").(string)) + } + if _, ok := d.GetOk("property_value"); ok { + getAlertsOptions.SetPropertyValue(d.Get("property_value").(string)) + } + if _, ok := d.GetOk("alert_name"); ok { + getAlertsOptions.SetAlertName(d.Get("alert_name").(string)) + } + if _, ok := d.GetOk("resolution_ids"); ok { + var resolutionIds []int64 + for _, v := range d.Get("resolution_ids").([]interface{}) { + resolutionIdsItem := int64(v.(int)) + resolutionIds = append(resolutionIds, resolutionIdsItem) + } + getAlertsOptions.SetResolutionIds(resolutionIds) + } + if _, ok := d.GetOk("tenant_ids"); ok { + var tenantIds []string + for _, v := range d.Get("tenant_ids").([]interface{}) { + tenantIdsItem := v.(string) + tenantIds = append(tenantIds, tenantIdsItem) + } + getAlertsOptions.SetTenantIds(tenantIds) + } + if _, ok := d.GetOk("all_under_hierarchy"); ok { + getAlertsOptions.SetAllUnderHierarchy(d.Get("all_under_hierarchy").(bool)) + } + if _, ok := d.GetOk("x_scope_identifier"); ok { + getAlertsOptions.SetXScopeIdentifier(d.Get("x_scope_identifier").(string)) + } + + alertList, _, err := managementApiClient.GetAlertsWithContext(context, getAlertsOptions) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetAlertsWithContext failed: %s", err.Error()), "(Data) ibm_backup_recovery_manager_get_alerts", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + d.SetId(dataSourceIbmBackupRecoveryManagerGetAlertsID(d)) + + alerts := []map[string]interface{}{} + for _, alertsItem := range alertList.Alerts { + alertsItemMap, err := DataSourceIbmBackupRecoveryManagerGetAlertsAlertInfoToMap(&alertsItem) // #nosec G601 + if err != nil { + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "(Data) ibm_backup_recovery_manager_get_alerts", "read", "alerts-to-map").GetDiag() + } + alerts = append(alerts, alertsItemMap) + } + if err = d.Set("alerts", alerts); err != nil { + return flex.DiscriminatedTerraformErrorf(err, fmt.Sprintf("Error setting alerts: %s", err), "(Data) ibm_backup_recovery_manager_get_alerts", "read", "set-alerts").GetDiag() + } + + return nil +} + +// dataSourceIbmBackupRecoveryManagerGetAlertsID returns a reasonable ID for the list. +func dataSourceIbmBackupRecoveryManagerGetAlertsID(d *schema.ResourceData) string { + return time.Now().UTC().String() +} + +func DataSourceIbmBackupRecoveryManagerGetAlertsAlertInfoToMap(model *backuprecoveryv1.AlertInfo) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.AlertCategory != nil { + modelMap["alert_category"] = *model.AlertCategory + } + if model.AlertCode != nil { + modelMap["alert_code"] = *model.AlertCode + } + if model.AlertDocument != nil { + alertDocumentMap, err := DataSourceIbmBackupRecoveryManagerGetAlertsAlertDocumentToMap(model.AlertDocument) + if err != nil { + return modelMap, err + } + modelMap["alert_document"] = []map[string]interface{}{alertDocumentMap} + } + if model.AlertState != nil { + modelMap["alert_state"] = *model.AlertState + } + if model.AlertType != nil { + modelMap["alert_type"] = flex.IntValue(model.AlertType) + } + if model.AlertTypeBucket != nil { + modelMap["alert_type_bucket"] = *model.AlertTypeBucket + } + if model.ClusterID != nil { + modelMap["cluster_id"] = flex.IntValue(model.ClusterID) + } + if model.ClusterName != nil { + modelMap["cluster_name"] = *model.ClusterName + } + if model.DedupCount != nil { + modelMap["dedup_count"] = flex.IntValue(model.DedupCount) + } + if model.DedupTimestamps != nil { + modelMap["dedup_timestamps"] = model.DedupTimestamps + } + if model.EventSource != nil { + modelMap["event_source"] = *model.EventSource + } + if model.FirstTimestampUsecs != nil { + modelMap["first_timestamp_usecs"] = flex.IntValue(model.FirstTimestampUsecs) + } + if model.ID != nil { + modelMap["id"] = *model.ID + } + if model.LabelIds != nil { + modelMap["label_ids"] = model.LabelIds + } + if model.LatestTimestampUsecs != nil { + modelMap["latest_timestamp_usecs"] = flex.IntValue(model.LatestTimestampUsecs) + } + if model.PropertyList != nil { + propertyList := []map[string]interface{}{} + for _, propertyListItem := range model.PropertyList { + propertyListItemMap, err := DataSourceIbmBackupRecoveryManagerGetAlertsLabelToMap(&propertyListItem) // #nosec G601 + if err != nil { + return modelMap, err + } + propertyList = append(propertyList, propertyListItemMap) + } + modelMap["property_list"] = propertyList + } + if model.RegionID != nil { + modelMap["region_id"] = *model.RegionID + } + if model.ResolutionDetails != nil { + resolutionDetailsMap, err := DataSourceIbmBackupRecoveryManagerGetAlertsAlertResolutionDetailsToMap(model.ResolutionDetails) + if err != nil { + return modelMap, err + } + modelMap["resolution_details"] = []map[string]interface{}{resolutionDetailsMap} + } + if model.ResolutionIdString != nil { + modelMap["resolution_id_string"] = *model.ResolutionIdString + } + if model.ResolvedTimestampUsecs != nil { + modelMap["resolved_timestamp_usecs"] = flex.IntValue(model.ResolvedTimestampUsecs) + } + if model.Severity != nil { + modelMap["severity"] = *model.Severity + } + if model.SuppressionID != nil { + modelMap["suppression_id"] = flex.IntValue(model.SuppressionID) + } + if model.TenantIds != nil { + modelMap["tenant_ids"] = model.TenantIds + } + if model.Vaults != nil { + vaults := []map[string]interface{}{} + for _, vaultsItem := range model.Vaults { + vaultsItemMap, err := DataSourceIbmBackupRecoveryManagerGetAlertsVaultToMap(&vaultsItem) // #nosec G601 + if err != nil { + return modelMap, err + } + vaults = append(vaults, vaultsItemMap) + } + modelMap["vaults"] = vaults + } + return modelMap, nil +} + +func DataSourceIbmBackupRecoveryManagerGetAlertsAlertDocumentToMap(model *backuprecoveryv1.AlertDocument) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.AlertCause != nil { + modelMap["alert_cause"] = *model.AlertCause + } + if model.AlertDescription != nil { + modelMap["alert_description"] = *model.AlertDescription + } + if model.AlertHelpText != nil { + modelMap["alert_help_text"] = *model.AlertHelpText + } + if model.AlertName != nil { + modelMap["alert_name"] = *model.AlertName + } + if model.AlertSummary != nil { + modelMap["alert_summary"] = *model.AlertSummary + } + return modelMap, nil +} + +func DataSourceIbmBackupRecoveryManagerGetAlertsLabelToMap(model *backuprecoveryv1.Label) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + modelMap["key"] = *model.Key + modelMap["value"] = *model.Value + return modelMap, nil +} + +func DataSourceIbmBackupRecoveryManagerGetAlertsAlertResolutionDetailsToMap(model *backuprecoveryv1.AlertResolutionDetails) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ResolutionDetails != nil { + modelMap["resolution_details"] = *model.ResolutionDetails + } + if model.ResolutionID != nil { + modelMap["resolution_id"] = flex.IntValue(model.ResolutionID) + } + if model.ResolutionSummary != nil { + modelMap["resolution_summary"] = *model.ResolutionSummary + } + if model.TimestampUsecs != nil { + modelMap["timestamp_usecs"] = flex.IntValue(model.TimestampUsecs) + } + if model.UserName != nil { + modelMap["user_name"] = *model.UserName + } + return modelMap, nil +} + +func DataSourceIbmBackupRecoveryManagerGetAlertsVaultToMap(model *backuprecoveryv1.Vault) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.GlobalVaultID != nil { + modelMap["global_vault_id"] = *model.GlobalVaultID + } + if model.RegionID != nil { + modelMap["region_id"] = *model.RegionID + } + if model.RegionName != nil { + modelMap["region_name"] = *model.RegionName + } + if model.VaultName != nil { + modelMap["vault_name"] = *model.VaultName + } + return modelMap, nil +} diff --git a/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_alerts_resolution.go b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_alerts_resolution.go new file mode 100644 index 0000000000..55b7025db0 --- /dev/null +++ b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_alerts_resolution.go @@ -0,0 +1,272 @@ +// Copyright IBM Corp. 2025 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.96.1-5136e54a-20241108-203028 + */ + +package backuprecovery + +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-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/ibm-backup-recovery-sdk-go/backuprecoveryv1" +) + +func DataSourceIbmBackupRecoveryManagerGetAlertsResolution() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmBackupRecoveryManagerGetAlertsResolutionRead, + + Schema: map[string]*schema.Schema{ + "max_resolutions": &schema.Schema{ + Type: schema.TypeInt, + Required: true, + Description: "Specifies the max number of Resolutions to be returned, from the latest created to the earliest created.", + }, + "resolution_name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "Specifies Alert Resolution Name to query.", + }, + "resolution_id": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "Specifies Alert Resolution id to query.", + }, + "alert_resolutions_list": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "List of alert resolutions.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies account id of the user who create the resolution.", + }, + "created_time_usecs": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies unix epoch timestamp (in microseconds) when the resolution is created.", + }, + "description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the full description about the Resolution.", + }, + "external_key": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the external key assigned outside of management console, with the form of \"clusterid:resolutionid\".", + }, + "resolution_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the unique reslution id assigned in management console.", + }, + "resolution_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the unique name of the resolution.", + }, + "resolved_alerts": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "alert_id": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Id of the alert.", + }, + "alert_id_str": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Alert Id with string format.", + }, + "alert_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Name of the alert being resolved.", + }, + "cluster_id": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Id of the cluster which the alert is associated.", + }, + "first_timestamp_usecs": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "First occurrence of the alert.", + }, + "resolved_time_usec": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + }, + "service_instance_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Id of the service instance which the alert is associated.", + }, + }, + }, + }, + "silence_minutes": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the time duration (in minutes) for silencing alerts. If unspecified or set zero, a silence rule will be created with default expiry time. No silence rule will be created if value < 0.", + }, + "tenant_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies tenant id of the user who create the resolution.", + }, + }, + }, + }, + }, + } +} + +func dataSourceIbmBackupRecoveryManagerGetAlertsResolutionRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + managementApiClient, err := meta.(conns.ClientSession).BackupRecoveryManagerV1() + if err != nil { + tfErr := flex.DiscriminatedTerraformErrorf(err, err.Error(), "(Data) ibm_backup_recovery_manager_get_alerts_resolution", "read", "initialize-client") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + bmxsession, err := meta.(conns.ClientSession).BluemixSession() + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("unable to get clientSession"), "ibm_backup_recovery_manager_get_alerts_resolution", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + endpointType := d.Get("endpoint_type").(string) + instanceId, region := getInstanceIdAndRegion(d) + managementApiClient, err = setManagerClientAuth(managementApiClient, bmxsession, region, endpointType) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("unable to set authenticator for clientSession: %s", err), "ibm_backup_recovery_manager_get_alerts_resolution", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + if instanceId != "" { + managementApiClient = getManagerClientWithInstanceEndpoint(managementApiClient, bmxsession, instanceId, region, endpointType) + } + + getManagementAlertResolutionOptions := &backuprecoveryv1.GetManagementAlertResolutionOptions{} + + getManagementAlertResolutionOptions.SetMaxResolutions(int64(d.Get("max_resolutions").(int))) + if _, ok := d.GetOk("resolution_name"); ok { + getManagementAlertResolutionOptions.SetResolutionName(d.Get("resolution_name").(string)) + } + if _, ok := d.GetOk("resolution_id"); ok { + getManagementAlertResolutionOptions.SetResolutionID(d.Get("resolution_id").(string)) + } + + alertResolutionsList, _, err := managementApiClient.GetManagementAlertResolutionWithContext(context, getManagementAlertResolutionOptions) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetManagementAlertResolutionWithContext failed: %s", err.Error()), "(Data) ibm_backup_recovery_manager_get_alerts_resolution", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + d.SetId(dataSourceIbmBackupRecoveryManagerGetAlertsResolutionID(d)) + + if !core.IsNil(alertResolutionsList.AlertResolutionsList) { + alertResolutionsListResult := []map[string]interface{}{} + for _, alertResolutionsListItem := range alertResolutionsList.AlertResolutionsList { + alertResolutionsListItemMap, err := DataSourceIbmBackupRecoveryManagerGetAlertsResolutionAlertResolutionToMap(&alertResolutionsListItem) // #nosec G601 + if err != nil { + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "(Data) ibm_backup_recovery_manager_get_alerts_resolution", "read", "alert_resolutions_list-to-map").GetDiag() + } + alertResolutionsListResult = append(alertResolutionsListResult, alertResolutionsListItemMap) + } + if err = d.Set("alert_resolutions_list", alertResolutionsListResult); err != nil { + return flex.DiscriminatedTerraformErrorf(err, fmt.Sprintf("Error setting alert_resolutions_list: %s", err), "(Data) ibm_backup_recovery_manager_get_alerts_resolution", "read", "set-alert_resolutions_list").GetDiag() + } + } + + return nil +} + +// dataSourceIbmBackupRecoveryManagerGetAlertsResolutionID returns a reasonable ID for the list. +func dataSourceIbmBackupRecoveryManagerGetAlertsResolutionID(d *schema.ResourceData) string { + return time.Now().UTC().String() +} + +func DataSourceIbmBackupRecoveryManagerGetAlertsResolutionAlertResolutionToMap(model *backuprecoveryv1.AlertResolution) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.AccountID != nil { + modelMap["account_id"] = *model.AccountID + } + if model.CreatedTimeUsecs != nil { + modelMap["created_time_usecs"] = flex.IntValue(model.CreatedTimeUsecs) + } + if model.Description != nil { + modelMap["description"] = *model.Description + } + if model.ExternalKey != nil { + modelMap["external_key"] = *model.ExternalKey + } + if model.ResolutionID != nil { + modelMap["resolution_id"] = *model.ResolutionID + } + if model.ResolutionName != nil { + modelMap["resolution_name"] = *model.ResolutionName + } + if model.ResolvedAlerts != nil { + resolvedAlerts := []map[string]interface{}{} + for _, resolvedAlertsItem := range model.ResolvedAlerts { + resolvedAlertsItemMap, err := DataSourceIbmBackupRecoveryManagerGetAlertsResolutionResolvedAlertInfoToMap(&resolvedAlertsItem) // #nosec G601 + if err != nil { + return modelMap, err + } + resolvedAlerts = append(resolvedAlerts, resolvedAlertsItemMap) + } + modelMap["resolved_alerts"] = resolvedAlerts + } + if model.SilenceMinutes != nil { + modelMap["silence_minutes"] = flex.IntValue(model.SilenceMinutes) + } + if model.TenantID != nil { + modelMap["tenant_id"] = *model.TenantID + } + return modelMap, nil +} + +func DataSourceIbmBackupRecoveryManagerGetAlertsResolutionResolvedAlertInfoToMap(model *backuprecoveryv1.ResolvedAlertInfo) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.AlertID != nil { + modelMap["alert_id"] = flex.IntValue(model.AlertID) + } + if model.AlertIdStr != nil { + modelMap["alert_id_str"] = *model.AlertIdStr + } + if model.AlertName != nil { + modelMap["alert_name"] = *model.AlertName + } + if model.ClusterID != nil { + modelMap["cluster_id"] = flex.IntValue(model.ClusterID) + } + if model.FirstTimestampUsecs != nil { + modelMap["first_timestamp_usecs"] = flex.IntValue(model.FirstTimestampUsecs) + } + if model.ResolvedTimeUsec != nil { + modelMap["resolved_time_usec"] = flex.IntValue(model.ResolvedTimeUsec) + } + if model.ServiceInstanceID != nil { + modelMap["service_instance_id"] = *model.ServiceInstanceID + } + return modelMap, nil +} diff --git a/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_alerts_resolution_test.go b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_alerts_resolution_test.go new file mode 100644 index 0000000000..3f6455e280 --- /dev/null +++ b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_alerts_resolution_test.go @@ -0,0 +1,41 @@ +// Copyright IBM Corp. 2025 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.96.1-5136e54a-20241108-203028 + */ + +package backuprecovery_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmBackupRecoveryManagerGetAlertsResolutionDataSourceBasic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmBackupRecoveryManagerGetAlertsResolutionDataSourceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_backup_recovery_manager_get_alerts_resolution.backup_recovery_manager_get_alerts_resolution_instance", "id"), + resource.TestCheckResourceAttrSet("data.ibm_backup_recovery_manager_get_alerts_resolution.backup_recovery_manager_get_alerts_resolution_instance", "max_resolutions"), + ), + }, + }, + }) +} + +func testAccCheckIbmBackupRecoveryManagerGetAlertsResolutionDataSourceConfigBasic() string { + return fmt.Sprintf(` + data "ibm_backup_recovery_manager_get_alerts_resolution" "backup_recovery_manager_get_alerts_resolution_instance" { + max_resolutions = 1 + } + `) +} diff --git a/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_alerts_stats.go b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_alerts_stats.go new file mode 100644 index 0000000000..f7a822ae14 --- /dev/null +++ b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_alerts_stats.go @@ -0,0 +1,593 @@ +// Copyright IBM Corp. 2025 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.96.1-5136e54a-20241108-203028 + */ + +package backuprecovery + +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-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/ibm-backup-recovery-sdk-go/backuprecoveryv1" +) + +func DataSourceIbmBackupRecoveryManagerGetAlertsStats() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmBackupRecoveryManagerGetAlertsStatsRead, + + Schema: map[string]*schema.Schema{ + "start_time_usecs": &schema.Schema{ + Type: schema.TypeInt, + Required: true, + Description: "Specifies the start time Unix time epoch in microseconds from which the active alerts stats are computed.", + }, + "end_time_usecs": &schema.Schema{ + Type: schema.TypeInt, + Required: true, + Description: "Specifies the end time Unix time epoch in microseconds to which the active alerts stats are computed.", + }, + "cluster_ids": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Specifies the list of cluster IDs.", + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "service_instance_ids": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Specifies list of service instance ids to filter alert stats by.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "region_ids": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Filter by a list of region ids.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "exclude_stats_by_cluster": &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + Description: "Specifies if stats of active alerts per cluster needs to be excluded. If set to false (default value), stats of active alerts per cluster is included in the response. If set to true, only aggregated stats summary will be present in the response.", + }, + "alert_source": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "Specifies a list of alert origination source. If not specified, all alerts from all the sources are considered in the response.", + }, + "tenant_ids": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Specifies a list of tenants.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "aggregated_alerts_stats": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies the active alert statistics details.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "num_critical_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active critical Alerts excluding alerts that belong to other bucket.", + }, + "num_critical_alerts_categories": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active critical alerts categories.", + }, + "num_data_service_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active service Alerts.", + }, + "num_data_service_critical_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active service critical Alerts.", + }, + "num_data_service_info_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active service info Alerts.", + }, + "num_data_service_warning_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active service warning Alerts.", + }, + "num_hardware_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active hardware Alerts.", + }, + "num_hardware_critical_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active hardware critical Alerts.", + }, + "num_hardware_info_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active hardware info Alerts.", + }, + "num_hardware_warning_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active hardware warning Alerts.", + }, + "num_info_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active info Alerts excluding alerts that belong to other bucket.", + }, + "num_info_alerts_categories": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active info alerts categories.", + }, + "num_maintenance_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active Alerts of maintenance bucket.", + }, + "num_maintenance_critical_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active other critical Alerts.", + }, + "num_maintenance_info_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active other info Alerts.", + }, + "num_maintenance_warning_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active other warning Alerts.", + }, + "num_software_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active software Alerts.", + }, + "num_software_critical_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active software critical Alerts.", + }, + "num_software_info_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active software info Alerts.", + }, + "num_software_warning_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active software warning Alerts.", + }, + "num_warning_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active warning Alerts excluding alerts that belong to other bucket.", + }, + "num_warning_alerts_categories": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active warning alerts categories.", + }, + }, + }, + }, + "aggregated_cluster_stats": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies the cluster statistics based on active alerts.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "num_clusters_with_critical_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of clusters with at least one critical alert.", + }, + "num_clusters_with_warning_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of clusters with at least one warning category alert and no critical alerts.", + }, + "num_healthy_clusters": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of clusters with no warning or critical alerts.", + }, + }, + }, + }, + "stats_by_cluster": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies the active Alerts stats by clusters.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "alerts_stats": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies the active alert statistics details.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "num_critical_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active critical Alerts excluding alerts that belong to other bucket.", + }, + "num_critical_alerts_categories": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active critical alerts categories.", + }, + "num_data_service_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active service Alerts.", + }, + "num_data_service_critical_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active service critical Alerts.", + }, + "num_data_service_info_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active service info Alerts.", + }, + "num_data_service_warning_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active service warning Alerts.", + }, + "num_hardware_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active hardware Alerts.", + }, + "num_hardware_critical_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active hardware critical Alerts.", + }, + "num_hardware_info_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active hardware info Alerts.", + }, + "num_hardware_warning_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active hardware warning Alerts.", + }, + "num_info_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active info Alerts excluding alerts that belong to other bucket.", + }, + "num_info_alerts_categories": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active info alerts categories.", + }, + "num_maintenance_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active Alerts of maintenance bucket.", + }, + "num_maintenance_critical_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active other critical Alerts.", + }, + "num_maintenance_info_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active other info Alerts.", + }, + "num_maintenance_warning_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active other warning Alerts.", + }, + "num_software_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active software Alerts.", + }, + "num_software_critical_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active software critical Alerts.", + }, + "num_software_info_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active software info Alerts.", + }, + "num_software_warning_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active software warning Alerts.", + }, + "num_warning_alerts": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active warning Alerts excluding alerts that belong to other bucket.", + }, + "num_warning_alerts_categories": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the count of active warning alerts categories.", + }, + }, + }, + }, + "cluster_id": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the Cluster Id.", + }, + "region_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the region id of cluster.", + }, + }, + }, + }, + }, + } +} + +func dataSourceIbmBackupRecoveryManagerGetAlertsStatsRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + managementApiClient, err := meta.(conns.ClientSession).BackupRecoveryManagerV1() + if err != nil { + tfErr := flex.DiscriminatedTerraformErrorf(err, err.Error(), "(Data) ibm_backup_recovery_manager_get_alerts_stats", "read", "initialize-client") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + bmxsession, err := meta.(conns.ClientSession).BluemixSession() + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("unable to get clientSession"), "ibm_backup_recovery_manager_get_alerts_stats", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + endpointType := d.Get("endpoint_type").(string) + instanceId, region := getInstanceIdAndRegion(d) + managementApiClient, err = setManagerClientAuth(managementApiClient, bmxsession, region, endpointType) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("unable to set authenticator for clientSession: %s", err), "ibm_backup_recovery_manager_get_alerts_stats", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + if instanceId != "" { + managementApiClient = getManagerClientWithInstanceEndpoint(managementApiClient, bmxsession, instanceId, region, endpointType) + } + + getManagementAlertsStatsOptions := &backuprecoveryv1.GetManagementAlertsStatsOptions{} + + getManagementAlertsStatsOptions.SetStartTimeUsecs(int64(d.Get("start_time_usecs").(int))) + getManagementAlertsStatsOptions.SetEndTimeUsecs(int64(d.Get("end_time_usecs").(int))) + if _, ok := d.GetOk("cluster_ids"); ok { + var clusterIds []int64 + for _, v := range d.Get("cluster_ids").([]interface{}) { + clusterIdsItem := int64(v.(int)) + clusterIds = append(clusterIds, clusterIdsItem) + } + getManagementAlertsStatsOptions.SetClusterIds(clusterIds) + } + if _, ok := d.GetOk("service_instance_ids"); ok { + var serviceInstanceIds []string + for _, v := range d.Get("service_instance_ids").([]interface{}) { + serviceInstanceIdsItem := v.(string) + serviceInstanceIds = append(serviceInstanceIds, serviceInstanceIdsItem) + } + getManagementAlertsStatsOptions.SetServiceInstanceIds(serviceInstanceIds) + } + if _, ok := d.GetOk("region_ids"); ok { + var regionIds []string + for _, v := range d.Get("region_ids").([]interface{}) { + regionIdsItem := v.(string) + regionIds = append(regionIds, regionIdsItem) + } + getManagementAlertsStatsOptions.SetRegionIds(regionIds) + } + if _, ok := d.GetOk("exclude_stats_by_cluster"); ok { + getManagementAlertsStatsOptions.SetExcludeStatsByCluster(d.Get("exclude_stats_by_cluster").(bool)) + } + if _, ok := d.GetOk("alert_source"); ok { + getManagementAlertsStatsOptions.SetAlertSource(d.Get("alert_source").(string)) + } + if _, ok := d.GetOk("tenant_ids"); ok { + var tenantIds []string + for _, v := range d.Get("tenant_ids").([]interface{}) { + tenantIdsItem := v.(string) + tenantIds = append(tenantIds, tenantIdsItem) + } + getManagementAlertsStatsOptions.SetTenantIds(tenantIds) + } + + mcmActiveAlertsStats, _, err := managementApiClient.GetManagementAlertsStatsWithContext(context, getManagementAlertsStatsOptions) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetManagementAlertsStatsWithContext failed: %s", err.Error()), "(Data) ibm_backup_recovery_manager_get_alerts_stats", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + d.SetId(dataSourceIbmBackupRecoveryManagerGetAlertsStatsID(d)) + + if !core.IsNil(mcmActiveAlertsStats.AggregatedAlertsStats) { + aggregatedAlertsStats := []map[string]interface{}{} + aggregatedAlertsStatsMap, err := DataSourceIbmBackupRecoveryManagerGetAlertsStatsActiveAlertsStatsToMap(mcmActiveAlertsStats.AggregatedAlertsStats) + if err != nil { + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "(Data) ibm_backup_recovery_manager_get_alerts_stats", "read", "aggregated_alerts_stats-to-map").GetDiag() + } + aggregatedAlertsStats = append(aggregatedAlertsStats, aggregatedAlertsStatsMap) + if err = d.Set("aggregated_alerts_stats", aggregatedAlertsStats); err != nil { + return flex.DiscriminatedTerraformErrorf(err, fmt.Sprintf("Error setting aggregated_alerts_stats: %s", err), "(Data) ibm_backup_recovery_manager_get_alerts_stats", "read", "set-aggregated_alerts_stats").GetDiag() + } + } + + if !core.IsNil(mcmActiveAlertsStats.AggregatedClusterStats) { + aggregatedClusterStats := []map[string]interface{}{} + aggregatedClusterStatsMap, err := DataSourceIbmBackupRecoveryManagerGetAlertsStatsClusterAlertStatsToMap(mcmActiveAlertsStats.AggregatedClusterStats) + if err != nil { + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "(Data) ibm_backup_recovery_manager_get_alerts_stats", "read", "aggregated_cluster_stats-to-map").GetDiag() + } + aggregatedClusterStats = append(aggregatedClusterStats, aggregatedClusterStatsMap) + if err = d.Set("aggregated_cluster_stats", aggregatedClusterStats); err != nil { + return flex.DiscriminatedTerraformErrorf(err, fmt.Sprintf("Error setting aggregated_cluster_stats: %s", err), "(Data) ibm_backup_recovery_manager_get_alerts_stats", "read", "set-aggregated_cluster_stats").GetDiag() + } + } + + if !core.IsNil(mcmActiveAlertsStats.StatsByCluster) { + statsByCluster := []map[string]interface{}{} + for _, statsByClusterItem := range mcmActiveAlertsStats.StatsByCluster { + statsByClusterItemMap, err := DataSourceIbmBackupRecoveryManagerGetAlertsStatsMcmActiveAlertsStatsByClusterToMap(&statsByClusterItem) // #nosec G601 + if err != nil { + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "(Data) ibm_backup_recovery_manager_get_alerts_stats", "read", "stats_by_cluster-to-map").GetDiag() + } + statsByCluster = append(statsByCluster, statsByClusterItemMap) + } + if err = d.Set("stats_by_cluster", statsByCluster); err != nil { + return flex.DiscriminatedTerraformErrorf(err, fmt.Sprintf("Error setting stats_by_cluster: %s", err), "(Data) ibm_backup_recovery_manager_get_alerts_stats", "read", "set-stats_by_cluster").GetDiag() + } + } + + return nil +} + +// dataSourceIbmBackupRecoveryManagerGetAlertsStatsID returns a reasonable ID for the list. +func dataSourceIbmBackupRecoveryManagerGetAlertsStatsID(d *schema.ResourceData) string { + return time.Now().UTC().String() +} + +func DataSourceIbmBackupRecoveryManagerGetAlertsStatsActiveAlertsStatsToMap(model *backuprecoveryv1.ActiveAlertsStats) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.NumCriticalAlerts != nil { + modelMap["num_critical_alerts"] = flex.IntValue(model.NumCriticalAlerts) + } + if model.NumCriticalAlertsCategories != nil { + modelMap["num_critical_alerts_categories"] = flex.IntValue(model.NumCriticalAlertsCategories) + } + if model.NumDataServiceAlerts != nil { + modelMap["num_data_service_alerts"] = flex.IntValue(model.NumDataServiceAlerts) + } + if model.NumDataServiceCriticalAlerts != nil { + modelMap["num_data_service_critical_alerts"] = flex.IntValue(model.NumDataServiceCriticalAlerts) + } + if model.NumDataServiceInfoAlerts != nil { + modelMap["num_data_service_info_alerts"] = flex.IntValue(model.NumDataServiceInfoAlerts) + } + if model.NumDataServiceWarningAlerts != nil { + modelMap["num_data_service_warning_alerts"] = flex.IntValue(model.NumDataServiceWarningAlerts) + } + if model.NumHardwareAlerts != nil { + modelMap["num_hardware_alerts"] = flex.IntValue(model.NumHardwareAlerts) + } + if model.NumHardwareCriticalAlerts != nil { + modelMap["num_hardware_critical_alerts"] = flex.IntValue(model.NumHardwareCriticalAlerts) + } + if model.NumHardwareInfoAlerts != nil { + modelMap["num_hardware_info_alerts"] = flex.IntValue(model.NumHardwareInfoAlerts) + } + if model.NumHardwareWarningAlerts != nil { + modelMap["num_hardware_warning_alerts"] = flex.IntValue(model.NumHardwareWarningAlerts) + } + if model.NumInfoAlerts != nil { + modelMap["num_info_alerts"] = flex.IntValue(model.NumInfoAlerts) + } + if model.NumInfoAlertsCategories != nil { + modelMap["num_info_alerts_categories"] = flex.IntValue(model.NumInfoAlertsCategories) + } + if model.NumMaintenanceAlerts != nil { + modelMap["num_maintenance_alerts"] = flex.IntValue(model.NumMaintenanceAlerts) + } + if model.NumMaintenanceCriticalAlerts != nil { + modelMap["num_maintenance_critical_alerts"] = flex.IntValue(model.NumMaintenanceCriticalAlerts) + } + if model.NumMaintenanceInfoAlerts != nil { + modelMap["num_maintenance_info_alerts"] = flex.IntValue(model.NumMaintenanceInfoAlerts) + } + if model.NumMaintenanceWarningAlerts != nil { + modelMap["num_maintenance_warning_alerts"] = flex.IntValue(model.NumMaintenanceWarningAlerts) + } + if model.NumSoftwareAlerts != nil { + modelMap["num_software_alerts"] = flex.IntValue(model.NumSoftwareAlerts) + } + if model.NumSoftwareCriticalAlerts != nil { + modelMap["num_software_critical_alerts"] = flex.IntValue(model.NumSoftwareCriticalAlerts) + } + if model.NumSoftwareInfoAlerts != nil { + modelMap["num_software_info_alerts"] = flex.IntValue(model.NumSoftwareInfoAlerts) + } + if model.NumSoftwareWarningAlerts != nil { + modelMap["num_software_warning_alerts"] = flex.IntValue(model.NumSoftwareWarningAlerts) + } + if model.NumWarningAlerts != nil { + modelMap["num_warning_alerts"] = flex.IntValue(model.NumWarningAlerts) + } + if model.NumWarningAlertsCategories != nil { + modelMap["num_warning_alerts_categories"] = flex.IntValue(model.NumWarningAlertsCategories) + } + return modelMap, nil +} + +func DataSourceIbmBackupRecoveryManagerGetAlertsStatsClusterAlertStatsToMap(model *backuprecoveryv1.ClusterAlertStats) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.NumClustersWithCriticalAlerts != nil { + modelMap["num_clusters_with_critical_alerts"] = flex.IntValue(model.NumClustersWithCriticalAlerts) + } + if model.NumClustersWithWarningAlerts != nil { + modelMap["num_clusters_with_warning_alerts"] = flex.IntValue(model.NumClustersWithWarningAlerts) + } + if model.NumHealthyClusters != nil { + modelMap["num_healthy_clusters"] = flex.IntValue(model.NumHealthyClusters) + } + return modelMap, nil +} + +func DataSourceIbmBackupRecoveryManagerGetAlertsStatsMcmActiveAlertsStatsByClusterToMap(model *backuprecoveryv1.McmActiveAlertsStatsByCluster) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.AlertsStats != nil { + alertsStatsMap, err := DataSourceIbmBackupRecoveryManagerGetAlertsStatsActiveAlertsStatsToMap(model.AlertsStats) + if err != nil { + return modelMap, err + } + modelMap["alerts_stats"] = []map[string]interface{}{alertsStatsMap} + } + if model.ClusterID != nil { + modelMap["cluster_id"] = flex.IntValue(model.ClusterID) + } + if model.RegionID != nil { + modelMap["region_id"] = *model.RegionID + } + return modelMap, nil +} diff --git a/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_alerts_stats_test.go b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_alerts_stats_test.go new file mode 100644 index 0000000000..a8c7a99177 --- /dev/null +++ b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_alerts_stats_test.go @@ -0,0 +1,43 @@ +// Copyright IBM Corp. 2025 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.96.1-5136e54a-20241108-203028 + */ + +package backuprecovery_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmBackupRecoveryManagerGetAlertsStatsDataSourceBasic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmBackupRecoveryManagerGetAlertsStatsDataSourceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_backup_recovery_manager_get_alerts_stats.backup_recovery_manager_get_alerts_stats_instance", "id"), + resource.TestCheckResourceAttrSet("data.ibm_backup_recovery_manager_get_alerts_stats.backup_recovery_manager_get_alerts_stats_instance", "start_time_usecs"), + resource.TestCheckResourceAttrSet("data.ibm_backup_recovery_manager_get_alerts_stats.backup_recovery_manager_get_alerts_stats_instance", "end_time_usecs"), + ), + }, + }, + }) +} + +func testAccCheckIbmBackupRecoveryManagerGetAlertsStatsDataSourceConfigBasic() string { + return fmt.Sprintf(` + data "ibm_backup_recovery_manager_get_alerts_stats" "backup_recovery_manager_get_alerts_stats_instance" { + start_time_usecs = 1748739600000 + end_time_usecs = 1848739600000 + } + `) +} diff --git a/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_alerts_summary.go b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_alerts_summary.go new file mode 100644 index 0000000000..7c71cc194f --- /dev/null +++ b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_alerts_summary.go @@ -0,0 +1,219 @@ +// Copyright IBM Corp. 2025 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.96.1-5136e54a-20241108-203028 + */ + +package backuprecovery + +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-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/ibm-backup-recovery-sdk-go/backuprecoveryv1" +) + +func DataSourceIbmBackupRecoveryManagerGetAlertsSummary() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmBackupRecoveryManagerGetAlertsSummaryRead, + + Schema: map[string]*schema.Schema{ + "start_time_usecs": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Description: "Filter by start time. Specify the start time as a Unix epoch Timestamp (in microseconds). By default it is current time minus a day.", + }, + "end_time_usecs": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Description: "Filter by end time. Specify the end time as a Unix epoch Timestamp (in microseconds). By default it is current time.", + }, + "include_tenants": &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + Description: "IncludeTenants specifies if alerts of all the tenants under the hierarchy of the logged in user's organization should be used to compute summary.", + }, + "tenant_ids": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "TenantIds contains ids of the tenants for which alerts are to be used to compute summary.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "states_list": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Specifies list of alert states to filter alerts by. If not specified, only open alerts will be used to get summary.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "x_scope_identifier": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "This field uniquely represents a service instance. Please specify the values as \"service-instance-id: \".", + }, + "alerts_summary": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies a list of alerts summary grouped by category.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "category": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Category of alerts by which summary is grouped.", + }, + "critical_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies count of critical alerts.", + }, + "info_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies count of info alerts.", + }, + "total_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies count of total alerts.", + }, + "type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Type/bucket that this alert category belongs to.", + }, + "warning_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies count of warning alerts.", + }, + }, + }, + }, + }, + } +} + +func dataSourceIbmBackupRecoveryManagerGetAlertsSummaryRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + managementApiClient, err := meta.(conns.ClientSession).BackupRecoveryManagerV1() + if err != nil { + tfErr := flex.DiscriminatedTerraformErrorf(err, err.Error(), "(Data) ibm_backup_recovery_manager_get_alerts_summary", "read", "initialize-client") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + bmxsession, err := meta.(conns.ClientSession).BluemixSession() + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("unable to get clientSession"), "ibm_backup_recovery_manager_get_alerts_summary", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + endpointType := d.Get("endpoint_type").(string) + instanceId, region := getInstanceIdAndRegion(d) + managementApiClient, err = setManagerClientAuth(managementApiClient, bmxsession, region, endpointType) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("unable to set authenticator for clientSession: %s", err), "ibm_backup_recovery_manager_get_alerts_summary", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + if instanceId != "" { + managementApiClient = getManagerClientWithInstanceEndpoint(managementApiClient, bmxsession, instanceId, region, endpointType) + } + + getAlertSummaryOptions := &backuprecoveryv1.GetAlertSummaryOptions{} + + if _, ok := d.GetOk("start_time_usecs"); ok { + getAlertSummaryOptions.SetStartTimeUsecs(int64(d.Get("start_time_usecs").(int))) + } + if _, ok := d.GetOk("end_time_usecs"); ok { + getAlertSummaryOptions.SetEndTimeUsecs(int64(d.Get("end_time_usecs").(int))) + } + if _, ok := d.GetOk("include_tenants"); ok { + getAlertSummaryOptions.SetIncludeTenants(d.Get("include_tenants").(bool)) + } + if _, ok := d.GetOk("tenant_ids"); ok { + var tenantIds []string + for _, v := range d.Get("tenant_ids").([]interface{}) { + tenantIdsItem := v.(string) + tenantIds = append(tenantIds, tenantIdsItem) + } + getAlertSummaryOptions.SetTenantIds(tenantIds) + } + if _, ok := d.GetOk("states_list"); ok { + var statesList []string + for _, v := range d.Get("states_list").([]interface{}) { + statesListItem := v.(string) + statesList = append(statesList, statesListItem) + } + getAlertSummaryOptions.SetStatesList(statesList) + } + if _, ok := d.GetOk("x_scope_identifier"); ok { + getAlertSummaryOptions.SetXScopeIdentifier(d.Get("x_scope_identifier").(string)) + } + + alertsSummaryResponse, _, err := managementApiClient.GetAlertSummaryWithContext(context, getAlertSummaryOptions) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetAlertSummaryWithContext failed: %s", err.Error()), "(Data) ibm_backup_recovery_manager_get_alerts_summary", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + d.SetId(dataSourceIbmBackupRecoveryManagerGetAlertsSummaryID(d)) + + if !core.IsNil(alertsSummaryResponse.AlertsSummary) { + alertsSummary := []map[string]interface{}{} + for _, alertsSummaryItem := range alertsSummaryResponse.AlertsSummary { + alertsSummaryItemMap, err := DataSourceIbmBackupRecoveryManagerGetAlertsSummaryAlertGroupSummaryToMap(&alertsSummaryItem) // #nosec G601 + if err != nil { + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "(Data) ibm_backup_recovery_manager_get_alerts_summary", "read", "alerts_summary-to-map").GetDiag() + } + alertsSummary = append(alertsSummary, alertsSummaryItemMap) + } + if err = d.Set("alerts_summary", alertsSummary); err != nil { + return flex.DiscriminatedTerraformErrorf(err, fmt.Sprintf("Error setting alerts_summary: %s", err), "(Data) ibm_backup_recovery_manager_get_alerts_summary", "read", "set-alerts_summary").GetDiag() + } + } + + return nil +} + +// dataSourceIbmBackupRecoveryManagerGetAlertsSummaryID returns a reasonable ID for the list. +func dataSourceIbmBackupRecoveryManagerGetAlertsSummaryID(d *schema.ResourceData) string { + return time.Now().UTC().String() +} + +func DataSourceIbmBackupRecoveryManagerGetAlertsSummaryAlertGroupSummaryToMap(model *backuprecoveryv1.AlertGroupSummary) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Category != nil { + modelMap["category"] = *model.Category + } + if model.CriticalCount != nil { + modelMap["critical_count"] = flex.IntValue(model.CriticalCount) + } + if model.InfoCount != nil { + modelMap["info_count"] = flex.IntValue(model.InfoCount) + } + if model.TotalCount != nil { + modelMap["total_count"] = flex.IntValue(model.TotalCount) + } + if model.Type != nil { + modelMap["type"] = *model.Type + } + if model.WarningCount != nil { + modelMap["warning_count"] = flex.IntValue(model.WarningCount) + } + return modelMap, nil +} diff --git a/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_alerts_summary_test.go b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_alerts_summary_test.go new file mode 100644 index 0000000000..c09fd5cded --- /dev/null +++ b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_alerts_summary_test.go @@ -0,0 +1,41 @@ +// Copyright IBM Corp. 2025 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.96.1-5136e54a-20241108-203028 + */ + +package backuprecovery_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmBackupRecoveryManagerGetAlertsSummaryDataSourceBasic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmBackupRecoveryManagerGetAlertsSummaryDataSourceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_backup_recovery_manager_get_alerts_summary.backup_recovery_manager_get_alerts_summary_instance", "id"), + ), + }, + }, + }) +} + +func testAccCheckIbmBackupRecoveryManagerGetAlertsSummaryDataSourceConfigBasic() string { + return fmt.Sprintf(` + data "ibm_backup_recovery_manager_get_alerts_summary" "backup_recovery_manager_get_alerts_summary_instance" { + start_time_usecs = 1748739600000 + end_time_usecs = 1848739600000 + } + `) +} diff --git a/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_alerts_test.go b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_alerts_test.go new file mode 100644 index 0000000000..fdcf925f71 --- /dev/null +++ b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_alerts_test.go @@ -0,0 +1,40 @@ +// Copyright IBM Corp. 2025 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.96.1-5136e54a-20241108-203028 + */ + +package backuprecovery_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmBackupRecoveryManagerGetAlertsDataSourceBasic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmBackupRecoveryManagerGetAlertsDataSourceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_backup_recovery_manager_get_alerts.backup_recovery_manager_get_alerts_instance", "id"), + resource.TestCheckResourceAttrSet("data.ibm_backup_recovery_manager_get_alerts.backup_recovery_manager_get_alerts_instance", "alerts.#"), + ), + }, + }, + }) +} + +func testAccCheckIbmBackupRecoveryManagerGetAlertsDataSourceConfigBasic() string { + return fmt.Sprintf(` + data "ibm_backup_recovery_manager_get_alerts" "backup_recovery_manager_get_alerts_instance" { + } + `) +} diff --git a/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_cluster_info.go b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_cluster_info.go new file mode 100644 index 0000000000..ec01c59735 --- /dev/null +++ b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_cluster_info.go @@ -0,0 +1,530 @@ +// Copyright IBM Corp. 2025 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.96.1-5136e54a-20241108-203028 + */ + +package backuprecovery + +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-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/ibm-backup-recovery-sdk-go/backuprecoveryv1" +) + +func DataSourceIbmBackupRecoveryManagerGetClusterInfo() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmBackupRecoveryManagerGetClusterInfoRead, + + Schema: map[string]*schema.Schema{ + "cohesity_clusters": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies the array of clusters upgrade details.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "auth_support_for_pkg_downloads": &schema.Schema{ + Type: schema.TypeBool, + Computed: true, + Description: "If cluster can support authHeader for upgrade or not.", + }, + "available_versions": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies the release versions the cluster can upgrade to.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "notes": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies release's notes.", + }, + "patch_details": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies the details of the available patch release.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "notes": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies patch release's notes.", + }, + "release_type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Release's type.", + }, + "version": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies patch release's version.", + }, + }, + }, + }, + "release_stage": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the stage of a release.", + }, + "release_type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Release's type e.g, LTS, Feature, Patch, MCM.", + }, + "type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the type of package or release.", + }, + "version": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies release's version.", + }, + }, + }, + }, + "cluster_id": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies cluster id.", + }, + "cluster_incarnation_id": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies cluster incarnation id.", + }, + "cluster_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies cluster's name.", + }, + "current_patch_version": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies current patch version of the cluster.", + }, + "current_version": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies if the cluster is connected to management console.", + }, + "health": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the health of the cluster.", + }, + "is_connected_to_helios": &schema.Schema{ + Type: schema.TypeBool, + Computed: true, + Description: "Specifies if the cluster is connected to management console.", + }, + "location": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the location of the cluster.", + }, + "multi_tenancy_enabled": &schema.Schema{ + Type: schema.TypeBool, + Computed: true, + Description: "Specifies if multi tenancy is enabled in the cluster.", + }, + "node_ips": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies an array of node ips for the cluster.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "number_of_nodes": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the number of nodes in the cluster.", + }, + "patch_target_upgrade_url": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the patch package URL for the cluster. This is populated for patch update only.", + }, + "patch_target_version": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies target version to which clusters are upgrading. This is populated for patch update only.", + }, + "provider_type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the type of the cluster provider.", + }, + "scheduled_timestamp": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Time at which an upgrade is scheduled.", + }, + "status": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the upgrade status of the cluster.", + }, + "target_upgrade_url": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the upgrade URL for the cluster. This is populated for upgrade only.", + }, + "target_version": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies target version to which clusters are to be upgraded. This is populated for upgrade only.", + }, + "total_capacity": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies how total memory capacity of the cluster.", + }, + "type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the type of the cluster.", + }, + "update_type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the type of upgrade performed on a cluster. This is to be used with status field to know the status of the upgrade action performed on cluster.", + }, + "used_capacity": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies how much of the cluster capacity is consumed.", + }, + }, + }, + }, + "sp_clusters": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies the array of clusters claimed from IBM Storage Protect environment.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cluster_id": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies cluster id.", + }, + "cluster_incarnation_id": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies cluster incarnation id.", + }, + "cluster_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies cluster's name.", + }, + "current_version": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the currently running version on cluster.", + }, + "health": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the health of the cluster.", + }, + "is_connected_to_helios": &schema.Schema{ + Type: schema.TypeBool, + Computed: true, + Description: "Specifies if the cluster is connected to management console.", + }, + "node_ips": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies an array of node ips for the cluster.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "number_of_nodes": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the number of nodes in the cluster.", + }, + "provider_type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the type of the cluster provider.", + }, + "total_capacity": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies total capacity of the cluster in bytes.", + }, + "type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the type of the SP cluster.", + }, + "used_capacity": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies how much of the cluster capacity is consumed in bytes.", + }, + }, + }, + }, + }, + } +} + +func dataSourceIbmBackupRecoveryManagerGetClusterInfoRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + managementApiClient, err := meta.(conns.ClientSession).BackupRecoveryManagerV1() + if err != nil { + tfErr := flex.DiscriminatedTerraformErrorf(err, err.Error(), "(Data) ibm_backup_recovery_manager_get_cluster_info", "read", "initialize-client") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + bmxsession, err := meta.(conns.ClientSession).BluemixSession() + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("unable to get clientSession"), "ibm_backup_recovery_manager_get_cluster_info", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + endpointType := d.Get("endpoint_type").(string) + instanceId, region := getInstanceIdAndRegion(d) + managementApiClient, err = setManagerClientAuth(managementApiClient, bmxsession, region, endpointType) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("unable to set authenticator for clientSession: %s", err), "ibm_backup_recovery_manager_get_cluster_info", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + if instanceId != "" { + managementApiClient = getManagerClientWithInstanceEndpoint(managementApiClient, bmxsession, instanceId, region, endpointType) + } + + getClustersInfoOptions := &backuprecoveryv1.GetClustersInfoOptions{} + + clusterDetails, _, err := managementApiClient.GetClustersInfoWithContext(context, getClustersInfoOptions) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetClustersInfoWithContext failed: %s", err.Error()), "(Data) ibm_backup_recovery_manager_get_cluster_info", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + d.SetId(dataSourceIbmBackupRecoveryManagerGetClusterInfoID(d)) + + if !core.IsNil(clusterDetails.CohesityClusters) { + cohesityClusters := []map[string]interface{}{} + for _, cohesityClustersItem := range clusterDetails.CohesityClusters { + cohesityClustersItemMap, err := DataSourceIbmBackupRecoveryManagerGetClusterInfoClusterInfoToMap(&cohesityClustersItem) // #nosec G601 + if err != nil { + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "(Data) ibm_backup_recovery_manager_get_cluster_info", "read", "cohesity_clusters-to-map").GetDiag() + } + cohesityClusters = append(cohesityClusters, cohesityClustersItemMap) + } + if err = d.Set("cohesity_clusters", cohesityClusters); err != nil { + return flex.DiscriminatedTerraformErrorf(err, fmt.Sprintf("Error setting cohesity_clusters: %s", err), "(Data) ibm_backup_recovery_manager_get_cluster_info", "read", "set-cohesity_clusters").GetDiag() + } + } + + if !core.IsNil(clusterDetails.SpClusters) { + spClusters := []map[string]interface{}{} + for _, spClustersItem := range clusterDetails.SpClusters { + spClustersItemMap, err := DataSourceIbmBackupRecoveryManagerGetClusterInfoSPClusterInfoToMap(&spClustersItem) // #nosec G601 + if err != nil { + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "(Data) ibm_backup_recovery_manager_get_cluster_info", "read", "sp_clusters-to-map").GetDiag() + } + spClusters = append(spClusters, spClustersItemMap) + } + if err = d.Set("sp_clusters", spClusters); err != nil { + return flex.DiscriminatedTerraformErrorf(err, fmt.Sprintf("Error setting sp_clusters: %s", err), "(Data) ibm_backup_recovery_manager_get_cluster_info", "read", "set-sp_clusters").GetDiag() + } + } + + return nil +} + +// dataSourceIbmBackupRecoveryManagerGetClusterInfoID returns a reasonable ID for the list. +func dataSourceIbmBackupRecoveryManagerGetClusterInfoID(d *schema.ResourceData) string { + return time.Now().UTC().String() +} + +func DataSourceIbmBackupRecoveryManagerGetClusterInfoClusterInfoToMap(model *backuprecoveryv1.ClusterInfo) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.AuthSupportForPkgDownloads != nil { + modelMap["auth_support_for_pkg_downloads"] = *model.AuthSupportForPkgDownloads + } + if model.AvailableVersions != nil { + availableVersions := []map[string]interface{}{} + for _, availableVersionsItem := range model.AvailableVersions { + availableVersionsItemMap, err := DataSourceIbmBackupRecoveryManagerGetClusterInfoAvailableReleaseVersionToMap(&availableVersionsItem) // #nosec G601 + if err != nil { + return modelMap, err + } + availableVersions = append(availableVersions, availableVersionsItemMap) + } + modelMap["available_versions"] = availableVersions + } + if model.ClusterID != nil { + modelMap["cluster_id"] = flex.IntValue(model.ClusterID) + } + if model.ClusterIncarnationID != nil { + modelMap["cluster_incarnation_id"] = flex.IntValue(model.ClusterIncarnationID) + } + if model.ClusterName != nil { + modelMap["cluster_name"] = *model.ClusterName + } + if model.CurrentPatchVersion != nil { + modelMap["current_patch_version"] = *model.CurrentPatchVersion + } + if model.CurrentVersion != nil { + modelMap["current_version"] = *model.CurrentVersion + } + if model.Health != nil { + modelMap["health"] = *model.Health + } + if model.IsConnectedToHelios != nil { + modelMap["is_connected_to_helios"] = *model.IsConnectedToHelios + } + if model.Location != nil { + modelMap["location"] = *model.Location + } + if model.MultiTenancyEnabled != nil { + modelMap["multi_tenancy_enabled"] = *model.MultiTenancyEnabled + } + if model.NodeIps != nil { + modelMap["node_ips"] = model.NodeIps + } + if model.NumberOfNodes != nil { + modelMap["number_of_nodes"] = flex.IntValue(model.NumberOfNodes) + } + if model.PatchTargetUpgradeURL != nil { + modelMap["patch_target_upgrade_url"] = *model.PatchTargetUpgradeURL + } + if model.PatchTargetVersion != nil { + modelMap["patch_target_version"] = *model.PatchTargetVersion + } + if model.ProviderType != nil { + modelMap["provider_type"] = *model.ProviderType + } + if model.ScheduledTimestamp != nil { + modelMap["scheduled_timestamp"] = flex.IntValue(model.ScheduledTimestamp) + } + if model.Status != nil { + modelMap["status"] = *model.Status + } + if model.TargetUpgradeURL != nil { + modelMap["target_upgrade_url"] = *model.TargetUpgradeURL + } + if model.TargetVersion != nil { + modelMap["target_version"] = *model.TargetVersion + } + if model.TotalCapacity != nil { + modelMap["total_capacity"] = flex.IntValue(model.TotalCapacity) + } + if model.Type != nil { + modelMap["type"] = *model.Type + } + if model.UpdateType != nil { + modelMap["update_type"] = *model.UpdateType + } + if model.UsedCapacity != nil { + modelMap["used_capacity"] = flex.IntValue(model.UsedCapacity) + } + return modelMap, nil +} + +func DataSourceIbmBackupRecoveryManagerGetClusterInfoAvailableReleaseVersionToMap(model *backuprecoveryv1.AvailableReleaseVersion) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Notes != nil { + modelMap["notes"] = *model.Notes + } + if model.PatchDetails != nil { + patchDetailsMap, err := DataSourceIbmBackupRecoveryManagerGetClusterInfoAvailablePatchReleaseToMap(model.PatchDetails) + if err != nil { + return modelMap, err + } + modelMap["patch_details"] = []map[string]interface{}{patchDetailsMap} + } + if model.ReleaseStage != nil { + modelMap["release_stage"] = *model.ReleaseStage + } + if model.ReleaseType != nil { + modelMap["release_type"] = *model.ReleaseType + } + if model.Type != nil { + modelMap["type"] = *model.Type + } + if model.Version != nil { + modelMap["version"] = *model.Version + } + return modelMap, nil +} + +func DataSourceIbmBackupRecoveryManagerGetClusterInfoAvailablePatchReleaseToMap(model *backuprecoveryv1.AvailablePatchRelease) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Notes != nil { + modelMap["notes"] = *model.Notes + } + if model.ReleaseType != nil { + modelMap["release_type"] = *model.ReleaseType + } + if model.Version != nil { + modelMap["version"] = *model.Version + } + return modelMap, nil +} + +func DataSourceIbmBackupRecoveryManagerGetClusterInfoSPClusterInfoToMap(model *backuprecoveryv1.SPClusterInfo) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ClusterID != nil { + modelMap["cluster_id"] = flex.IntValue(model.ClusterID) + } + if model.ClusterIncarnationID != nil { + modelMap["cluster_incarnation_id"] = flex.IntValue(model.ClusterIncarnationID) + } + if model.ClusterName != nil { + modelMap["cluster_name"] = *model.ClusterName + } + if model.CurrentVersion != nil { + modelMap["current_version"] = *model.CurrentVersion + } + if model.Health != nil { + modelMap["health"] = *model.Health + } + if model.IsConnectedToHelios != nil { + modelMap["is_connected_to_helios"] = *model.IsConnectedToHelios + } + if model.NodeIps != nil { + modelMap["node_ips"] = model.NodeIps + } + if model.NumberOfNodes != nil { + modelMap["number_of_nodes"] = flex.IntValue(model.NumberOfNodes) + } + if model.ProviderType != nil { + modelMap["provider_type"] = *model.ProviderType + } + if model.TotalCapacity != nil { + modelMap["total_capacity"] = flex.IntValue(model.TotalCapacity) + } + if model.Type != nil { + modelMap["type"] = *model.Type + } + if model.UsedCapacity != nil { + modelMap["used_capacity"] = flex.IntValue(model.UsedCapacity) + } + return modelMap, nil +} diff --git a/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_cluster_info_test.go b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_cluster_info_test.go new file mode 100644 index 0000000000..1c0df5f302 --- /dev/null +++ b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_cluster_info_test.go @@ -0,0 +1,39 @@ +// Copyright IBM Corp. 2025 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.96.1-5136e54a-20241108-203028 + */ + +package backuprecovery_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmBackupRecoveryManagerGetClusterInfoDataSourceBasic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmBackupRecoveryManagerGetClusterInfoDataSourceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_backup_recovery_manager_get_cluster_info.backup_recovery_manager_get_cluster_info_instance", "id"), + ), + }, + }, + }) +} + +func testAccCheckIbmBackupRecoveryManagerGetClusterInfoDataSourceConfigBasic() string { + return fmt.Sprintf(` + data "ibm_backup_recovery_manager_get_cluster_info" "backup_recovery_manager_get_cluster_info_instance" { + } + `) +} diff --git a/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_compatible_clusters.go b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_compatible_clusters.go new file mode 100644 index 0000000000..da920a59f7 --- /dev/null +++ b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_compatible_clusters.go @@ -0,0 +1,145 @@ +// Copyright IBM Corp. 2025 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.96.1-5136e54a-20241108-203028 + */ + +package backuprecovery + +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-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/ibm-backup-recovery-sdk-go/backuprecoveryv1" +) + +func DataSourceIbmBackupRecoveryManagerGetCompatibleClusters() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmBackupRecoveryManagerGetCompatibleClustersRead, + + Schema: map[string]*schema.Schema{ + "release_version": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, + "compatible_clusters": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cluster_id": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies cluster id.", + }, + "cluster_incarnation_id": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies cluster incarnation id.", + }, + "cluster_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies cluster's name.", + }, + "current_version": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the current version of the cluster.", + }, + }, + }, + }, + }, + } +} + +func dataSourceIbmBackupRecoveryManagerGetCompatibleClustersRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + managementApiClient, err := meta.(conns.ClientSession).BackupRecoveryManagerV1() + if err != nil { + tfErr := flex.DiscriminatedTerraformErrorf(err, err.Error(), "(Data) ibm_backup_recovery_manager_get_compatible_clusters", "read", "initialize-client") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + bmxsession, err := meta.(conns.ClientSession).BluemixSession() + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("unable to get clientSession"), "ibm_backup_recovery_manager_get_compatible_clusters", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + endpointType := d.Get("endpoint_type").(string) + instanceId, region := getInstanceIdAndRegion(d) + managementApiClient, err = setManagerClientAuth(managementApiClient, bmxsession, region, endpointType) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("unable to set authenticator for clientSession: %s", err), "ibm_backup_recovery_manager_get_compatible_clusters", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + if instanceId != "" { + managementApiClient = getManagerClientWithInstanceEndpoint(managementApiClient, bmxsession, instanceId, region, endpointType) + } + + compatibleClustersForReleaseOptions := &backuprecoveryv1.CompatibleClustersForReleaseOptions{} + + if _, ok := d.GetOk("release_version"); ok { + compatibleClustersForReleaseOptions.SetReleaseVersion(d.Get("release_version").(string)) + } + + compatibleClusters, _, err := managementApiClient.CompatibleClustersForReleaseWithContext(context, compatibleClustersForReleaseOptions) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CompatibleClustersForReleaseWithContext failed: %s", err.Error()), "(Data) ibm_backup_recovery_manager_get_compatible_clusters", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + d.SetId(dataSourceIbmBackupRecoveryManagerGetCompatibleClustersID(d)) + + if !core.IsNil(compatibleClusters) { + compatibleClustersResult := []map[string]interface{}{} + for _, compatibleClustersItem := range compatibleClusters { + compatibleClustersItemMap, err := DataSourceIbmBackupRecoveryManagerGetCompatibleClustersCompatibleClusterToMap(&compatibleClustersItem) // #nosec G601 + if err != nil { + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "(Data) ibm_backup_recovery_manager_get_compatible_clusters", "read", "compatible_clusters-to-map").GetDiag() + } + compatibleClustersResult = append(compatibleClustersResult, compatibleClustersItemMap) + } + if err = d.Set("compatible_clusters", compatibleClustersResult); err != nil { + return flex.DiscriminatedTerraformErrorf(err, fmt.Sprintf("Error setting compatible_clusters: %s", err), "(Data) ibm_backup_recovery_manager_get_compatible_clusters", "read", "set-compatible_clusters").GetDiag() + } + } + + return nil +} + +// dataSourceIbmBackupRecoveryManagerGetCompatibleClustersID returns a reasonable ID for the list. +func dataSourceIbmBackupRecoveryManagerGetCompatibleClustersID(d *schema.ResourceData) string { + return time.Now().UTC().String() +} + +func DataSourceIbmBackupRecoveryManagerGetCompatibleClustersCompatibleClusterToMap(model *backuprecoveryv1.CompatibleCluster) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ClusterID != nil { + modelMap["cluster_id"] = flex.IntValue(model.ClusterID) + } + if model.ClusterIncarnationID != nil { + modelMap["cluster_incarnation_id"] = flex.IntValue(model.ClusterIncarnationID) + } + if model.ClusterName != nil { + modelMap["cluster_name"] = *model.ClusterName + } + if model.CurrentVersion != nil { + modelMap["current_version"] = *model.CurrentVersion + } + return modelMap, nil +} diff --git a/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_compatible_clusters_test.go b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_compatible_clusters_test.go new file mode 100644 index 0000000000..052503292b --- /dev/null +++ b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_compatible_clusters_test.go @@ -0,0 +1,39 @@ +// Copyright IBM Corp. 2025 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.96.1-5136e54a-20241108-203028 + */ + +package backuprecovery_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmBackupRecoveryManagerGetCompatibleClustersDataSourceBasic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmBackupRecoveryManagerGetCompatibleClustersDataSourceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_backup_recovery_manager_get_compatible_clusters.backup_recovery_manager_get_compatible_clusters_instance", "id"), + ), + }, + }, + }) +} + +func testAccCheckIbmBackupRecoveryManagerGetCompatibleClustersDataSourceConfigBasic() string { + return fmt.Sprintf(` + data "ibm_backup_recovery_manager_get_compatible_clusters" "backup_recovery_manager_get_compatible_clusters_instance" { + } + `) +} diff --git a/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_management_alerts.go b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_management_alerts.go new file mode 100644 index 0000000000..a96fbb68bc --- /dev/null +++ b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_management_alerts.go @@ -0,0 +1,614 @@ +// Copyright IBM Corp. 2025 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.96.1-5136e54a-20241108-203028 + */ + +package backuprecovery + +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-Cloud/terraform-provider-ibm/ibm/conns" + "github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex" + "github.com/IBM/ibm-backup-recovery-sdk-go/backuprecoveryv1" +) + +func DataSourceIbmBackupRecoveryManagerGetManagementAlerts() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmBackupRecoveryManagerGetManagementAlertsRead, + + Schema: map[string]*schema.Schema{ + "alert_id_list": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Filter by list of alert ids.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "alert_state_list": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Filter by list of alert states.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "alert_type_list": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Filter by list of alert types.", + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "alert_severity_list": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Filter by list of alert severity types.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "region_ids": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Filter by list of region ids.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "cluster_identifiers": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Filter by list of cluster ids.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "start_date_usecs": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Description: "Specifies the start time of the alerts to be returned. All the alerts returned are raised after the specified start time. This value should be in Unix timestamp epoch in microseconds.", + }, + "end_date_usecs": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Description: "Specifies the end time of the alerts to be returned. All the alerts returned are raised before the specified end time. This value should be in Unix timestamp epoch in microseconds.", + }, + "max_alerts": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Description: "Specifies maximum number of alerts to return.", + }, + "alert_category_list": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Filter by list of alert categories.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "tenant_ids": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Filter by tenant ids.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "alert_type_bucket_list": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Filter by list of alert type buckets.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "alert_property_key_list": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Specifies list of the alert property keys to query.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "alert_property_value_list": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Specifies list of the alert property value, multiple values for one key should be joined by '|'.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "alert_name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "Specifies name of alert to filter alerts by.", + }, + "service_instance_ids": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Specifies services instance ids to filter alerts for IBM customers.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "alerts_list": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies the list of alerts.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "alert_category": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the alert category.", + }, + "alert_code": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies a unique code that categorizes the Alert, for example: CE00200014, where CE stands for IBM Error, the alert state next 3 digits is the id of the Alert Category (e.g. 002 for 'kNode') and the last 5 digits is the id of the Alert Type (e.g. 00014 for 'kNodeHighCpuUsage').", + }, + "alert_document": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies the fields of alert document.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "alert_cause": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the cause of alert.", + }, + "alert_description": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the description of alert.", + }, + "alert_help_text": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the help text for alert.", + }, + "alert_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the name of alert.", + }, + "alert_summary": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Short description for the alert.", + }, + }, + }, + }, + "alert_state": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the alert state.", + }, + "alert_type": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the alert type.", + }, + "alert_type_bucket": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the Alert type bucket.", + }, + "cluster_id": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Id of the cluster which the alert is associated.", + }, + "cluster_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the name of cluster which alert is raised from.", + }, + "dedup_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies the dedup count of alert.", + }, + "dedup_timestamps": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies Unix epoch Timestamps (in microseconds) for the last 25 occurrences of duplicated Alerts that are stored with the original/primary Alert. Alerts are grouped into one Alert if the Alerts are the same type, are reporting on the same Object and occur within one hour. 'dedupCount' always reports the total count of duplicated Alerts even if there are more than 25 occurrences. For example, if there are 100 occurrences of this Alert, dedupTimestamps stores the timestamps of the last 25 occurrences and dedupCount equals 100.", + Elem: &schema.Schema{ + Type: schema.TypeInt, + }, + }, + "first_timestamp_usecs": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "SpeSpecifies Unix epoch Timestamp (in microseconds) of the first occurrence of the Alert.", + }, + "id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies unique id of the alert.", + }, + "latest_timestamp_usecs": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "SpeSpecifies Unix epoch Timestamp (in microseconds) of the most recent occurrence of the Alert.", + }, + "property_list": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "List of property key and values associated with alert.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "key": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Key of the Label.", + }, + "value": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Value of the Label, multiple values should be joined by '|'.", + }, + }, + }, + }, + "region_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the region id of the alert.", + }, + "resolution_id_string": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the resolution id of the alert if its resolved.", + }, + "service_instance_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Id of the serrvice instance which the alert is associated.", + }, + "severity": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the alert severity.", + }, + "vaults": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies information about vaults where source object associated with alert is vaulted. This could be empty if alert is not related to any source object or it is not vaulted.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "global_vault_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies Global vault id.", + }, + "region_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies id of region where vault resides.", + }, + "region_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies name of region where vault resides.", + }, + "vault_name": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies name of vault.", + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func dataSourceIbmBackupRecoveryManagerGetManagementAlertsRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + managementApiClient, err := meta.(conns.ClientSession).BackupRecoveryManagerV1() + if err != nil { + tfErr := flex.DiscriminatedTerraformErrorf(err, err.Error(), "(Data) ibm_backup_recovery_manager_get_management_alerts", "read", "initialize-client") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + bmxsession, err := meta.(conns.ClientSession).BluemixSession() + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("unable to get clientSession"), "ibm_backup_recovery_manager_get_management_alerts", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + endpointType := d.Get("endpoint_type").(string) + instanceId, region := getInstanceIdAndRegion(d) + managementApiClient, err = setManagerClientAuth(managementApiClient, bmxsession, region, endpointType) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("unable to set authenticator for clientSession: %s", err), "ibm_backup_recovery_manager_get_management_alerts", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + if instanceId != "" { + managementApiClient = getManagerClientWithInstanceEndpoint(managementApiClient, bmxsession, instanceId, region, endpointType) + } + + getManagementAlertsOptions := &backuprecoveryv1.GetManagementAlertsOptions{} + + if _, ok := d.GetOk("alert_id_list"); ok { + var alertIdList []string + for _, v := range d.Get("alert_id_list").([]interface{}) { + alertIdListItem := v.(string) + alertIdList = append(alertIdList, alertIdListItem) + } + getManagementAlertsOptions.SetAlertIdList(alertIdList) + } + if _, ok := d.GetOk("alert_state_list"); ok { + var alertStateList []string + for _, v := range d.Get("alert_state_list").([]interface{}) { + alertStateListItem := v.(string) + alertStateList = append(alertStateList, alertStateListItem) + } + getManagementAlertsOptions.SetAlertStateList(alertStateList) + } + if _, ok := d.GetOk("alert_type_list"); ok { + var alertTypeList []int64 + for _, v := range d.Get("alert_type_list").([]interface{}) { + alertTypeListItem := int64(v.(int)) + alertTypeList = append(alertTypeList, alertTypeListItem) + } + getManagementAlertsOptions.SetAlertTypeList(alertTypeList) + } + if _, ok := d.GetOk("alert_severity_list"); ok { + var alertSeverityList []string + for _, v := range d.Get("alert_severity_list").([]interface{}) { + alertSeverityListItem := v.(string) + alertSeverityList = append(alertSeverityList, alertSeverityListItem) + } + getManagementAlertsOptions.SetAlertSeverityList(alertSeverityList) + } + if _, ok := d.GetOk("region_ids"); ok { + var regionIds []string + for _, v := range d.Get("region_ids").([]interface{}) { + regionIdsItem := v.(string) + regionIds = append(regionIds, regionIdsItem) + } + getManagementAlertsOptions.SetRegionIds(regionIds) + } + if _, ok := d.GetOk("cluster_identifiers"); ok { + var clusterIdentifiers []string + for _, v := range d.Get("cluster_identifiers").([]interface{}) { + clusterIdentifiersItem := v.(string) + clusterIdentifiers = append(clusterIdentifiers, clusterIdentifiersItem) + } + getManagementAlertsOptions.SetClusterIdentifiers(clusterIdentifiers) + } + if _, ok := d.GetOk("start_date_usecs"); ok { + getManagementAlertsOptions.SetStartDateUsecs(int64(d.Get("start_date_usecs").(int))) + } + if _, ok := d.GetOk("end_date_usecs"); ok { + getManagementAlertsOptions.SetEndDateUsecs(int64(d.Get("end_date_usecs").(int))) + } + if _, ok := d.GetOk("max_alerts"); ok { + getManagementAlertsOptions.SetMaxAlerts(int64(d.Get("max_alerts").(int))) + } + if _, ok := d.GetOk("alert_category_list"); ok { + var alertCategoryList []string + for _, v := range d.Get("alert_category_list").([]interface{}) { + alertCategoryListItem := v.(string) + alertCategoryList = append(alertCategoryList, alertCategoryListItem) + } + getManagementAlertsOptions.SetAlertCategoryList(alertCategoryList) + } + if _, ok := d.GetOk("tenant_ids"); ok { + var tenantIds []string + for _, v := range d.Get("tenant_ids").([]interface{}) { + tenantIdsItem := v.(string) + tenantIds = append(tenantIds, tenantIdsItem) + } + getManagementAlertsOptions.SetTenantIds(tenantIds) + } + if _, ok := d.GetOk("alert_type_bucket_list"); ok { + var alertTypeBucketList []string + for _, v := range d.Get("alert_type_bucket_list").([]interface{}) { + alertTypeBucketListItem := v.(string) + alertTypeBucketList = append(alertTypeBucketList, alertTypeBucketListItem) + } + getManagementAlertsOptions.SetAlertTypeBucketList(alertTypeBucketList) + } + if _, ok := d.GetOk("alert_property_key_list"); ok { + var alertPropertyKeyList []string + for _, v := range d.Get("alert_property_key_list").([]interface{}) { + alertPropertyKeyListItem := v.(string) + alertPropertyKeyList = append(alertPropertyKeyList, alertPropertyKeyListItem) + } + getManagementAlertsOptions.SetAlertPropertyKeyList(alertPropertyKeyList) + } + if _, ok := d.GetOk("alert_property_value_list"); ok { + var alertPropertyValueList []string + for _, v := range d.Get("alert_property_value_list").([]interface{}) { + alertPropertyValueListItem := v.(string) + alertPropertyValueList = append(alertPropertyValueList, alertPropertyValueListItem) + } + getManagementAlertsOptions.SetAlertPropertyValueList(alertPropertyValueList) + } + if _, ok := d.GetOk("alert_name"); ok { + getManagementAlertsOptions.SetAlertName(d.Get("alert_name").(string)) + } + if _, ok := d.GetOk("service_instance_ids"); ok { + var serviceInstanceIds []string + for _, v := range d.Get("service_instance_ids").([]interface{}) { + serviceInstanceIdsItem := v.(string) + serviceInstanceIds = append(serviceInstanceIds, serviceInstanceIdsItem) + } + getManagementAlertsOptions.SetServiceInstanceIds(serviceInstanceIds) + } + + alertsList, _, err := managementApiClient.GetManagementAlertsWithContext(context, getManagementAlertsOptions) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetManagementAlertsWithContext failed: %s", err.Error()), "(Data) ibm_backup_recovery_manager_get_management_alerts", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + d.SetId(dataSourceIbmBackupRecoveryManagerGetManagementAlertsID(d)) + + alertsListResult := []map[string]interface{}{} + for _, alertsListItem := range alertsList.AlertsList { + alertsListItemMap, err := DataSourceIbmBackupRecoveryManagerGetManagementAlertsAlertToMap(&alertsListItem) // #nosec G601 + if err != nil { + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "(Data) ibm_backup_recovery_manager_get_management_alerts", "read", "alerts_list-to-map").GetDiag() + } + alertsListResult = append(alertsListResult, alertsListItemMap) + } + if err = d.Set("alerts_list", alertsListResult); err != nil { + return flex.DiscriminatedTerraformErrorf(err, fmt.Sprintf("Error setting alerts_list: %s", err), "(Data) ibm_backup_recovery_manager_get_management_alerts", "read", "set-alerts_list").GetDiag() + } + + return nil +} + +// dataSourceIbmBackupRecoveryManagerGetManagementAlertsID returns a reasonable ID for the list. +func dataSourceIbmBackupRecoveryManagerGetManagementAlertsID(d *schema.ResourceData) string { + return time.Now().UTC().String() +} + +func DataSourceIbmBackupRecoveryManagerGetManagementAlertsAlertToMap(model *backuprecoveryv1.Alert) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.AlertCategory != nil { + modelMap["alert_category"] = *model.AlertCategory + } + if model.AlertCode != nil { + modelMap["alert_code"] = *model.AlertCode + } + if model.AlertDocument != nil { + alertDocumentMap, err := DataSourceIbmBackupRecoveryManagerGetManagementAlertsAlertDocumentToMap(model.AlertDocument) + if err != nil { + return modelMap, err + } + modelMap["alert_document"] = []map[string]interface{}{alertDocumentMap} + } + if model.AlertState != nil { + modelMap["alert_state"] = *model.AlertState + } + if model.AlertType != nil { + modelMap["alert_type"] = flex.IntValue(model.AlertType) + } + if model.AlertTypeBucket != nil { + modelMap["alert_type_bucket"] = *model.AlertTypeBucket + } + if model.ClusterID != nil { + modelMap["cluster_id"] = flex.IntValue(model.ClusterID) + } + if model.ClusterName != nil { + modelMap["cluster_name"] = *model.ClusterName + } + if model.DedupCount != nil { + modelMap["dedup_count"] = flex.IntValue(model.DedupCount) + } + if model.DedupTimestamps != nil { + modelMap["dedup_timestamps"] = model.DedupTimestamps + } + if model.FirstTimestampUsecs != nil { + modelMap["first_timestamp_usecs"] = flex.IntValue(model.FirstTimestampUsecs) + } + if model.ID != nil { + modelMap["id"] = *model.ID + } + if model.LatestTimestampUsecs != nil { + modelMap["latest_timestamp_usecs"] = flex.IntValue(model.LatestTimestampUsecs) + } + if model.PropertyList != nil { + propertyList := []map[string]interface{}{} + for _, propertyListItem := range model.PropertyList { + propertyListItemMap, err := DataSourceIbmBackupRecoveryManagerGetManagementAlertsLabelToMap(&propertyListItem) // #nosec G601 + if err != nil { + return modelMap, err + } + propertyList = append(propertyList, propertyListItemMap) + } + modelMap["property_list"] = propertyList + } + if model.RegionID != nil { + modelMap["region_id"] = *model.RegionID + } + if model.ResolutionIdString != nil { + modelMap["resolution_id_string"] = *model.ResolutionIdString + } + if model.ServiceInstanceID != nil { + modelMap["service_instance_id"] = *model.ServiceInstanceID + } + if model.Severity != nil { + modelMap["severity"] = *model.Severity + } + if model.Vaults != nil { + vaults := []map[string]interface{}{} + for _, vaultsItem := range model.Vaults { + vaultsItemMap, err := DataSourceIbmBackupRecoveryManagerGetManagementAlertsVaultToMap(&vaultsItem) // #nosec G601 + if err != nil { + return modelMap, err + } + vaults = append(vaults, vaultsItemMap) + } + modelMap["vaults"] = vaults + } + return modelMap, nil +} + +func DataSourceIbmBackupRecoveryManagerGetManagementAlertsAlertDocumentToMap(model *backuprecoveryv1.AlertDocument) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.AlertCause != nil { + modelMap["alert_cause"] = *model.AlertCause + } + if model.AlertDescription != nil { + modelMap["alert_description"] = *model.AlertDescription + } + if model.AlertHelpText != nil { + modelMap["alert_help_text"] = *model.AlertHelpText + } + if model.AlertName != nil { + modelMap["alert_name"] = *model.AlertName + } + if model.AlertSummary != nil { + modelMap["alert_summary"] = *model.AlertSummary + } + return modelMap, nil +} + +func DataSourceIbmBackupRecoveryManagerGetManagementAlertsLabelToMap(model *backuprecoveryv1.Label) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + modelMap["key"] = *model.Key + modelMap["value"] = *model.Value + return modelMap, nil +} + +func DataSourceIbmBackupRecoveryManagerGetManagementAlertsVaultToMap(model *backuprecoveryv1.Vault) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.GlobalVaultID != nil { + modelMap["global_vault_id"] = *model.GlobalVaultID + } + if model.RegionID != nil { + modelMap["region_id"] = *model.RegionID + } + if model.RegionName != nil { + modelMap["region_name"] = *model.RegionName + } + if model.VaultName != nil { + modelMap["vault_name"] = *model.VaultName + } + return modelMap, nil +} diff --git a/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_management_alerts_summary.go b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_management_alerts_summary.go new file mode 100644 index 0000000000..b133295dc2 --- /dev/null +++ b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_management_alerts_summary.go @@ -0,0 +1,203 @@ +// Copyright IBM Corp. 2025 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.96.1-5136e54a-20241108-203028 + */ + +package backuprecovery + +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-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/ibm-backup-recovery-sdk-go/backuprecoveryv1" +) + +func DataSourceIbmBackupRecoveryManagerGetManagementAlertsSummary() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmBackupRecoveryManagerGetManagementAlertsSummaryRead, + + Schema: map[string]*schema.Schema{ + "cluster_identifiers": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Specifies the list of cluster identifiers. Format is clusterId:clusterIncarnationId.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "start_time_usecs": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Description: "Filter by start time. Specify the start time as a Unix epoch Timestamp (in microseconds). By default it is current time minus a day.", + }, + "end_time_usecs": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Description: "Filter by end time. Specify the end time as a Unix epoch Timestamp (in microseconds). By default it is current time.", + }, + "states_list": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Specifies list of alert states to filter alerts by. If not specified, only open alerts will be used to get summary.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "alerts_summary": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies a list of alerts summary grouped by category.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "category": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Category of alerts by which summary is grouped.", + }, + "critical_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies count of critical alerts.", + }, + "info_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies count of info alerts.", + }, + "total_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies count of total alerts.", + }, + "type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Type/bucket that this alert category belongs to.", + }, + "warning_count": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies count of warning alerts.", + }, + }, + }, + }, + }, + } +} + +func dataSourceIbmBackupRecoveryManagerGetManagementAlertsSummaryRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + managementApiClient, err := meta.(conns.ClientSession).BackupRecoveryManagerV1() + if err != nil { + tfErr := flex.DiscriminatedTerraformErrorf(err, err.Error(), "(Data) ibm_backup_recovery_manager_get_management_alerts_summary", "read", "initialize-client") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + bmxsession, err := meta.(conns.ClientSession).BluemixSession() + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("unable to get clientSession"), "ibm_backup_recovery_manager_get_management_alerts_summary", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + endpointType := d.Get("endpoint_type").(string) + instanceId, region := getInstanceIdAndRegion(d) + managementApiClient, err = setManagerClientAuth(managementApiClient, bmxsession, region, endpointType) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("unable to set authenticator for clientSession: %s", err), "ibm_backup_recovery_manager_get_management_alerts_summary", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + if instanceId != "" { + managementApiClient = getManagerClientWithInstanceEndpoint(managementApiClient, bmxsession, instanceId, region, endpointType) + } + + getManagementAlertsSummaryOptions := &backuprecoveryv1.GetManagementAlertsSummaryOptions{} + + if _, ok := d.GetOk("cluster_identifiers"); ok { + var clusterIdentifiers []string + for _, v := range d.Get("cluster_identifiers").([]interface{}) { + clusterIdentifiersItem := v.(string) + clusterIdentifiers = append(clusterIdentifiers, clusterIdentifiersItem) + } + getManagementAlertsSummaryOptions.SetClusterIdentifiers(clusterIdentifiers) + } + if _, ok := d.GetOk("start_time_usecs"); ok { + getManagementAlertsSummaryOptions.SetStartTimeUsecs(int64(d.Get("start_time_usecs").(int))) + } + if _, ok := d.GetOk("end_time_usecs"); ok { + getManagementAlertsSummaryOptions.SetEndTimeUsecs(int64(d.Get("end_time_usecs").(int))) + } + if _, ok := d.GetOk("states_list"); ok { + var statesList []string + for _, v := range d.Get("states_list").([]interface{}) { + statesListItem := v.(string) + statesList = append(statesList, statesListItem) + } + getManagementAlertsSummaryOptions.SetStatesList(statesList) + } + + alertsManagementSummaryResponse, _, err := managementApiClient.GetManagementAlertsSummaryWithContext(context, getManagementAlertsSummaryOptions) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("GetManagementAlertsSummaryWithContext failed: %s", err.Error()), "(Data) ibm_backup_recovery_manager_get_management_alerts_summary", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + d.SetId(dataSourceIbmBackupRecoveryManagerGetManagementAlertsSummaryID(d)) + + if !core.IsNil(alertsManagementSummaryResponse.AlertsSummary) { + alertsSummary := []map[string]interface{}{} + for _, alertsSummaryItem := range alertsManagementSummaryResponse.AlertsSummary { + alertsSummaryItemMap, err := DataSourceIbmBackupRecoveryManagerGetManagementAlertsSummaryAlertGroupSummaryToMap(&alertsSummaryItem) // #nosec G601 + if err != nil { + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "(Data) ibm_backup_recovery_manager_get_management_alerts_summary", "read", "alerts_summary-to-map").GetDiag() + } + alertsSummary = append(alertsSummary, alertsSummaryItemMap) + } + if err = d.Set("alerts_summary", alertsSummary); err != nil { + return flex.DiscriminatedTerraformErrorf(err, fmt.Sprintf("Error setting alerts_summary: %s", err), "(Data) ibm_backup_recovery_manager_get_management_alerts_summary", "read", "set-alerts_summary").GetDiag() + } + } + + return nil +} + +// dataSourceIbmBackupRecoveryManagerGetManagementAlertsSummaryID returns a reasonable ID for the list. +func dataSourceIbmBackupRecoveryManagerGetManagementAlertsSummaryID(d *schema.ResourceData) string { + return time.Now().UTC().String() +} + +func DataSourceIbmBackupRecoveryManagerGetManagementAlertsSummaryAlertGroupSummaryToMap(model *backuprecoveryv1.AlertGroupSummary) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Category != nil { + modelMap["category"] = *model.Category + } + if model.CriticalCount != nil { + modelMap["critical_count"] = flex.IntValue(model.CriticalCount) + } + if model.InfoCount != nil { + modelMap["info_count"] = flex.IntValue(model.InfoCount) + } + if model.TotalCount != nil { + modelMap["total_count"] = flex.IntValue(model.TotalCount) + } + if model.Type != nil { + modelMap["type"] = *model.Type + } + if model.WarningCount != nil { + modelMap["warning_count"] = flex.IntValue(model.WarningCount) + } + return modelMap, nil +} diff --git a/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_management_alerts_summary_test.go b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_management_alerts_summary_test.go new file mode 100644 index 0000000000..c1d3d3c8c0 --- /dev/null +++ b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_management_alerts_summary_test.go @@ -0,0 +1,39 @@ +// Copyright IBM Corp. 2025 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.96.1-5136e54a-20241108-203028 + */ + +package backuprecovery_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmBackupRecoveryManagerGetManagementAlertsSummaryDataSourceBasic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmBackupRecoveryManagerGetManagementAlertsSummaryDataSourceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_backup_recovery_manager_get_management_alerts_summary.backup_recovery_manager_get_management_alerts_summary_instance", "id"), + ), + }, + }, + }) +} + +func testAccCheckIbmBackupRecoveryManagerGetManagementAlertsSummaryDataSourceConfigBasic() string { + return fmt.Sprintf(` + data "ibm_backup_recovery_manager_get_management_alerts_summary" "backup_recovery_manager_get_management_alerts_summary_instance" { + } + `) +} diff --git a/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_management_alerts_test.go b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_management_alerts_test.go new file mode 100644 index 0000000000..9071f1af5f --- /dev/null +++ b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_management_alerts_test.go @@ -0,0 +1,41 @@ +// Copyright IBM Corp. 2025 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.96.1-5136e54a-20241108-203028 + */ + +package backuprecovery_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmBackupRecoveryManagerGetManagementAlertsDataSourceBasic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmBackupRecoveryManagerGetManagementAlertsDataSourceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_backup_recovery_manager_get_management_alerts.backup_recovery_manager_get_management_alerts_instance", "id"), + resource.TestCheckResourceAttrSet("data.ibm_backup_recovery_manager_get_management_alerts.backup_recovery_manager_get_management_alerts_instance", "alerts_list.#"), + ), + }, + }, + }) +} + +func testAccCheckIbmBackupRecoveryManagerGetManagementAlertsDataSourceConfigBasic() string { + return fmt.Sprintf(` + data "ibm_backup_recovery_manager_get_management_alerts" "backup_recovery_manager_get_management_alerts_instance" { + + } + `) +} diff --git a/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_upgrades_info.go b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_upgrades_info.go new file mode 100644 index 0000000000..65273e6fdd --- /dev/null +++ b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_upgrades_info.go @@ -0,0 +1,252 @@ +// Copyright IBM Corp. 2025 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.96.1-5136e54a-20241108-203028 + */ + +package backuprecovery + +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-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/ibm-backup-recovery-sdk-go/backuprecoveryv1" +) + +func DataSourceIbmBackupRecoveryManagerGetUpgradesInfo() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceIbmBackupRecoveryManagerGetUpgradesInfoRead, + + Schema: map[string]*schema.Schema{ + "cluster_identifiers": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Fetch upgrade progress details for a list of cluster identifiers in format clusterId:clusterIncarnationId.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "upgrades_info": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cluster_id": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies cluster's id.", + }, + "cluster_incarnation_id": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Specifies cluster's incarnation id.", + }, + "patch_software_version": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Patch software version against which these logs are generated. This is specified for Patch type only.", + }, + "software_version": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Upgrade software version against which these logs are generated.", + }, + "type": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Specifies the type of upgrade on a cluster.", + }, + "upgrade_logs": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Upgrade logs per node.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "logs": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Upgrade logs for the node.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "log": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "One log statement of the complete logs.", + }, + "time_stamp": &schema.Schema{ + Type: schema.TypeInt, + Computed: true, + Description: "Time at which this log got generated.", + }, + }, + }, + }, + "node_id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Id of the node.", + }, + }, + }, + }, + "upgrade_percent_complete": &schema.Schema{ + Type: schema.TypeFloat, + Computed: true, + Description: "Upgrade percentage complete so far.", + }, + "upgrade_status": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Upgrade status.", + }, + }, + }, + }, + }, + } +} + +func dataSourceIbmBackupRecoveryManagerGetUpgradesInfoRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + managementApiClient, err := meta.(conns.ClientSession).BackupRecoveryManagerV1() + if err != nil { + tfErr := flex.DiscriminatedTerraformErrorf(err, err.Error(), "(Data) ibm_backup_recovery_manager_get_upgrades_info", "read", "initialize-client") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + bmxsession, err := meta.(conns.ClientSession).BluemixSession() + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("unable to get clientSession"), "ibm_backup_recovery_manager_get_upgrades_info", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + endpointType := d.Get("endpoint_type").(string) + instanceId, region := getInstanceIdAndRegion(d) + managementApiClient, err = setManagerClientAuth(managementApiClient, bmxsession, region, endpointType) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("unable to set authenticator for clientSession: %s", err), "ibm_backup_recovery_manager_get_upgrades_info", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + if instanceId != "" { + managementApiClient = getManagerClientWithInstanceEndpoint(managementApiClient, bmxsession, instanceId, region, endpointType) + } + + clustersUpgradesInfoOptions := &backuprecoveryv1.ClustersUpgradesInfoOptions{} + + if _, ok := d.GetOk("cluster_identifiers"); ok { + var clusterIdentifiers []string + for _, v := range d.Get("cluster_identifiers").([]interface{}) { + clusterIdentifiersItem := v.(string) + clusterIdentifiers = append(clusterIdentifiers, clusterIdentifiersItem) + } + clustersUpgradesInfoOptions.SetClusterIdentifiers(clusterIdentifiers) + } + + upgradesInfo, _, err := managementApiClient.ClustersUpgradesInfoWithContext(context, clustersUpgradesInfoOptions) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("ClustersUpgradesInfoWithContext failed: %s", err.Error()), "(Data) ibm_backup_recovery_manager_get_upgrades_info", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + d.SetId(dataSourceIbmBackupRecoveryManagerGetUpgradesInfoID(d)) + + if !core.IsNil(upgradesInfo) { + upgradesInfoResult := []map[string]interface{}{} + for _, upgradesInfoItem := range upgradesInfo { + upgradesInfoItemMap, err := DataSourceIbmBackupRecoveryManagerGetUpgradesInfoUpgradeInfoToMap(&upgradesInfoItem) // #nosec G601 + if err != nil { + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "(Data) ibm_backup_recovery_manager_get_upgrades_info", "read", "upgrades_info-to-map").GetDiag() + } + upgradesInfoResult = append(upgradesInfoResult, upgradesInfoItemMap) + } + if err = d.Set("upgrades_info", upgradesInfoResult); err != nil { + return flex.DiscriminatedTerraformErrorf(err, fmt.Sprintf("Error setting upgrades_info: %s", err), "(Data) ibm_backup_recovery_manager_get_upgrades_info", "read", "set-upgrades_info").GetDiag() + } + } + + return nil +} + +// dataSourceIbmBackupRecoveryManagerGetUpgradesInfoID returns a reasonable ID for the list. +func dataSourceIbmBackupRecoveryManagerGetUpgradesInfoID(d *schema.ResourceData) string { + return time.Now().UTC().String() +} + +func DataSourceIbmBackupRecoveryManagerGetUpgradesInfoUpgradeInfoToMap(model *backuprecoveryv1.UpgradeInfo) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ClusterID != nil { + modelMap["cluster_id"] = flex.IntValue(model.ClusterID) + } + if model.ClusterIncarnationID != nil { + modelMap["cluster_incarnation_id"] = flex.IntValue(model.ClusterIncarnationID) + } + if model.PatchSoftwareVersion != nil { + modelMap["patch_software_version"] = *model.PatchSoftwareVersion + } + if model.SoftwareVersion != nil { + modelMap["software_version"] = *model.SoftwareVersion + } + if model.Type != nil { + modelMap["type"] = *model.Type + } + if model.UpgradeLogs != nil { + upgradeLogs := []map[string]interface{}{} + for _, upgradeLogsItem := range model.UpgradeLogs { + upgradeLogsItemMap, err := DataSourceIbmBackupRecoveryManagerGetUpgradesInfoNodeUpgradeLogToMap(&upgradeLogsItem) // #nosec G601 + if err != nil { + return modelMap, err + } + upgradeLogs = append(upgradeLogs, upgradeLogsItemMap) + } + modelMap["upgrade_logs"] = upgradeLogs + } + if model.UpgradePercentComplete != nil { + modelMap["upgrade_percent_complete"] = *model.UpgradePercentComplete + } + if model.UpgradeStatus != nil { + modelMap["upgrade_status"] = *model.UpgradeStatus + } + return modelMap, nil +} + +func DataSourceIbmBackupRecoveryManagerGetUpgradesInfoNodeUpgradeLogToMap(model *backuprecoveryv1.NodeUpgradeLog) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Logs != nil { + logs := []map[string]interface{}{} + for _, logsItem := range model.Logs { + logsItemMap, err := DataSourceIbmBackupRecoveryManagerGetUpgradesInfoUpgradeLogToMap(&logsItem) // #nosec G601 + if err != nil { + return modelMap, err + } + logs = append(logs, logsItemMap) + } + modelMap["logs"] = logs + } + if model.NodeID != nil { + modelMap["node_id"] = *model.NodeID + } + return modelMap, nil +} + +func DataSourceIbmBackupRecoveryManagerGetUpgradesInfoUpgradeLogToMap(model *backuprecoveryv1.UpgradeLog) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.Log != nil { + modelMap["log"] = *model.Log + } + if model.TimeStamp != nil { + modelMap["time_stamp"] = flex.IntValue(model.TimeStamp) + } + return modelMap, nil +} diff --git a/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_upgrades_info_test.go b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_upgrades_info_test.go new file mode 100644 index 0000000000..1b5de04e8c --- /dev/null +++ b/ibm/service/backuprecovery/data_source_ibm_backup_recovery_manager_get_upgrades_info_test.go @@ -0,0 +1,40 @@ +// Copyright IBM Corp. 2025 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.96.1-5136e54a-20241108-203028 + */ + +package backuprecovery_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmBackupRecoveryManagerGetUpgradesInfoDataSourceBasic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmBackupRecoveryManagerGetUpgradesInfoDataSourceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.ibm_backup_recovery_manager_get_upgrades_info.backup_recovery_manager_get_upgrades_info_instance", "id"), + ), + }, + }, + }) +} + +func testAccCheckIbmBackupRecoveryManagerGetUpgradesInfoDataSourceConfigBasic() string { + return fmt.Sprintf(` + data "ibm_backup_recovery_manager_get_upgrades_info" "backup_recovery_manager_get_upgrades_info_instance" { + cluster_identifiers = [ "3524800407225868","8305184241232842","7463743295903869","1589079364046703","90858563991288","4532338433036076" ] + } + `) +} diff --git a/ibm/service/backuprecovery/resource_ibm_backup_recovery_manager_cancel_cluster_upgrades.go b/ibm/service/backuprecovery/resource_ibm_backup_recovery_manager_cancel_cluster_upgrades.go new file mode 100644 index 0000000000..af78a3348d --- /dev/null +++ b/ibm/service/backuprecovery/resource_ibm_backup_recovery_manager_cancel_cluster_upgrades.go @@ -0,0 +1,192 @@ +// Copyright IBM Corp. 2025 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.96.1-5136e54a-20241108-203028 + */ + +package backuprecovery + +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-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/ibm-backup-recovery-sdk-go/backuprecoveryv1" +) + +func ResourceIbmBackupRecoveryManagerCancelClusterUpgrades() *schema.Resource { + return &schema.Resource{ + CreateContext: resourceIbmBackupRecoveryManagerCancelClusterUpgradesCreate, + ReadContext: resourceIbmBackupRecoveryManagerCancelClusterUpgradesRead, + DeleteContext: resourceIbmBackupRecoveryManagerCancelClusterUpgradesDelete, + UpdateContext: resourceIbmBackupRecoveryManagerCancelClusterUpgradesUpdate, + Importer: &schema.ResourceImporter{}, + + Schema: map[string]*schema.Schema{ + "cluster_identifiers": &schema.Schema{ + Type: schema.TypeList, + Required: true, + ForceNew: true, + Description: "Specifies the list of cluster identifiers. The format is clusterId:clusterIncarnationId.", + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "cancelled_upgrade_response_list": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies list of cluster scheduled uprgade cancel response.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "error_message": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "Specifies an error message if failed to cancel a scheduled upgrade.", + }, + "is_upgrade_cancel_successful": &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + Computed: true, + Description: "Specifies if scheduled upgrade cancelling was successful.", + }, + "cluster_id": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Computed: true, + Description: "Specifies cluster id.", + }, + "cluster_incarnation_id": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Computed: true, + Description: "Specifies cluster incarnation id.", + }, + }, + }, + }, + }, + } +} + +func resourceIbmBackupRecoveryManagerCancelClusterUpgradesCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + managementApiClient, err := meta.(conns.ClientSession).BackupRecoveryManagerV1() + if err != nil { + tfErr := flex.DiscriminatedTerraformErrorf(err, err.Error(), "ibm_backup_recovery_manager_cancel_cluster_upgrades", "read", "initialize-client") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + bmxsession, err := meta.(conns.ClientSession).BluemixSession() + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("unable to get clientSession"), "ibm_backup_recovery_manager_cancel_cluster_upgrades", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + endpointType := d.Get("endpoint_type").(string) + instanceId, region := getInstanceIdAndRegion(d) + managementApiClient, err = setManagerClientAuth(managementApiClient, bmxsession, region, endpointType) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("unable to set authenticator for clientSession: %s", err), "ibm_backup_recovery_manager_cancel_cluster_upgrades", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + if instanceId != "" { + managementApiClient = getManagerClientWithInstanceEndpoint(managementApiClient, bmxsession, instanceId, region, endpointType) + } + + deleteClustersUpgradesOptions := &backuprecoveryv1.DeleteClustersUpgradesOptions{} + + if _, ok := d.GetOk("cluster_identifiers"); ok { + var clusterIdentifiers []string + for _, v := range d.Get("cluster_identifiers").([]interface{}) { + clusterIdentifiersItem := v.(string) + clusterIdentifiers = append(clusterIdentifiers, clusterIdentifiersItem) + } + deleteClustersUpgradesOptions.SetClusterIdentifiers(clusterIdentifiers) + } + + upgradesCancelResponse, _, err := managementApiClient.DeleteClustersUpgradesWithContext(context, deleteClustersUpgradesOptions) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("DeleteClustersUpgradesWithContext failed: %s", err.Error()), "ibm_backup_recovery_manager_cancel_cluster_upgrades", "read") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + d.SetId(resourceIbmBackupRecoveryManagerCancelClusterUpgradesID(d)) + + if !core.IsNil(upgradesCancelResponse) { + cancelledUpgradeResponseListResult := []map[string]interface{}{} + for _, cancelledUpgradeResponseListItem := range upgradesCancelResponse { + cancelledUpgradeResponseListItemMap, err := ResourceIbmBackupRecoveryManagerCancelClusterUpgradesUpgradeCancelResponseToMap(&cancelledUpgradeResponseListItem) // #nosec G601 + if err != nil { + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "ibm_backup_recovery_manager_cancel_cluster_upgrades", "read", "cancelled_upgrade_response_list-to-map").GetDiag() + } + cancelledUpgradeResponseListResult = append(cancelledUpgradeResponseListResult, cancelledUpgradeResponseListItemMap) + } + if err = d.Set("cancelled_upgrade_response_list", cancelledUpgradeResponseListResult); err != nil { + err = fmt.Errorf("Error setting cancelled_upgrade_response_list: %s", err) + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "ibm_backup_recovery_manager_cancel_cluster_upgrades", "read", "set-cancelled_upgrade_response_list").GetDiag() + } + } + + return resourceIbmBackupRecoveryManagerCancelClusterUpgradesRead(context, d, meta) +} + +func resourceIbmBackupRecoveryManagerCancelClusterUpgradesID(d *schema.ResourceData) string { + return time.Now().UTC().String() +} + +func resourceIbmBackupRecoveryManagerCancelClusterUpgradesRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + + return nil +} + +func resourceIbmBackupRecoveryManagerCancelClusterUpgradesUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + // This resource does not support a "delete" operation. + var diags diag.Diagnostics + warning := diag.Diagnostic{ + Severity: diag.Warning, + Summary: "Update Not Supported", + Detail: "Update operation for this resource is not supported and will only affect the terraform statefile. No changes will be made to the backend resource.", + } + diags = append(diags, warning) + return diags +} + +func resourceIbmBackupRecoveryManagerCancelClusterUpgradesDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + // This resource does not support a "delete" operation. + var diags diag.Diagnostics + warning := diag.Diagnostic{ + Severity: diag.Warning, + Summary: "Delete Not Supported", + Detail: "The resource definition will be only be removed from the terraform statefile. This resource cannot be deleted from the backend. ", + } + diags = append(diags, warning) + d.SetId("") + return diags +} + +func ResourceIbmBackupRecoveryManagerCancelClusterUpgradesUpgradeCancelResponseToMap(model *backuprecoveryv1.UpgradeCancelResponse) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ErrorMessage != nil { + modelMap["error_message"] = *model.ErrorMessage + } + if model.IsUpgradeCancelSuccessful != nil { + modelMap["is_upgrade_cancel_successful"] = *model.IsUpgradeCancelSuccessful + } + if model.ClusterID != nil { + modelMap["cluster_id"] = flex.IntValue(model.ClusterID) + } + if model.ClusterIncarnationID != nil { + modelMap["cluster_incarnation_id"] = flex.IntValue(model.ClusterIncarnationID) + } + return modelMap, nil +} diff --git a/ibm/service/backuprecovery/resource_ibm_backup_recovery_manager_cancel_cluster_upgrades_test.go b/ibm/service/backuprecovery/resource_ibm_backup_recovery_manager_cancel_cluster_upgrades_test.go new file mode 100644 index 0000000000..0ca935172d --- /dev/null +++ b/ibm/service/backuprecovery/resource_ibm_backup_recovery_manager_cancel_cluster_upgrades_test.go @@ -0,0 +1,38 @@ +// Copyright IBM Corp. 2025 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package backuprecovery_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmBackupRecoveryManagerCancelClusterUpgradesBasic(t *testing.T) { + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmBackupRecoveryManagerCancelClusterUpgradesConfigBasic(), + Destroy: false, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("resource.ibm_backup_recovery_manager_cancel_cluster_upgrades.backup_recovery_manager_cancel_cluster_upgrades_instance", "id"), + ), + }, + }, + }) +} + +func testAccCheckIbmBackupRecoveryManagerCancelClusterUpgradesConfigBasic() string { + return fmt.Sprintf(` + resource "ibm_backup_recovery_manager_cancel_cluster_upgrades" "backup_recovery_manager_cancel_cluster_upgrades_instance" { + cluster_identifiers = ["3524800407225868"] + } + `) +} diff --git a/ibm/service/backuprecovery/resource_ibm_backup_recovery_manager_create_cluster_upgrades.go b/ibm/service/backuprecovery/resource_ibm_backup_recovery_manager_create_cluster_upgrades.go new file mode 100644 index 0000000000..06ffbba028 --- /dev/null +++ b/ibm/service/backuprecovery/resource_ibm_backup_recovery_manager_create_cluster_upgrades.go @@ -0,0 +1,390 @@ +// Copyright IBM Corp. 2025 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.96.1-5136e54a-20241108-203028 + */ + +package backuprecovery + +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-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/ibm-backup-recovery-sdk-go/backuprecoveryv1" +) + +func ResourceIbmBackupRecoveryManagerCreateClusterUpgrades() *schema.Resource { + return &schema.Resource{ + CreateContext: resourceIbmBackupRecoveryManagerCreateClusterUpgradesCreate, + ReadContext: resourceIbmBackupRecoveryManagerCreateClusterUpgradesRead, + DeleteContext: resourceIbmBackupRecoveryManagerCreateClusterUpgradesDelete, + UpdateContext: resourceIbmBackupRecoveryManagerCreateClusterUpgradesUpdate, + Importer: &schema.ResourceImporter{}, + + Schema: map[string]*schema.Schema{ + "auth_headers": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Description: "Specifies the optional headers for upgrade request.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "key": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "Specifies the key or name of the header.", + }, + "value": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "Specifies the value of the header.", + }, + }, + }, + }, + "clusters": &schema.Schema{ + Type: schema.TypeList, + Required: true, + ForceNew: true, + Description: "Array for clusters to be upgraded.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cluster_id": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Description: "Specifies cluster id.", + }, + "cluster_incarnation_id": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Description: "Specifies cluster incarnation id.", + }, + "current_version": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "Specifies current version of cluster.", + }, + }, + }, + }, + "interval_for_rolling_upgrade_in_hours": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + ForceNew: true, + Description: "Specifies the difference of time between two cluster's upgrade.", + }, + "package_url": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Description: "Specifies URL from which package can be downloaded. Note: This option is only supported in Multi-Cluster Manager (MCM).", + }, + "patch_upgrade_params": &schema.Schema{ + Type: schema.TypeList, + MaxItems: 1, + Optional: true, + ForceNew: true, + Description: "Specifies the parameters for patch upgrade request.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "auth_headers": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Specifies the optional headers for the patch cluster request.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "key": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "Specifies the key or name of the header.", + }, + "value": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "Specifies the value of the header.", + }, + }, + }, + }, + "ignore_pre_checks_failure": &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "Specify if pre check results can be ignored.", + }, + "package_url": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "Specifies URL from which patch package can be downloaded. Note: This option is only supported in Multi-Cluster Manager (MCM).", + }, + "target_version": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "Specifies target patch version to which clusters are to be upgraded.", + }, + }, + }, + }, + "target_version": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Description: "Specifies target version to which clusters are to be upgraded.", + }, + "time_stamp_to_upgrade_at_msecs": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + ForceNew: true, + Description: "Specifies the time in msecs at which the cluster has to be upgraded.", + }, + "type": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Default: "Upgrade", + ForceNew: true, + Description: "Specifies the type of upgrade to be performed on a cluster.", + }, + "upgrade_response_list": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies a list of disks to exclude from being protected. This is only applicable to VM objects.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "error_message": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "Specifies error message if failed to schedule upgrade.", + }, + "is_upgrade_scheduling_successful": &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + Computed: true, + Description: "Specifies if upgrade scheduling was successsful.", + }, + "cluster_id": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Computed: true, + Description: "Specifies cluster id.", + }, + "cluster_incarnation_id": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Computed: true, + Description: "Specifies cluster incarnation id.", + }, + }, + }, + }, + }, + } +} + +func resourceIbmBackupRecoveryManagerCreateClusterUpgradesCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + managementApiClient, err := meta.(conns.ClientSession).BackupRecoveryManagerV1() + if err != nil { + tfErr := flex.DiscriminatedTerraformErrorf(err, err.Error(), "ibm_backup_recovery_manager_create_cluster_upgrades", "create", "initialize-client") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + bmxsession, err := meta.(conns.ClientSession).BluemixSession() + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("unable to get clientSession"), "ibm_backup_recovery_manager_cancel_cluster_upgrades", "create") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + endpointType := d.Get("endpoint_type").(string) + instanceId, region := getInstanceIdAndRegion(d) + managementApiClient, err = setManagerClientAuth(managementApiClient, bmxsession, region, endpointType) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("unable to set authenticator for clientSession: %s", err), "ibm_backup_recovery_manager_create_cluster_upgrades", "create") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + if instanceId != "" { + managementApiClient = getManagerClientWithInstanceEndpoint(managementApiClient, bmxsession, instanceId, region, endpointType) + } + + createClustersUpgradesOptions := &backuprecoveryv1.CreateClustersUpgradesOptions{} + + if _, ok := d.GetOk("auth_headers"); ok { + var authHeaders []backuprecoveryv1.AuthHeaderForClusterUpgrade + for _, v := range d.Get("auth_headers").([]interface{}) { + value := v.(map[string]interface{}) + authHeadersItem, err := ResourceIbmBackupRecoveryManagerCreateClusterUpgradesMapToAuthHeaderForClusterUpgrade(value) + if err != nil { + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "ibm_backup_recovery_manager_create_cluster_upgrades", "create", "parse-auth_headers").GetDiag() + } + authHeaders = append(authHeaders, *authHeadersItem) + } + createClustersUpgradesOptions.SetAuthHeaders(authHeaders) + } + if _, ok := d.GetOk("clusters"); ok { + var clusters []backuprecoveryv1.Upgrade + for _, v := range d.Get("clusters").([]interface{}) { + value := v.(map[string]interface{}) + clustersItem, err := ResourceIbmBackupRecoveryManagerCreateClusterUpgradesMapToUpgrade(value) + if err != nil { + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "ibm_backup_recovery_manager_create_cluster_upgrades", "create", "parse-clusters").GetDiag() + } + clusters = append(clusters, *clustersItem) + } + createClustersUpgradesOptions.SetClusters(clusters) + } + if _, ok := d.GetOk("interval_for_rolling_upgrade_in_hours"); ok { + createClustersUpgradesOptions.SetIntervalForRollingUpgradeInHours(int64(d.Get("interval_for_rolling_upgrade_in_hours").(int))) + } + if _, ok := d.GetOk("package_url"); ok { + createClustersUpgradesOptions.SetPackageURL(d.Get("package_url").(string)) + } + if _, ok := d.GetOk("patch_upgrade_params"); ok { + patchUpgradeParamsModel, err := ResourceIbmBackupRecoveryManagerCreateClusterUpgradesMapToPatchUpgradeParams(d.Get("patch_upgrade_params.0").(map[string]interface{})) + if err != nil { + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "ibm_backup_recovery_manager_create_cluster_upgrades", "create", "parse-patch_upgrade_params").GetDiag() + } + createClustersUpgradesOptions.SetPatchUpgradeParams(patchUpgradeParamsModel) + } + if _, ok := d.GetOk("target_version"); ok { + createClustersUpgradesOptions.SetTargetVersion(d.Get("target_version").(string)) + } + if _, ok := d.GetOk("time_stamp_to_upgrade_at_msecs"); ok { + createClustersUpgradesOptions.SetTimeStampToUpgradeAtMsecs(int64(d.Get("time_stamp_to_upgrade_at_msecs").(int))) + } + if _, ok := d.GetOk("type"); ok { + createClustersUpgradesOptions.SetType(d.Get("type").(string)) + } + + upgradesResponse, _, err := managementApiClient.CreateClustersUpgradesWithContext(context, createClustersUpgradesOptions) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("CreateClustersUpgradesWithContext failed: %s", err.Error()), "ibm_backup_recovery_manager_create_cluster_upgrades", "create") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + d.SetId(resourceIbmBackupRecoveryManagerCreateClusterUpgradesID(d)) + + if !core.IsNil(upgradesResponse) { + upgradeResponseListResult := []map[string]interface{}{} + for _, upgradeResponseListItem := range upgradesResponse { + upgradeResponseListItemMap, err := ResourceIbmBackupRecoveryManagerCreateClusterUpgradesUpgradeResponseToMap(&upgradeResponseListItem) // #nosec G601 + if err != nil { + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "ibm_backup_recovery_manager_create_cluster_upgrades", "read", "upgrade_response_list-to-map").GetDiag() + } + upgradeResponseListResult = append(upgradeResponseListResult, upgradeResponseListItemMap) + } + if err = d.Set("upgrade_response_list", upgradeResponseListResult); err != nil { + err = fmt.Errorf("Error setting upgrade_response_list: %s", err) + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "ibm_backup_recovery_manager_create_cluster_upgrades", "read", "set-upgrade_response_list").GetDiag() + } + } + + return resourceIbmBackupRecoveryManagerCreateClusterUpgradesRead(context, d, meta) +} + +func ResourceIbmBackupRecoveryManagerCreateClusterUpgradesUpgradeResponseToMap(model *backuprecoveryv1.UpgradeResponse) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ErrorMessage != nil { + modelMap["error_message"] = *model.ErrorMessage + } + if model.IsUpgradeSchedulingSuccessful != nil { + modelMap["is_upgrade_scheduling_successful"] = *model.IsUpgradeSchedulingSuccessful + } + if model.ClusterID != nil { + modelMap["cluster_id"] = flex.IntValue(model.ClusterID) + } + if model.ClusterIncarnationID != nil { + modelMap["cluster_incarnation_id"] = flex.IntValue(model.ClusterIncarnationID) + } + return modelMap, nil +} + +func resourceIbmBackupRecoveryManagerCreateClusterUpgradesID(d *schema.ResourceData) string { + return time.Now().UTC().String() +} + +func resourceIbmBackupRecoveryManagerCreateClusterUpgradesRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + return nil +} + +func resourceIbmBackupRecoveryManagerCreateClusterUpgradesUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + // This resource does not support a "delete" operation. + var diags diag.Diagnostics + warning := diag.Diagnostic{ + Severity: diag.Warning, + Summary: "Update Not Supported", + Detail: "Update operation for this resource is not supported and will only affect the terraform statefile. No changes will be made to the backend resource. ", + } + diags = append(diags, warning) + return diags +} + +func resourceIbmBackupRecoveryManagerCreateClusterUpgradesDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + // This resource does not support a "delete" operation. + var diags diag.Diagnostics + warning := diag.Diagnostic{ + Severity: diag.Warning, + Summary: "Delete Not Supported", + Detail: "The resource definition will be only be removed from the terraform statefile. This resource cannot be deleted from the backend. ", + } + diags = append(diags, warning) + d.SetId("") + return diags +} + +func ResourceIbmBackupRecoveryManagerCreateClusterUpgradesMapToAuthHeaderForClusterUpgrade(modelMap map[string]interface{}) (*backuprecoveryv1.AuthHeaderForClusterUpgrade, error) { + model := &backuprecoveryv1.AuthHeaderForClusterUpgrade{} + model.Key = core.StringPtr(modelMap["key"].(string)) + model.Value = core.StringPtr(modelMap["value"].(string)) + return model, nil +} + +func ResourceIbmBackupRecoveryManagerCreateClusterUpgradesMapToUpgrade(modelMap map[string]interface{}) (*backuprecoveryv1.Upgrade, error) { + model := &backuprecoveryv1.Upgrade{} + if modelMap["cluster_id"] != nil { + model.ClusterID = core.Int64Ptr(int64(modelMap["cluster_id"].(int))) + } + if modelMap["cluster_incarnation_id"] != nil { + model.ClusterIncarnationID = core.Int64Ptr(int64(modelMap["cluster_incarnation_id"].(int))) + } + if modelMap["current_version"] != nil && modelMap["current_version"].(string) != "" { + model.CurrentVersion = core.StringPtr(modelMap["current_version"].(string)) + } + return model, nil +} + +func ResourceIbmBackupRecoveryManagerCreateClusterUpgradesMapToPatchUpgradeParams(modelMap map[string]interface{}) (*backuprecoveryv1.PatchUpgradeParams, error) { + model := &backuprecoveryv1.PatchUpgradeParams{} + if modelMap["auth_headers"] != nil { + authHeaders := []backuprecoveryv1.AuthHeaderForClusterUpgrade{} + for _, authHeadersItem := range modelMap["auth_headers"].([]interface{}) { + authHeadersItemModel, err := ResourceIbmBackupRecoveryManagerCreateClusterUpgradesMapToAuthHeaderForClusterUpgrade(authHeadersItem.(map[string]interface{})) + if err != nil { + return model, err + } + authHeaders = append(authHeaders, *authHeadersItemModel) + } + model.AuthHeaders = authHeaders + } + if modelMap["ignore_pre_checks_failure"] != nil { + model.IgnorePreChecksFailure = core.BoolPtr(modelMap["ignore_pre_checks_failure"].(bool)) + } + if modelMap["package_url"] != nil && modelMap["package_url"].(string) != "" { + model.PackageURL = core.StringPtr(modelMap["package_url"].(string)) + } + if modelMap["target_version"] != nil && modelMap["target_version"].(string) != "" { + model.TargetVersion = core.StringPtr(modelMap["target_version"].(string)) + } + return model, nil +} diff --git a/ibm/service/backuprecovery/resource_ibm_backup_recovery_manager_create_cluster_upgrades_test.go b/ibm/service/backuprecovery/resource_ibm_backup_recovery_manager_create_cluster_upgrades_test.go new file mode 100644 index 0000000000..8d92f0b727 --- /dev/null +++ b/ibm/service/backuprecovery/resource_ibm_backup_recovery_manager_create_cluster_upgrades_test.go @@ -0,0 +1,42 @@ +// Copyright IBM Corp. 2025 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package backuprecovery_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmBackupRecoveryManagerCreateClusterUpgradesBasic(t *testing.T) { + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmBackupRecoveryManagerCreateClusterUpgradesConfigBasic(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("resource.ibm_backup_recovery_manager_create_cluster_upgrades.backup_recovery_manager_create_cluster_upgrades_instance", "id"), + ), + Destroy: false, + }, + }, + }) +} + +func testAccCheckIbmBackupRecoveryManagerCreateClusterUpgradesConfigBasic() string { + return fmt.Sprintf(` + resource "ibm_backup_recovery_manager_create_cluster_upgrades" "backup_recovery_manager_create_cluster_upgrades_instance" { + clusters { + cluster_id = "3524800407225868" + cluster_incarnation_id = "1758305184241232842" + } + package_url = "https://s3.us-east.cloud-object-storage.appdomain.cloud/7.2.15/cluster_artifacts/cohesity-7.2.15_release-20250721_6aa24701.tar.gz" + } + `) +} diff --git a/ibm/service/backuprecovery/resource_ibm_backup_recovery_manager_update_cluster_upgrades.go b/ibm/service/backuprecovery/resource_ibm_backup_recovery_manager_update_cluster_upgrades.go new file mode 100644 index 0000000000..618aa4d10e --- /dev/null +++ b/ibm/service/backuprecovery/resource_ibm_backup_recovery_manager_update_cluster_upgrades.go @@ -0,0 +1,390 @@ +// Copyright IBM Corp. 2025 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +/* + * IBM OpenAPI Terraform Generator Version: 3.96.1-5136e54a-20241108-203028 + */ + +package backuprecovery + +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-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/ibm-backup-recovery-sdk-go/backuprecoveryv1" +) + +func ResourceIbmBackupRecoveryManagerUpdateClusterUpgrades() *schema.Resource { + return &schema.Resource{ + CreateContext: resourceIbmBackupRecoveryManagerUpdateClusterUpgradesCreate, + ReadContext: resourceIbmBackupRecoveryManagerUpdateClusterUpgradesRead, + DeleteContext: resourceIbmBackupRecoveryManagerUpdateClusterUpgradesDelete, + UpdateContext: resourceIbmBackupRecoveryManagerUpdateClusterUpgradesUpdate, + Importer: &schema.ResourceImporter{}, + + Schema: map[string]*schema.Schema{ + "auth_headers": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Description: "Specifies the optional headers for upgrade request.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "key": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "Specifies the key or name of the header.", + }, + "value": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "Specifies the value of the header.", + }, + }, + }, + }, + "clusters": &schema.Schema{ + Type: schema.TypeList, + Required: true, + ForceNew: true, + Description: "Array for clusters to be upgraded.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cluster_id": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Description: "Specifies cluster id.", + }, + "cluster_incarnation_id": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Description: "Specifies cluster incarnation id.", + }, + "current_version": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "Specifies current version of cluster.", + }, + }, + }, + }, + "interval_for_rolling_upgrade_in_hours": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + ForceNew: true, + Description: "Specifies the difference of time between two cluster's upgrade.", + }, + "package_url": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Description: "Specifies URL from which package can be downloaded. Note: This option is only supported in Multi-Cluster Manager (MCM).", + }, + "patch_upgrade_params": &schema.Schema{ + Type: schema.TypeList, + MaxItems: 1, + Optional: true, + ForceNew: true, + Description: "Specifies the parameters for patch upgrade request.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "auth_headers": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Description: "Specifies the optional headers for the patch cluster request.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "key": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "Specifies the key or name of the header.", + }, + "value": &schema.Schema{ + Type: schema.TypeString, + Required: true, + Description: "Specifies the value of the header.", + }, + }, + }, + }, + "ignore_pre_checks_failure": &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + Default: false, + Description: "Specify if pre check results can be ignored.", + }, + "package_url": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "Specifies URL from which patch package can be downloaded. Note: This option is only supported in Multi-Cluster Manager (MCM).", + }, + "target_version": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Description: "Specifies target patch version to which clusters are to be upgraded.", + }, + }, + }, + }, + "target_version": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Description: "Specifies target version to which clusters are to be upgraded.", + }, + "time_stamp_to_upgrade_at_msecs": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + ForceNew: true, + Description: "Specifies the time in msecs at which the cluster has to be upgraded.", + }, + "type": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Default: "Upgrade", + ForceNew: true, + Description: "Specifies the type of upgrade to be performed on a cluster.", + }, + "upgrade_response_list": &schema.Schema{ + Type: schema.TypeList, + Computed: true, + Description: "Specifies a list of disks to exclude from being protected. This is only applicable to VM objects.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "error_message": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "Specifies error message if failed to schedule upgrade.", + }, + "is_upgrade_scheduling_successful": &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + Computed: true, + Description: "Specifies if upgrade scheduling was successsful.", + }, + "cluster_id": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Computed: true, + Description: "Specifies cluster id.", + }, + "cluster_incarnation_id": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + Computed: true, + Description: "Specifies cluster incarnation id.", + }, + }, + }, + }, + }, + } +} + +func resourceIbmBackupRecoveryManagerUpdateClusterUpgradesCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + managementApiClient, err := meta.(conns.ClientSession).BackupRecoveryManagerV1() + if err != nil { + tfErr := flex.DiscriminatedTerraformErrorf(err, err.Error(), "ibm_backup_recovery_manager_update_cluster_upgrades", "create", "initialize-client") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + bmxsession, err := meta.(conns.ClientSession).BluemixSession() + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("unable to get clientSession"), "ibm_backup_recovery_manager_update_cluster_upgrades", "create") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + endpointType := d.Get("endpoint_type").(string) + instanceId, region := getInstanceIdAndRegion(d) + managementApiClient, err = setManagerClientAuth(managementApiClient, bmxsession, region, endpointType) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("unable to set authenticator for clientSession: %s", err), "ibm_backup_recovery_manager_update_cluster_upgrades", "create") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + if instanceId != "" { + managementApiClient = getManagerClientWithInstanceEndpoint(managementApiClient, bmxsession, instanceId, region, endpointType) + } + + updateClustersUpgradesOptions := &backuprecoveryv1.UpdateClustersUpgradesOptions{} + + if _, ok := d.GetOk("auth_headers"); ok { + var authHeaders []backuprecoveryv1.AuthHeaderForClusterUpgrade + for _, v := range d.Get("auth_headers").([]interface{}) { + value := v.(map[string]interface{}) + authHeadersItem, err := ResourceIbmBackupRecoveryManagerUpdateClusterUpgradesMapToAuthHeaderForClusterUpgrade(value) + if err != nil { + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "ibm_backup_recovery_manager_update_cluster_upgrades", "create", "parse-auth_headers").GetDiag() + } + authHeaders = append(authHeaders, *authHeadersItem) + } + updateClustersUpgradesOptions.SetAuthHeaders(authHeaders) + } + if _, ok := d.GetOk("clusters"); ok { + var clusters []backuprecoveryv1.Upgrade + for _, v := range d.Get("clusters").([]interface{}) { + value := v.(map[string]interface{}) + clustersItem, err := ResourceIbmBackupRecoveryManagerUpdateClusterUpgradesMapToUpgrade(value) + if err != nil { + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "ibm_backup_recovery_manager_update_cluster_upgrades", "create", "parse-clusters").GetDiag() + } + clusters = append(clusters, *clustersItem) + } + updateClustersUpgradesOptions.SetClusters(clusters) + } + if _, ok := d.GetOk("interval_for_rolling_upgrade_in_hours"); ok { + updateClustersUpgradesOptions.SetIntervalForRollingUpgradeInHours(int64(d.Get("interval_for_rolling_upgrade_in_hours").(int))) + } + if _, ok := d.GetOk("package_url"); ok { + updateClustersUpgradesOptions.SetPackageURL(d.Get("package_url").(string)) + } + if _, ok := d.GetOk("patch_upgrade_params"); ok { + patchUpgradeParamsModel, err := ResourceIbmBackupRecoveryManagerUpdateClusterUpgradesMapToPatchUpgradeParams(d.Get("patch_upgrade_params.0").(map[string]interface{})) + if err != nil { + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "ibm_backup_recovery_manager_update_cluster_upgrades", "create", "parse-patch_upgrade_params").GetDiag() + } + updateClustersUpgradesOptions.SetPatchUpgradeParams(patchUpgradeParamsModel) + } + if _, ok := d.GetOk("target_version"); ok { + updateClustersUpgradesOptions.SetTargetVersion(d.Get("target_version").(string)) + } + if _, ok := d.GetOk("time_stamp_to_upgrade_at_msecs"); ok { + updateClustersUpgradesOptions.SetTimeStampToUpgradeAtMsecs(int64(d.Get("time_stamp_to_upgrade_at_msecs").(int))) + } + if _, ok := d.GetOk("type"); ok { + updateClustersUpgradesOptions.SetType(d.Get("type").(string)) + } + + upgradesResponse, _, err := managementApiClient.UpdateClustersUpgradesWithContext(context, updateClustersUpgradesOptions) + if err != nil { + tfErr := flex.TerraformErrorf(err, fmt.Sprintf("UpdateClustersUpgradesWithContext failed: %s", err.Error()), "ibm_backup_recovery_manager_update_cluster_upgrades", "create") + log.Printf("[DEBUG]\n%s", tfErr.GetDebugMessage()) + return tfErr.GetDiag() + } + + d.SetId(resourceIbmBackupRecoveryManagerUpdateClusterUpgradesID(d)) + + if !core.IsNil(upgradesResponse) { + upgradeResponseListResult := []map[string]interface{}{} + for _, upgradeResponseListItem := range upgradesResponse { + upgradeResponseListItemMap, err := ResourceIbmBackupRecoveryManagerUpdateClusterUpgradesUpgradeResponseToMap(&upgradeResponseListItem) // #nosec G601 + if err != nil { + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "ibm_backup_recovery_manager_update_cluster_upgrades", "read", "upgrade_response_list-to-map").GetDiag() + } + upgradeResponseListResult = append(upgradeResponseListResult, upgradeResponseListItemMap) + } + if err = d.Set("upgrade_response_list", upgradeResponseListResult); err != nil { + err = fmt.Errorf("Error setting upgrade_response_list: %s", err) + return flex.DiscriminatedTerraformErrorf(err, err.Error(), "ibm_backup_recovery_manager_update_cluster_upgrades", "read", "set-upgrade_response_list").GetDiag() + } + } + + return resourceIbmBackupRecoveryManagerUpdateClusterUpgradesRead(context, d, meta) +} + +func ResourceIbmBackupRecoveryManagerUpdateClusterUpgradesUpgradeResponseToMap(model *backuprecoveryv1.UpgradeResponse) (map[string]interface{}, error) { + modelMap := make(map[string]interface{}) + if model.ErrorMessage != nil { + modelMap["error_message"] = *model.ErrorMessage + } + if model.IsUpgradeSchedulingSuccessful != nil { + modelMap["is_upgrade_scheduling_successful"] = *model.IsUpgradeSchedulingSuccessful + } + if model.ClusterID != nil { + modelMap["cluster_id"] = flex.IntValue(model.ClusterID) + } + if model.ClusterIncarnationID != nil { + modelMap["cluster_incarnation_id"] = flex.IntValue(model.ClusterIncarnationID) + } + return modelMap, nil +} + +func resourceIbmBackupRecoveryManagerUpdateClusterUpgradesID(d *schema.ResourceData) string { + return time.Now().UTC().String() +} + +func resourceIbmBackupRecoveryManagerUpdateClusterUpgradesRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + return nil +} + +func resourceIbmBackupRecoveryManagerUpdateClusterUpgradesUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + // This resource does not support a "delete" operation. + var diags diag.Diagnostics + warning := diag.Diagnostic{ + Severity: diag.Warning, + Summary: "Update Not Supported", + Detail: "Update operation for this resource is not supported and will only affect the terraform statefile. No changes will be made to the backend resource.", + } + diags = append(diags, warning) + return diags +} + +func resourceIbmBackupRecoveryManagerUpdateClusterUpgradesDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + // This resource does not support a "delete" operation. + var diags diag.Diagnostics + warning := diag.Diagnostic{ + Severity: diag.Warning, + Summary: "Delete Not Supported", + Detail: "The resource definition will be only be removed from the terraform statefile. This resource cannot be deleted from the backend. ", + } + diags = append(diags, warning) + d.SetId("") + return diags +} + +func ResourceIbmBackupRecoveryManagerUpdateClusterUpgradesMapToAuthHeaderForClusterUpgrade(modelMap map[string]interface{}) (*backuprecoveryv1.AuthHeaderForClusterUpgrade, error) { + model := &backuprecoveryv1.AuthHeaderForClusterUpgrade{} + model.Key = core.StringPtr(modelMap["key"].(string)) + model.Value = core.StringPtr(modelMap["value"].(string)) + return model, nil +} + +func ResourceIbmBackupRecoveryManagerUpdateClusterUpgradesMapToUpgrade(modelMap map[string]interface{}) (*backuprecoveryv1.Upgrade, error) { + model := &backuprecoveryv1.Upgrade{} + if modelMap["cluster_id"] != nil { + model.ClusterID = core.Int64Ptr(int64(modelMap["cluster_id"].(int))) + } + if modelMap["cluster_incarnation_id"] != nil { + model.ClusterIncarnationID = core.Int64Ptr(int64(modelMap["cluster_incarnation_id"].(int))) + } + if modelMap["current_version"] != nil && modelMap["current_version"].(string) != "" { + model.CurrentVersion = core.StringPtr(modelMap["current_version"].(string)) + } + return model, nil +} + +func ResourceIbmBackupRecoveryManagerUpdateClusterUpgradesMapToPatchUpgradeParams(modelMap map[string]interface{}) (*backuprecoveryv1.PatchUpgradeParams, error) { + model := &backuprecoveryv1.PatchUpgradeParams{} + if modelMap["auth_headers"] != nil { + authHeaders := []backuprecoveryv1.AuthHeaderForClusterUpgrade{} + for _, authHeadersItem := range modelMap["auth_headers"].([]interface{}) { + authHeadersItemModel, err := ResourceIbmBackupRecoveryManagerUpdateClusterUpgradesMapToAuthHeaderForClusterUpgrade(authHeadersItem.(map[string]interface{})) + if err != nil { + return model, err + } + authHeaders = append(authHeaders, *authHeadersItemModel) + } + model.AuthHeaders = authHeaders + } + if modelMap["ignore_pre_checks_failure"] != nil { + model.IgnorePreChecksFailure = core.BoolPtr(modelMap["ignore_pre_checks_failure"].(bool)) + } + if modelMap["package_url"] != nil && modelMap["package_url"].(string) != "" { + model.PackageURL = core.StringPtr(modelMap["package_url"].(string)) + } + if modelMap["target_version"] != nil && modelMap["target_version"].(string) != "" { + model.TargetVersion = core.StringPtr(modelMap["target_version"].(string)) + } + return model, nil +} diff --git a/ibm/service/backuprecovery/resource_ibm_backup_recovery_manager_update_cluster_upgrades_test.go b/ibm/service/backuprecovery/resource_ibm_backup_recovery_manager_update_cluster_upgrades_test.go new file mode 100644 index 0000000000..18f1240458 --- /dev/null +++ b/ibm/service/backuprecovery/resource_ibm_backup_recovery_manager_update_cluster_upgrades_test.go @@ -0,0 +1,44 @@ +// Copyright IBM Corp. 2025 All Rights Reserved. +// Licensed under the Mozilla Public License v2.0 + +package backuprecovery_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + acc "github.com/IBM-Cloud/terraform-provider-ibm/ibm/acctest" +) + +func TestAccIbmBackupRecoveryManagerUpdateClusterUpgradesBasic(t *testing.T) { + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acc.TestAccPreCheck(t) }, + Providers: acc.TestAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccCheckIbmBackupRecoveryManagerUpdateClusterUpgradesConfigBasic(), + Destroy: false, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("resource.ibm_backup_recovery_manager_update_cluster_upgrades.backup_recovery_manager_update_cluster_upgrades_instance", "id"), + ), + }, + }, + }) +} + +func testAccCheckIbmBackupRecoveryManagerUpdateClusterUpgradesConfigBasic() string { + return fmt.Sprintf(` + resource "ibm_backup_recovery_manager_update_cluster_upgrades" "backup_recovery_manager_update_cluster_upgrades_instance" { + resource "ibm_backup_recovery_manager_create_cluster_upgrades" "backup_recovery_manager_create_cluster_upgrades_instance" { + clusters { + cluster_id = "3524800407225868" + cluster_incarnation_id = "1758305184241232842" + } + package_url = "https://s3.us-east.cloud-object-storage.appdomain.cloud/7.2.16/cluster_artifacts/cohesity-7.2.16.tar.gz" + } + } + `) +} diff --git a/ibm/service/backuprecovery/utils.go b/ibm/service/backuprecovery/utils.go index f0edc9e302..bb99ca61c1 100644 --- a/ibm/service/backuprecovery/utils.go +++ b/ibm/service/backuprecovery/utils.go @@ -1,6 +1,7 @@ package backuprecovery import ( + "encoding/json" "fmt" "os" "strings" @@ -93,3 +94,91 @@ func AddInstanceFields(resource *schema.Resource) *schema.Resource { return resource } + +func BackupRecoverManagerEnvFallBack(endpointsFile, endpointType, region, str string) string { + if v := os.Getenv(str); v != "" { + return v + } + return fileFallBack(endpointsFile, endpointType, region, "IBMCLOUD_BACKUP_RECOVERY_MANAGER_API_KEY") + +} + +func fileFallBack(f, visibility, region, key string) string { + fileMap := map[string]interface{}{} + err := json.Unmarshal([]byte(f), &fileMap) + if err != nil { + return "" + } + if val, ok := fileMap[key]; ok { + if v, ok := val.(map[string]interface{})[visibility]; ok { + if r, ok := v.(map[string]interface{})[region]; ok && r.(string) != "" { + return r.(string) + } + } + } + return "" +} + +// Clone the base backup recovery client and set the API endpoint per the instance +func setManagerClientAuth(originalClient *backuprecoveryv1.BackupRecoveryManagementSreApiV1, bmxsession *session.Session, region, endpointType string) (*backuprecoveryv1.BackupRecoveryManagementSreApiV1, error) { + // build the api endpoint + + endpointsFile := bmxsession.Config.EndpointsFile + + apiKey := BackupRecoverManagerEnvFallBack(endpointsFile, endpointType, region, "IBMCLOUD_BACKUP_RECOVERY_MANAGER_API_KEY") + + if apiKey == "" { + err := fmt.Errorf("IBMCLOUD_BACKUP_RECOVERY_MANAGER_API_KEY not set in env or endpoints file") + return nil, err + } + authconfig := &backuprecoveryv1.ManagementSreAuthenticatorConfig{ + ApiKey: apiKey, + } + authenticator, err := backuprecoveryv1.NewManagementSreAuthenticator(authconfig) + if err != nil { + return nil, err + } + + // clone the client and set endpoint + newClient := &backuprecoveryv1.BackupRecoveryManagementSreApiV1{ + Service: originalClient.Service.Clone(), + } + newClient.Service.Options.Authenticator = authenticator + return newClient, nil +} + +// Clone the base backup recovery client and set the API endpoint per the instance +func getManagerClientWithInstanceEndpoint(originalClient *backuprecoveryv1.BackupRecoveryManagementSreApiV1, bmxsession *session.Session, instanceId, region, endpointType string) *backuprecoveryv1.BackupRecoveryManagementSreApiV1 { + // build the api endpoint + + // default endpoint_type is set to public + if instanceId == "" { + return originalClient + } + + domain := "cloud.ibm.com" + serviceName := "backup-recovery" + endpointsFile := bmxsession.Config.EndpointsFile + + iamUrl := os.Getenv("IBMCLOUD_IAM_API_ENDPOINT") + if iamUrl == "" { + iamUrl = conns.FileFallBack(endpointsFile, endpointType, "IBMCLOUD_IAM_API_ENDPOINT", region, "https://iam.cloud.ibm.com") + } + if strings.Contains(iamUrl, "test") { + domain = "test.cloud.ibm.com" + } + + var endpoint string + if endpointType == "private" { + endpoint = fmt.Sprintf("https://%s.sre.private.%s.%s.%s/v2", instanceId, region, serviceName, domain) + } else { + endpoint = fmt.Sprintf("https://%s.sre.%s.%s.%s/v2", instanceId, region, serviceName, domain) + } + + // clone the client and set endpoint + newClient := &backuprecoveryv1.BackupRecoveryManagementSreApiV1{ + Service: originalClient.Service.Clone(), + } + newClient.Service.SetServiceURL(endpoint) + return newClient +} diff --git a/website/docs/d/backup_recovery_manager_get_alerts.html.markdown b/website/docs/d/backup_recovery_manager_get_alerts.html.markdown new file mode 100644 index 0000000000..b1316d8f92 --- /dev/null +++ b/website/docs/d/backup_recovery_manager_get_alerts.html.markdown @@ -0,0 +1,100 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_backup_recovery_manager_get_alerts" +description: |- + Get information about backup_recovery_manager_get_alerts +subcategory: "IBM REST API" +--- + +# ibm_backup_recovery_manager_get_alerts + +Provides a read-only data source to retrieve information about backup_recovery_manager_get_alerts. 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_backup_recovery_manager_get_alerts" "backup_recovery_manager_get_alerts" { +} +``` + +## Argument Reference + +You can specify the following arguments for this data source. + +* `alert_categories` - (Optional, List) Filter by list of alert categories. + * Constraints: Allowable list items are: `kDisk`, `kNode`, `kCluster`, `kChassis`, `kPowerSupply`, `kCPU`, `kMemory`, `kTemperature`, `kFan`, `kNIC`, `kFirmware`, `kNodeHealth`, `kOperatingSystem`, `kDataPath`, `kMetadata`, `kIndexing`, `kHelios`, `kAppMarketPlace`, `kSystemService`, `kLicense`, `kSecurity`, `kUpgrade`, `kClusterManagement`, `kAuditLog`, `kNetworking`, `kConfiguration`, `kStorageUsage`, `kFaultTolerance`, `kBackupRestore`, `kArchivalRestore`, `kRemoteReplication`, `kQuota`, `kCDP`, `kViewFailover`, `kDisasterRecovery`, `kStorageDevice`, `kStoragePool`, `kGeneralSoftwareFailure`, `kAgent`. +* `alert_ids` - (Optional, List) Filter by list of alert ids. +* `alert_name` - (Optional, String) Specifies name of alert to filter alerts by. +* `alert_severities` - (Optional, List) Filter by list of alert severity types. + * Constraints: Allowable list items are: `kCritical`, `kWarning`, `kInfo`. +* `alert_states` - (Optional, List) Filter by list of alert states. + * Constraints: Allowable list items are: `kResolved`, `kOpen`, `kNote`, `kSuppressed`. +* `alert_type_buckets` - (Optional, List) Filter by list of alert type buckets. + * Constraints: Allowable list items are: `kHardware`, `kSoftware`, `kDataService`, `kMaintenance`. +* `alert_types` - (Optional, List) Filter by list of alert types. +* `all_under_hierarchy` - (Optional, Boolean) Filter by objects of all the tenants under the hierarchy of the logged in user's organization. +* `end_time_usecs` - (Optional, Integer) Specifies end time Unix epoch time in microseconds to filter alerts by. +* `max_alerts` - (Optional, Integer) Specifies maximum number of alerts to return.The default value is 100 and maximum allowed value is 1000. +* `property_key` - (Optional, String) Specifies name of the property to filter alerts by. +* `property_value` - (Optional, String) Specifies value of the property to filter alerts by. +* `resolution_ids` - (Optional, List) Specifies alert resolution ids to filter alerts by. +* `start_time_usecs` - (Optional, Integer) Specifies start time Unix epoch time in microseconds to filter alerts by. +* `tenant_ids` - (Optional, List) Filter by tenant ids. +* `x_scope_identifier` - (Optional, String) This field uniquely represents a service instance. Please specify the values as "service-instance-id: ". + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the backup_recovery_manager_get_alerts. +* `alerts` - (List) Specifies the list of alerts. +Nested schema for **alerts**: + * `alert_category` - (String) Specifies the alert category. + * Constraints: Allowable values are: `kDisk`, `kNode`, `kCluster`, `kChassis`, `kPowerSupply`, `kCPU`, `kMemory`, `kTemperature`, `kFan`, `kNIC`, `kFirmware`, `kNodeHealth`, `kOperatingSystem`, `kDataPath`, `kMetadata`, `kIndexing`, `kHelios`, `kAppMarketPlace`, `kSystemService`, `kLicense`, `kSecurity`, `kUpgrade`, `kClusterManagement`, `kAuditLog`, `kNetworking`, `kConfiguration`, `kStorageUsage`, `kFaultTolerance`, `kBackupRestore`, `kArchivalRestore`, `kRemoteReplication`, `kQuota`, `kCDP`, `kViewFailover`, `kDisasterRecovery`, `kStorageDevice`, `kStoragePool`, `kGeneralSoftwareFailure`, `kAgent`. + * `alert_code` - (String) Specifies a unique code that categorizes the Alert, for example: CE00200014, where CE stands for IBM Error, the alert state next 3 digits is the id of the Alert Category (e.g. 002 for 'kNode') and the last 5 digits is the id of the Alert Type (e.g. 00014 for 'kNodeHighCpuUsage'). + * `alert_document` - (List) Specifies the fields of alert document. + Nested schema for **alert_document**: + * `alert_cause` - (String) Specifies the cause of alert. + * `alert_description` - (String) Specifies the description of alert. + * `alert_help_text` - (String) Specifies the help text for alert. + * `alert_name` - (String) Specifies the name of alert. + * `alert_summary` - (String) Short description for the alert. + * `alert_state` - (String) Specifies the alert state. + * Constraints: Allowable values are: `kResolved`, `kOpen`, `kNote`, `kSuppressed`. + * `alert_type` - (Integer) Specifies the alert type. + * `alert_type_bucket` - (String) Specifies the Alert type bucket. + * Constraints: Allowable values are: `kHardware`, `kSoftware`, `kDataService`, `kMaintenance`. + * `cluster_id` - (Integer) Id of the cluster which the alert is associated. + * `cluster_name` - (String) Specifies the name of cluster which alert is raised from. + * `dedup_count` - (Integer) Specifies the dedup count of alert. + * `dedup_timestamps` - (List) Specifies Unix epoch Timestamps (in microseconds) for the last 25 occurrences of duplicated Alerts that are stored with the original/primary Alert. Alerts are grouped into one Alert if the Alerts are the same type, are reporting on the same Object and occur within one hour. 'dedupCount' always reports the total count of duplicated Alerts even if there are more than 25 occurrences. For example, if there are 100 occurrences of this Alert, dedupTimestamps stores the timestamps of the last 25 occurrences and dedupCount equals 100. + * `event_source` - (String) Specifies source where the event occurred. + * `first_timestamp_usecs` - (Integer) Specifies Unix epoch Timestamp (in microseconds) of the first occurrence of the Alert. + * `id` - (String) Specifies unique id of the alert. + * `label_ids` - (List) Specifies the labels for which this alert has been raised. + * `latest_timestamp_usecs` - (Integer) Specifies Unix epoch Timestamp (in microseconds) of the most recent occurrence of the Alert. + * `property_list` - (List) List of property key and values associated with alert. + Nested schema for **property_list**: + * `key` - (String) Key of the Label. + * `value` - (String) Value of the Label, multiple values should be joined by '|'. + * `region_id` - (String) Specifies the region id of the alert. + * `resolution_details` - (List) Specifies information about the Alert Resolution. + Nested schema for **resolution_details**: + * `resolution_details` - (String) Specifies detailed notes about the Resolution. + * `resolution_id` - (Integer) Specifies the unique resolution id assigned in management console. + * `resolution_summary` - (String) Specifies short description about the Resolution. + * `timestamp_usecs` - (Integer) Specifies unix epoch timestamp (in microseconds) when the Alert was resolved. + * `user_name` - (String) Specifies name of the IBM Cluster user who resolved the Alerts. + * `resolution_id_string` - (String) Resolution Id String. + * `resolved_timestamp_usecs` - (Integer) Specifies Unix epoch Timestamps in microseconds when alert is resolved. + * `severity` - (String) Specifies the alert severity. + * Constraints: Allowable values are: `kCritical`, `kWarning`, `kInfo`. + * `suppression_id` - (Integer) Specifies unique id generated when the Alert is suppressed by the admin. + * `tenant_ids` - (List) Specifies the tenants for which this alert has been raised. + * `vaults` - (List) Specifies information about vaults where source object associated with alert is vaulted. This could be empty if alert is not related to any source object or it is not vaulted. + Nested schema for **vaults**: + * `global_vault_id` - (String) Specifies Global vault id. + * `region_id` - (String) Specifies id of region where vault resides. + * `region_name` - (String) Specifies name of region where vault resides. + * `vault_name` - (String) Specifies name of vault. + diff --git a/website/docs/d/backup_recovery_manager_get_alerts_resolution.html.markdown b/website/docs/d/backup_recovery_manager_get_alerts_resolution.html.markdown new file mode 100644 index 0000000000..609f23067d --- /dev/null +++ b/website/docs/d/backup_recovery_manager_get_alerts_resolution.html.markdown @@ -0,0 +1,53 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_backup_recovery_manager_get_alerts_resolution" +description: |- + Get information about backup_recovery_manager_get_alerts_resolution +subcategory: "IBM REST API" +--- + +# ibm_backup_recovery_manager_get_alerts_resolution + +Provides a read-only data source to retrieve information about a backup_recovery_manager_get_alerts_resolution. 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_backup_recovery_manager_get_alerts_resolution" "backup_recovery_manager_get_alerts_resolution" { + max_resolutions = 14 +} +``` + +## Argument Reference + +You can specify the following arguments for this data source. + +* `max_resolutions` - (Required, Integer) Specifies the max number of Resolutions to be returned, from the latest created to the earliest created. +* `resolution_id` - (Optional, String) Specifies Alert Resolution id to query. +* `resolution_name` - (Optional, String) Specifies Alert Resolution Name to query. + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the backup_recovery_manager_get_alerts_resolution. +* `alert_resolutions_list` - (List) List of alert resolutions. +Nested schema for **alert_resolutions_list**: + * `account_id` - (String) Specifies account id of the user who create the resolution. + * `created_time_usecs` - (Integer) Specifies unix epoch timestamp (in microseconds) when the resolution is created. + * `description` - (String) Specifies the full description about the Resolution. + * `external_key` - (String) Specifies the external key assigned outside of management console, with the form of "clusterid:resolutionid". + * `resolution_id` - (String) Specifies the unique reslution id assigned in management console. + * `resolution_name` - (String) Specifies the unique name of the resolution. + * `resolved_alerts` - (List) + Nested schema for **resolved_alerts**: + * `alert_id` - (Integer) Id of the alert. + * `alert_id_str` - (String) Alert Id with string format. + * `alert_name` - (String) Name of the alert being resolved. + * `cluster_id` - (Integer) Id of the cluster which the alert is associated. + * `first_timestamp_usecs` - (Integer) First occurrence of the alert. + * `resolved_time_usec` - (Integer) + * `service_instance_id` - (String) Id of the service instance which the alert is associated. + * `silence_minutes` - (Integer) Specifies the time duration (in minutes) for silencing alerts. If unspecified or set zero, a silence rule will be created with default expiry time. No silence rule will be created if value < 0. + * `tenant_id` - (String) Specifies tenant id of the user who create the resolution. + diff --git a/website/docs/d/backup_recovery_manager_get_alerts_stats.html.markdown b/website/docs/d/backup_recovery_manager_get_alerts_stats.html.markdown new file mode 100644 index 0000000000..77d818d175 --- /dev/null +++ b/website/docs/d/backup_recovery_manager_get_alerts_stats.html.markdown @@ -0,0 +1,98 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_backup_recovery_manager_get_alerts_stats" +description: |- + Get information about Active Alerts stats response. +subcategory: "IBM REST API" +--- + +# ibm_backup_recovery_manager_get_alerts_stats + +Provides a read-only data source to retrieve information about an Active Alerts stats response.. 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_backup_recovery_manager_get_alerts_stats" "backup_recovery_manager_get_alerts_stats" { + end_time_usecs = 12 + start_time_usecs = 14 +} +``` + +## Argument Reference + +You can specify the following arguments for this data source. + +* `alert_source` - (Optional, String) Specifies a list of alert origination source. If not specified, all alerts from all the sources are considered in the response. + * Constraints: Allowable values are: `kCluster`, `kHelios`. +* `cluster_ids` - (Optional, List) Specifies the list of cluster IDs. +* `end_time_usecs` - (Required, Integer) Specifies the end time Unix time epoch in microseconds to which the active alerts stats are computed. +* `exclude_stats_by_cluster` - (Optional, Boolean) Specifies if stats of active alerts per cluster needs to be excluded. If set to false (default value), stats of active alerts per cluster is included in the response. If set to true, only aggregated stats summary will be present in the response. +* `region_ids` - (Optional, List) Filter by a list of region ids. +* `service_instance_ids` - (Optional, List) Specifies list of service instance ids to filter alert stats by. +* `start_time_usecs` - (Required, Integer) Specifies the start time Unix time epoch in microseconds from which the active alerts stats are computed. +* `tenant_ids` - (Optional, List) Specifies a list of tenants. + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the Active Alerts stats response.. +* `aggregated_alerts_stats` - (List) Specifies the active alert statistics details. +Nested schema for **aggregated_alerts_stats**: + * `num_critical_alerts` - (Integer) Specifies the count of active critical Alerts excluding alerts that belong to other bucket. + * `num_critical_alerts_categories` - (Integer) Specifies the count of active critical alerts categories. + * `num_data_service_alerts` - (Integer) Specifies the count of active service Alerts. + * `num_data_service_critical_alerts` - (Integer) Specifies the count of active service critical Alerts. + * `num_data_service_info_alerts` - (Integer) Specifies the count of active service info Alerts. + * `num_data_service_warning_alerts` - (Integer) Specifies the count of active service warning Alerts. + * `num_hardware_alerts` - (Integer) Specifies the count of active hardware Alerts. + * `num_hardware_critical_alerts` - (Integer) Specifies the count of active hardware critical Alerts. + * `num_hardware_info_alerts` - (Integer) Specifies the count of active hardware info Alerts. + * `num_hardware_warning_alerts` - (Integer) Specifies the count of active hardware warning Alerts. + * `num_info_alerts` - (Integer) Specifies the count of active info Alerts excluding alerts that belong to other bucket. + * `num_info_alerts_categories` - (Integer) Specifies the count of active info alerts categories. + * `num_maintenance_alerts` - (Integer) Specifies the count of active Alerts of maintenance bucket. + * `num_maintenance_critical_alerts` - (Integer) Specifies the count of active other critical Alerts. + * `num_maintenance_info_alerts` - (Integer) Specifies the count of active other info Alerts. + * `num_maintenance_warning_alerts` - (Integer) Specifies the count of active other warning Alerts. + * `num_software_alerts` - (Integer) Specifies the count of active software Alerts. + * `num_software_critical_alerts` - (Integer) Specifies the count of active software critical Alerts. + * `num_software_info_alerts` - (Integer) Specifies the count of active software info Alerts. + * `num_software_warning_alerts` - (Integer) Specifies the count of active software warning Alerts. + * `num_warning_alerts` - (Integer) Specifies the count of active warning Alerts excluding alerts that belong to other bucket. + * `num_warning_alerts_categories` - (Integer) Specifies the count of active warning alerts categories. +* `aggregated_cluster_stats` - (List) Specifies the cluster statistics based on active alerts. +Nested schema for **aggregated_cluster_stats**: + * `num_clusters_with_critical_alerts` - (Integer) Specifies the count of clusters with at least one critical alert. + * `num_clusters_with_warning_alerts` - (Integer) Specifies the count of clusters with at least one warning category alert and no critical alerts. + * `num_healthy_clusters` - (Integer) Specifies the count of clusters with no warning or critical alerts. +* `stats_by_cluster` - (List) Specifies the active Alerts stats by clusters. +Nested schema for **stats_by_cluster**: + * `alerts_stats` - (List) Specifies the active alert statistics details. + Nested schema for **alerts_stats**: + * `num_critical_alerts` - (Integer) Specifies the count of active critical Alerts excluding alerts that belong to other bucket. + * `num_critical_alerts_categories` - (Integer) Specifies the count of active critical alerts categories. + * `num_data_service_alerts` - (Integer) Specifies the count of active service Alerts. + * `num_data_service_critical_alerts` - (Integer) Specifies the count of active service critical Alerts. + * `num_data_service_info_alerts` - (Integer) Specifies the count of active service info Alerts. + * `num_data_service_warning_alerts` - (Integer) Specifies the count of active service warning Alerts. + * `num_hardware_alerts` - (Integer) Specifies the count of active hardware Alerts. + * `num_hardware_critical_alerts` - (Integer) Specifies the count of active hardware critical Alerts. + * `num_hardware_info_alerts` - (Integer) Specifies the count of active hardware info Alerts. + * `num_hardware_warning_alerts` - (Integer) Specifies the count of active hardware warning Alerts. + * `num_info_alerts` - (Integer) Specifies the count of active info Alerts excluding alerts that belong to other bucket. + * `num_info_alerts_categories` - (Integer) Specifies the count of active info alerts categories. + * `num_maintenance_alerts` - (Integer) Specifies the count of active Alerts of maintenance bucket. + * `num_maintenance_critical_alerts` - (Integer) Specifies the count of active other critical Alerts. + * `num_maintenance_info_alerts` - (Integer) Specifies the count of active other info Alerts. + * `num_maintenance_warning_alerts` - (Integer) Specifies the count of active other warning Alerts. + * `num_software_alerts` - (Integer) Specifies the count of active software Alerts. + * `num_software_critical_alerts` - (Integer) Specifies the count of active software critical Alerts. + * `num_software_info_alerts` - (Integer) Specifies the count of active software info Alerts. + * `num_software_warning_alerts` - (Integer) Specifies the count of active software warning Alerts. + * `num_warning_alerts` - (Integer) Specifies the count of active warning Alerts excluding alerts that belong to other bucket. + * `num_warning_alerts_categories` - (Integer) Specifies the count of active warning alerts categories. + * `cluster_id` - (Integer) Specifies the Cluster Id. + * `region_id` - (String) Specifies the region id of cluster. + diff --git a/website/docs/d/backup_recovery_manager_get_alerts_summary.html.markdown b/website/docs/d/backup_recovery_manager_get_alerts_summary.html.markdown new file mode 100644 index 0000000000..a1bf4fc7bd --- /dev/null +++ b/website/docs/d/backup_recovery_manager_get_alerts_summary.html.markdown @@ -0,0 +1,46 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_backup_recovery_manager_get_alerts_summary" +description: |- + Get information about backup_recovery_manager_get_alerts_summary +subcategory: "IBM REST API" +--- + +# ibm_backup_recovery_manager_get_alerts_summary + +Provides a read-only data source to retrieve information about a backup_recovery_manager_get_alerts_summary. 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_backup_recovery_manager_get_alerts_summary" "backup_recovery_manager_get_alerts_summary" { +} +``` + +## Argument Reference + +You can specify the following arguments for this data source. + +* `end_time_usecs` - (Optional, Integer) Filter by end time. Specify the end time as a Unix epoch Timestamp (in microseconds). By default it is current time. +* `include_tenants` - (Optional, Boolean) IncludeTenants specifies if alerts of all the tenants under the hierarchy of the logged in user's organization should be used to compute summary. +* `start_time_usecs` - (Optional, Integer) Filter by start time. Specify the start time as a Unix epoch Timestamp (in microseconds). By default it is current time minus a day. +* `states_list` - (Optional, List) Specifies list of alert states to filter alerts by. If not specified, only open alerts will be used to get summary. + * Constraints: Allowable list items are: `kResolved`, `kOpen`, `kNote`, `kSuppressed`. +* `tenant_ids` - (Optional, List) TenantIds contains ids of the tenants for which alerts are to be used to compute summary. +* `x_scope_identifier` - (Optional, String) This field uniquely represents a service instance. Please specify the values as "service-instance-id: ". + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the backup_recovery_manager_get_alerts_summary. +* `alerts_summary` - (List) Specifies a list of alerts summary grouped by category. +Nested schema for **alerts_summary**: + * `category` - (String) Category of alerts by which summary is grouped. + * Constraints: Allowable values are: `kDisk`, `kNode`, `kCluster`, `kChassis`, `kPowerSupply`, `kCPU`, `kMemory`, `kTemperature`, `kFan`, `kNIC`, `kFirmware`, `kNodeHealth`, `kOperatingSystem`, `kDataPath`, `kMetadata`, `kIndexing`, `kHelios`, `kAppMarketPlace`, `kSystemService`, `kLicense`, `kSecurity`, `kUpgrade`, `kClusterManagement`, `kAuditLog`, `kNetworking`, `kConfiguration`, `kStorageUsage`, `kFaultTolerance`, `kBackupRestore`, `kArchivalRestore`, `kRemoteReplication`, `kQuota`, `kCDP`, `kViewFailover`, `kDisasterRecovery`, `kStorageDevice`, `kStoragePool`, `kGeneralSoftwareFailure`, `kAgent`. + * `critical_count` - (Integer) Specifies count of critical alerts. + * `info_count` - (Integer) Specifies count of info alerts. + * `total_count` - (Integer) Specifies count of total alerts. + * `type` - (String) Type/bucket that this alert category belongs to. + * `warning_count` - (Integer) Specifies count of warning alerts. + diff --git a/website/docs/d/backup_recovery_manager_get_cluster_info.html.markdown b/website/docs/d/backup_recovery_manager_get_cluster_info.html.markdown new file mode 100644 index 0000000000..53ae1d9eec --- /dev/null +++ b/website/docs/d/backup_recovery_manager_get_cluster_info.html.markdown @@ -0,0 +1,85 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_backup_recovery_manager_get_cluster_info" +description: |- + Get information about backup_recovery_manager_get_cluster_info +subcategory: "IBM REST API" +--- + +# ibm_backup_recovery_manager_get_cluster_info + +Provides a read-only data source to retrieve information about a backup_recovery_manager_get_cluster_info. 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_backup_recovery_manager_get_cluster_info" "backup_recovery_manager_get_cluster_info" { +} +``` + + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the backup_recovery_manager_get_cluster_info. +* `cohesity_clusters` - (List) Specifies the array of clusters upgrade details. +Nested schema for **cohesity_clusters**: + * `auth_support_for_pkg_downloads` - (Boolean) If cluster can support authHeader for upgrade or not. + * `available_versions` - (List) Specifies the release versions the cluster can upgrade to. + Nested schema for **available_versions**: + * `notes` - (String) Specifies release's notes. + * `patch_details` - (List) Specifies the details of the available patch release. + Nested schema for **patch_details**: + * `notes` - (String) Specifies patch release's notes. + * `release_type` - (String) Release's type. + * `version` - (String) Specifies patch release's version. + * `release_stage` - (String) Specifies the stage of a release. + * `release_type` - (String) Release's type e.g, LTS, Feature, Patch, MCM. + * `type` - (String) Specifies the type of package or release. + * Constraints: Allowable values are: `Upgrade`, `Patch`, `UpgradePatch`. + * `version` - (String) Specifies release's version. + * `cluster_id` - (Integer) Specifies cluster id. + * `cluster_incarnation_id` - (Integer) Specifies cluster incarnation id. + * `cluster_name` - (String) Specifies cluster's name. + * `current_patch_version` - (String) Specifies current patch version of the cluster. + * `current_version` - (String) Specifies if the cluster is connected to management console. + * `health` - (String) Specifies the health of the cluster. + * Constraints: Allowable values are: `Critical`, `NonCritical`. + * `is_connected_to_helios` - (Boolean) Specifies if the cluster is connected to management console. + * `location` - (String) Specifies the location of the cluster. + * `multi_tenancy_enabled` - (Boolean) Specifies if multi tenancy is enabled in the cluster. + * `node_ips` - (List) Specifies an array of node ips for the cluster. + * `number_of_nodes` - (Integer) Specifies the number of nodes in the cluster. + * `patch_target_upgrade_url` - (String) Specifies the patch package URL for the cluster. This is populated for patch update only. + * `patch_target_version` - (String) Specifies target version to which clusters are upgrading. This is populated for patch update only. + * `provider_type` - (String) Specifies the type of the cluster provider. + * Constraints: Allowable values are: `kMCMCohesity`, `kIBMStorageProtect`. + * `scheduled_timestamp` - (Integer) Time at which an upgrade is scheduled. + * `status` - (String) Specifies the upgrade status of the cluster. + * Constraints: Allowable values are: `InProgress`, `UpgradeAvailable`, `UpToDate`, `Scheduled`, `Failed`, `ClusterUnreachable`. + * `target_upgrade_url` - (String) Specifies the upgrade URL for the cluster. This is populated for upgrade only. + * `target_version` - (String) Specifies target version to which clusters are to be upgraded. This is populated for upgrade only. + * `total_capacity` - (Integer) Specifies how total memory capacity of the cluster. + * `type` - (String) Specifies the type of the cluster. + * Constraints: Allowable values are: `VMRobo`, `Physical`. + * `update_type` - (String) Specifies the type of upgrade performed on a cluster. This is to be used with status field to know the status of the upgrade action performed on cluster. + * Constraints: Allowable values are: `Upgrade`, `Patch`, `UpgradePatch`. + * `used_capacity` - (Integer) Specifies how much of the cluster capacity is consumed. +* `sp_clusters` - (List) Specifies the array of clusters claimed from IBM Storage Protect environment. +Nested schema for **sp_clusters**: + * `cluster_id` - (Integer) Specifies cluster id. + * `cluster_incarnation_id` - (Integer) Specifies cluster incarnation id. + * `cluster_name` - (String) Specifies cluster's name. + * `current_version` - (String) Specifies the currently running version on cluster. + * `health` - (String) Specifies the health of the cluster. + * Constraints: Allowable values are: `Critical`, `NonCritical`. + * `is_connected_to_helios` - (Boolean) Specifies if the cluster is connected to management console. + * `node_ips` - (List) Specifies an array of node ips for the cluster. + * `number_of_nodes` - (Integer) Specifies the number of nodes in the cluster. + * `provider_type` - (String) Specifies the type of the cluster provider. + * Constraints: Allowable values are: `kMCMCohesity`, `kIBMStorageProtect`. + * `total_capacity` - (Integer) Specifies total capacity of the cluster in bytes. + * `type` - (String) Specifies the type of the SP cluster. + * `used_capacity` - (Integer) Specifies how much of the cluster capacity is consumed in bytes. + diff --git a/website/docs/d/backup_recovery_manager_get_compatible_clusters.html.markdown b/website/docs/d/backup_recovery_manager_get_compatible_clusters.html.markdown new file mode 100644 index 0000000000..0c8048c775 --- /dev/null +++ b/website/docs/d/backup_recovery_manager_get_compatible_clusters.html.markdown @@ -0,0 +1,37 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_backup_recovery_manager_get_compatible_clusters" +description: |- + Get information about backup_recovery_manager_get_compatible_clusters +subcategory: "IBM REST API" +--- + +# ibm_backup_recovery_manager_get_compatible_clusters + +Provides a read-only data source to retrieve information about backup_recovery_manager_get_compatible_clusters. 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_backup_recovery_manager_get_compatible_clusters" "backup_recovery_manager_get_compatible_clusters" { +} +``` + +## Argument Reference + +You can specify the following arguments for this data source. + +* `release_version` - (Optional, String) + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the backup_recovery_manager_get_compatible_clusters. +* `compatible_clusters` - (List) +Nested schema for **compatible_clusters**: + * `cluster_id` - (Integer) Specifies cluster id. + * `cluster_incarnation_id` - (Integer) Specifies cluster incarnation id. + * `cluster_name` - (String) Specifies cluster's name. + * `current_version` - (String) Specifies the current version of the cluster. + diff --git a/website/docs/d/backup_recovery_manager_get_management_alerts.html.markdown b/website/docs/d/backup_recovery_manager_get_management_alerts.html.markdown new file mode 100644 index 0000000000..a536446563 --- /dev/null +++ b/website/docs/d/backup_recovery_manager_get_management_alerts.html.markdown @@ -0,0 +1,88 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_backup_recovery_manager_get_management_alerts" +description: |- + Get information about backup_recovery_manager_get_management_alerts +subcategory: "IBM REST API" +--- + +# ibm_backup_recovery_manager_get_management_alerts + +Provides a read-only data source to retrieve information about backup_recovery_manager_get_management_alerts. 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_backup_recovery_manager_get_management_alerts" "backup_recovery_manager_get_management_alerts" { +} +``` + +## Argument Reference + +You can specify the following arguments for this data source. + +* `alert_category_list` - (Optional, List) Filter by list of alert categories. + * Constraints: Allowable list items are: `kDisk`, `kNode`, `kCluster`, `kChassis`, `kPowerSupply`, `kCPU`, `kMemory`, `kTemperature`, `kFan`, `kNIC`, `kFirmware`, `kNodeHealth`, `kOperatingSystem`, `kDataPath`, `kMetadata`, `kIndexing`, `kHelios`, `kAppMarketPlace`, `kSystemService`, `kLicense`, `kSecurity`, `kUpgrade`, `kClusterManagement`, `kAuditLog`, `kNetworking`, `kConfiguration`, `kStorageUsage`, `kFaultTolerance`, `kBackupRestore`, `kArchivalRestore`, `kRemoteReplication`, `kQuota`, `kCDP`, `kViewFailover`, `kDisasterRecovery`, `kStorageDevice`, `kStoragePool`, `kGeneralSoftwareFailure`, `kAgent`. +* `alert_id_list` - (Optional, List) Filter by list of alert ids. +* `alert_name` - (Optional, String) Specifies name of alert to filter alerts by. +* `alert_property_key_list` - (Optional, List) Specifies list of the alert property keys to query. +* `alert_property_value_list` - (Optional, List) Specifies list of the alert property value, multiple values for one key should be joined by '|'. +* `alert_severity_list` - (Optional, List) Filter by list of alert severity types. + * Constraints: Allowable list items are: `kCritical`, `kWarning`, `kInfo`. +* `alert_state_list` - (Optional, List) Filter by list of alert states. +* `alert_type_bucket_list` - (Optional, List) Filter by list of alert type buckets. + * Constraints: Allowable list items are: `kHardware`, `kSoftware`, `kDataService`, `kMaintenance`. +* `alert_type_list` - (Optional, List) Filter by list of alert types. +* `cluster_identifiers` - (Optional, List) Filter by list of cluster ids. +* `end_date_usecs` - (Optional, Integer) Specifies the end time of the alerts to be returned. All the alerts returned are raised before the specified end time. This value should be in Unix timestamp epoch in microseconds. +* `max_alerts` - (Optional, Integer) Specifies maximum number of alerts to return. +* `region_ids` - (Optional, List) Filter by list of region ids. +* `service_instance_ids` - (Optional, List) Specifies services instance ids to filter alerts for IBM customers. +* `start_date_usecs` - (Optional, Integer) Specifies the start time of the alerts to be returned. All the alerts returned are raised after the specified start time. This value should be in Unix timestamp epoch in microseconds. +* `tenant_ids` - (Optional, List) Filter by tenant ids. + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the backup_recovery_manager_get_management_alerts. +* `alerts_list` - (List) Specifies the list of alerts. +Nested schema for **alerts_list**: + * `alert_category` - (String) Specifies the alert category. + * Constraints: Allowable values are: `kDisk`, `kNode`, `kCluster`, `kChassis`, `kPowerSupply`, `kCPU`, `kMemory`, `kTemperature`, `kFan`, `kNIC`, `kFirmware`, `kNodeHealth`, `kOperatingSystem`, `kDataPath`, `kMetadata`, `kIndexing`, `kHelios`, `kAppMarketPlace`, `kSystemService`, `kLicense`, `kSecurity`, `kUpgrade`, `kClusterManagement`, `kAuditLog`, `kNetworking`, `kConfiguration`, `kStorageUsage`, `kFaultTolerance`, `kBackupRestore`, `kArchivalRestore`, `kRemoteReplication`, `kQuota`, `kCDP`, `kViewFailover`, `kDisasterRecovery`, `kStorageDevice`, `kStoragePool`, `kGeneralSoftwareFailure`, `kAgent`. + * `alert_code` - (String) Specifies a unique code that categorizes the Alert, for example: CE00200014, where CE stands for IBM Error, the alert state next 3 digits is the id of the Alert Category (e.g. 002 for 'kNode') and the last 5 digits is the id of the Alert Type (e.g. 00014 for 'kNodeHighCpuUsage'). + * `alert_document` - (List) Specifies the fields of alert document. + Nested schema for **alert_document**: + * `alert_cause` - (String) Specifies the cause of alert. + * `alert_description` - (String) Specifies the description of alert. + * `alert_help_text` - (String) Specifies the help text for alert. + * `alert_name` - (String) Specifies the name of alert. + * `alert_summary` - (String) Short description for the alert. + * `alert_state` - (String) Specifies the alert state. + * Constraints: Allowable values are: `kResolved`, `kOpen`, `kNote`, `kSuppressed`. + * `alert_type` - (Integer) Specifies the alert type. + * `alert_type_bucket` - (String) Specifies the Alert type bucket. + * Constraints: Allowable values are: `kHardware`, `kSoftware`, `kDataService`, `kMaintenance`. + * `cluster_id` - (Integer) Id of the cluster which the alert is associated. + * `cluster_name` - (String) Specifies the name of cluster which alert is raised from. + * `dedup_count` - (Integer) Specifies the dedup count of alert. + * `dedup_timestamps` - (List) Specifies Unix epoch Timestamps (in microseconds) for the last 25 occurrences of duplicated Alerts that are stored with the original/primary Alert. Alerts are grouped into one Alert if the Alerts are the same type, are reporting on the same Object and occur within one hour. 'dedupCount' always reports the total count of duplicated Alerts even if there are more than 25 occurrences. For example, if there are 100 occurrences of this Alert, dedupTimestamps stores the timestamps of the last 25 occurrences and dedupCount equals 100. + * `first_timestamp_usecs` - (Integer) SpeSpecifies Unix epoch Timestamp (in microseconds) of the first occurrence of the Alert. + * `id` - (String) Specifies unique id of the alert. + * `latest_timestamp_usecs` - (Integer) SpeSpecifies Unix epoch Timestamp (in microseconds) of the most recent occurrence of the Alert. + * `property_list` - (List) List of property key and values associated with alert. + Nested schema for **property_list**: + * `key` - (String) Key of the Label. + * `value` - (String) Value of the Label, multiple values should be joined by '|'. + * `region_id` - (String) Specifies the region id of the alert. + * `resolution_id_string` - (String) Specifies the resolution id of the alert if its resolved. + * `service_instance_id` - (String) Id of the serrvice instance which the alert is associated. + * `severity` - (String) Specifies the alert severity. + * Constraints: Allowable values are: `kCritical`, `kWarning`, `kInfo`. + * `vaults` - (List) Specifies information about vaults where source object associated with alert is vaulted. This could be empty if alert is not related to any source object or it is not vaulted. + Nested schema for **vaults**: + * `global_vault_id` - (String) Specifies Global vault id. + * `region_id` - (String) Specifies id of region where vault resides. + * `region_name` - (String) Specifies name of region where vault resides. + * `vault_name` - (String) Specifies name of vault. + diff --git a/website/docs/d/backup_recovery_manager_get_management_alerts_summary.html.markdown b/website/docs/d/backup_recovery_manager_get_management_alerts_summary.html.markdown new file mode 100644 index 0000000000..605ce42b21 --- /dev/null +++ b/website/docs/d/backup_recovery_manager_get_management_alerts_summary.html.markdown @@ -0,0 +1,44 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_backup_recovery_manager_get_management_alerts_summary" +description: |- + Get information about backup_recovery_manager_get_management_alerts_summary +subcategory: "IBM REST API" +--- + +# ibm_backup_recovery_manager_get_management_alerts_summary + +Provides a read-only data source to retrieve information about a backup_recovery_manager_get_management_alerts_summary. 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_backup_recovery_manager_get_management_alerts_summary" "backup_recovery_manager_get_management_alerts_summary" { +} +``` + +## Argument Reference + +You can specify the following arguments for this data source. + +* `cluster_identifiers` - (Optional, List) Specifies the list of cluster identifiers. Format is clusterId:clusterIncarnationId. +* `end_time_usecs` - (Optional, Integer) Filter by end time. Specify the end time as a Unix epoch Timestamp (in microseconds). By default it is current time. +* `start_time_usecs` - (Optional, Integer) Filter by start time. Specify the start time as a Unix epoch Timestamp (in microseconds). By default it is current time minus a day. +* `states_list` - (Optional, List) Specifies list of alert states to filter alerts by. If not specified, only open alerts will be used to get summary. + * Constraints: Allowable list items are: `kResolved`, `kOpen`, `kNote`, `kSuppressed`. + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the backup_recovery_manager_get_management_alerts_summary. +* `alerts_summary` - (List) Specifies a list of alerts summary grouped by category. +Nested schema for **alerts_summary**: + * `category` - (String) Category of alerts by which summary is grouped. + * Constraints: Allowable values are: `kDisk`, `kNode`, `kCluster`, `kChassis`, `kPowerSupply`, `kCPU`, `kMemory`, `kTemperature`, `kFan`, `kNIC`, `kFirmware`, `kNodeHealth`, `kOperatingSystem`, `kDataPath`, `kMetadata`, `kIndexing`, `kHelios`, `kAppMarketPlace`, `kSystemService`, `kLicense`, `kSecurity`, `kUpgrade`, `kClusterManagement`, `kAuditLog`, `kNetworking`, `kConfiguration`, `kStorageUsage`, `kFaultTolerance`, `kBackupRestore`, `kArchivalRestore`, `kRemoteReplication`, `kQuota`, `kCDP`, `kViewFailover`, `kDisasterRecovery`, `kStorageDevice`, `kStoragePool`, `kGeneralSoftwareFailure`, `kAgent`. + * `critical_count` - (Integer) Specifies count of critical alerts. + * `info_count` - (Integer) Specifies count of info alerts. + * `total_count` - (Integer) Specifies count of total alerts. + * `type` - (String) Type/bucket that this alert category belongs to. + * `warning_count` - (Integer) Specifies count of warning alerts. + diff --git a/website/docs/d/backup_recovery_manager_get_upgrades_info.html.markdown b/website/docs/d/backup_recovery_manager_get_upgrades_info.html.markdown new file mode 100644 index 0000000000..00c62e1cd0 --- /dev/null +++ b/website/docs/d/backup_recovery_manager_get_upgrades_info.html.markdown @@ -0,0 +1,49 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_backup_recovery_manager_get_upgrades_info" +description: |- + Get information about backup_recovery_manager_get_upgrades_info +subcategory: "IBM REST API" +--- + +# ibm_backup_recovery_manager_get_upgrades_info + +Provides a read-only data source to retrieve information about a backup_recovery_manager_get_upgrades_info. 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_backup_recovery_manager_get_upgrades_info" "backup_recovery_manager_get_upgrades_info" { +} +``` + +## Argument Reference + +You can specify the following arguments for this data source. + +* `cluster_identifiers` - (Optional, List) Fetch upgrade progress details for a list of cluster identifiers in format clusterId:clusterIncarnationId. + +## Attribute Reference + +After your data source is created, you can read values from the following attributes. + +* `id` - The unique identifier of the backup_recovery_manager_get_upgrades_info. +* `upgrades_info` - (List) +Nested schema for **upgrades_info**: + * `cluster_id` - (Integer) Specifies cluster's id. + * `cluster_incarnation_id` - (Integer) Specifies cluster's incarnation id. + * `patch_software_version` - (String) Patch software version against which these logs are generated. This is specified for Patch type only. + * `software_version` - (String) Upgrade software version against which these logs are generated. + * `type` - (String) Specifies the type of upgrade on a cluster. + * Constraints: Allowable values are: `Upgrade`, `Patch`, `UpgradePatch`. + * `upgrade_logs` - (List) Upgrade logs per node. + Nested schema for **upgrade_logs**: + * `logs` - (List) Upgrade logs for the node. + Nested schema for **logs**: + * `log` - (String) One log statement of the complete logs. + * `time_stamp` - (Integer) Time at which this log got generated. + * `node_id` - (String) Id of the node. + * `upgrade_percent_complete` - (Float) Upgrade percentage complete so far. + * `upgrade_status` - (String) Upgrade status. + * Constraints: Allowable values are: `Scheduled`, `Complete`, `InProgress`, `Failed`, `ClusterUnreachable`. + diff --git a/website/docs/r/backup_recovery_manager_cancel_cluster_upgrades.html.markdown b/website/docs/r/backup_recovery_manager_cancel_cluster_upgrades.html.markdown new file mode 100644 index 0000000000..4065fa09f4 --- /dev/null +++ b/website/docs/r/backup_recovery_manager_cancel_cluster_upgrades.html.markdown @@ -0,0 +1,41 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_backup_recovery_manager_cancel_cluster_upgrades" +description: |- + Manages backup_recovery_manager_cancel_cluster_upgrades. +subcategory: "IBM REST API" +--- + +# ibm_backup_recovery_manager_cancel_cluster_upgrades + +Create, update, and delete backup_recovery_manager_cancel_cluster_upgradess with this resource. + +## Example Usage + +```hcl +resource "ibm_backup_recovery_manager_cancel_cluster_upgrades" "backup_recovery_manager_cancel_cluster_upgrades_instance" { +} +``` + +## Argument Reference + +You can specify the following arguments for this resource. + +* `cluster_identifiers` - (Required, Forces new resource, List) Specifies the list of cluster identifiers. The format is clusterId:clusterIncarnationId. + * Constraints: The list items must match regular expression `/^([0-9]+:[0-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 backup_recovery_manager_cancel_cluster_upgrades. +* `cancelled_upgrade_response_list` - (List) Specifies list of cluster scheduled uprgade cancel response. +Nested schema for **cancelled_upgrade_response_list**: + * `cluster_id` - (Integer) Specifies cluster id. + * `cluster_incarnation_id` - (Integer) Specifies cluster incarnation id. + * `error_message` - (String) Specifies an error message if failed to cancel a scheduled upgrade. + * `is_upgrade_cancel_successful` - (Boolean) Specifies if scheduled upgrade cancelling was successful. + + +## Import +Not Supported diff --git a/website/docs/r/backup_recovery_manager_create_cluster_upgrades.html.markdown b/website/docs/r/backup_recovery_manager_create_cluster_upgrades.html.markdown new file mode 100644 index 0000000000..e467cb3a23 --- /dev/null +++ b/website/docs/r/backup_recovery_manager_create_cluster_upgrades.html.markdown @@ -0,0 +1,65 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_backup_recovery_manager_create_cluster_upgrades" +description: |- + Manages backup_recovery_manager_create_cluster_upgrades. +subcategory: "IBM REST API" +--- + +# ibm_backup_recovery_manager_create_cluster_upgrades + +Create, update, and delete backup_recovery_manager_create_cluster_upgradess with this resource. + +## Example Usage + +```hcl +resource "ibm_backup_recovery_manager_create_cluster_upgrades" "backup_recovery_manager_create_cluster_upgrades_instance" { +} +``` + +## Argument Reference + +You can specify the following arguments for this resource. + +* `auth_headers` - (Optional, Forces new resource, List) Specifies the optional headers for upgrade request. +Nested schema for **auth_headers**: + * `key` - (Required, String) Specifies the key or name of the header. + * `value` - (Required, String) Specifies the value of the header. +* `clusters` - (Required, Forces new resource, List) Array for clusters to be upgraded. +Nested schema for **clusters**: + * `cluster_id` - (Optional, Integer) Specifies cluster id. + * `cluster_incarnation_id` - (Optional, Integer) Specifies cluster incarnation id. + * `current_version` - (Optional, String) Specifies current version of cluster. +* `interval_for_rolling_upgrade_in_hours` - (Optional, Forces new resource, Integer) Specifies the difference of time between two cluster's upgrade. +* `package_url` - (Optional, Forces new resource, String) Specifies URL from which package can be downloaded. Note: This option is only supported in Multi-Cluster Manager (MCM). +* `patch_upgrade_params` - (Optional, Forces new resource, List) Specifies the parameters for patch upgrade request. +Nested schema for **patch_upgrade_params**: + * `auth_headers` - (Optional, List) Specifies the optional headers for the patch cluster request. + Nested schema for **auth_headers**: + * `key` - (Required, String) Specifies the key or name of the header. + * `value` - (Required, String) Specifies the value of the header. + * `ignore_pre_checks_failure` - (Optional, Boolean) Specify if pre check results can be ignored. + * Constraints: The default value is `false`. + * `package_url` - (Optional, String) Specifies URL from which patch package can be downloaded. Note: This option is only supported in Multi-Cluster Manager (MCM). + * `target_version` - (Optional, String) Specifies target patch version to which clusters are to be upgraded. +* `target_version` - (Optional, Forces new resource, String) Specifies target version to which clusters are to be upgraded. +* `time_stamp_to_upgrade_at_msecs` - (Optional, Forces new resource, Integer) Specifies the time in msecs at which the cluster has to be upgraded. +* `type` - (Optional, Forces new resource, String) Specifies the type of upgrade to be performed on a cluster. + * Constraints: The default value is `Upgrade`. Allowable values are: `Upgrade`, `Patch`, `UpgradePatch`. + + +## 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 backup_recovery_manager_create_cluster_upgrades. +* `upgrade_response_list` - (List) Specifies a list of disks to exclude from being protected. This is only applicable to VM objects. +Nested schema for **upgrade_response_list**: + * `cluster_id` - (Integer) Specifies cluster id. + * `cluster_incarnation_id` - (Integer) Specifies cluster incarnation id. + * `error_message` - (String) Specifies error message if failed to schedule upgrade. + * `is_upgrade_scheduling_successful` - (Boolean) Specifies if upgrade scheduling was successsful. + + +## Import +Not Supported diff --git a/website/docs/r/backup_recovery_manager_update_cluster_upgrades.html.markdown b/website/docs/r/backup_recovery_manager_update_cluster_upgrades.html.markdown new file mode 100644 index 0000000000..283d84c5e7 --- /dev/null +++ b/website/docs/r/backup_recovery_manager_update_cluster_upgrades.html.markdown @@ -0,0 +1,76 @@ +--- +layout: "ibm" +page_title: "IBM : ibm_backup_recovery_manager_update_cluster_upgrades" +description: |- + Manages backup_recovery_manager_update_cluster_upgrades. +subcategory: "IBM REST API" +--- + +# ibm_backup_recovery_manager_update_cluster_upgrades + +Create, update, and delete backup_recovery_manager_update_cluster_upgradess with this resource. + +## Example Usage + +```hcl +resource "ibm_backup_recovery_manager_update_cluster_upgrades" "backup_recovery_manager_update_cluster_upgrades_instance" { + auth_headers { + key = "key" + value = "value" + } + clusters { + cluster_id = 1 + cluster_incarnation_id = 1 + current_version = "current_version" + } + patch_upgrade_params { + auth_headers { + key = "key" + value = "value" + } + ignore_pre_checks_failure = true + package_url = "package_url" + target_version = "target_version" + } +} +``` + +## Argument Reference + +You can specify the following arguments for this resource. + +* `auth_headers` - (Optional, Forces new resource, List) Specifies the optional headers for upgrade request. +Nested schema for **auth_headers**: + * `key` - (Required, String) Specifies the key or name of the header. + * `value` - (Required, String) Specifies the value of the header. +* `clusters` - (Required, Forces new resource, List) Array for clusters to be upgraded. +Nested schema for **clusters**: + * `cluster_id` - (Optional, Integer) Specifies cluster id. + * `cluster_incarnation_id` - (Optional, Integer) Specifies cluster incarnation id. + * `current_version` - (Optional, String) Specifies current version of cluster. +* `interval_for_rolling_upgrade_in_hours` - (Optional, Forces new resource, Integer) Specifies the difference of time between two cluster's upgrade. +* `package_url` - (Optional, Forces new resource, String) Specifies URL from which package can be downloaded. Note: This option is only supported in Multi-Cluster Manager (MCM). +* `patch_upgrade_params` - (Optional, Forces new resource, List) Specifies the parameters for patch upgrade request. +Nested schema for **patch_upgrade_params**: + * `auth_headers` - (Optional, List) Specifies the optional headers for the patch cluster request. + Nested schema for **auth_headers**: + * `key` - (Required, String) Specifies the key or name of the header. + * `value` - (Required, String) Specifies the value of the header. + * `ignore_pre_checks_failure` - (Optional, Boolean) Specify if pre check results can be ignored. + * Constraints: The default value is `false`. + * `package_url` - (Optional, String) Specifies URL from which patch package can be downloaded. Note: This option is only supported in Multi-Cluster Manager (MCM). + * `target_version` - (Optional, String) Specifies target patch version to which clusters are to be upgraded. +* `target_version` - (Optional, Forces new resource, String) Specifies target version to which clusters are to be upgraded. +* `time_stamp_to_upgrade_at_msecs` - (Optional, Forces new resource, Integer) Specifies the time in msecs at which the cluster has to be upgraded. +* `type` - (Optional, Forces new resource, String) Specifies the type of upgrade to be performed on a cluster. + * Constraints: The default value is `Upgrade`. Allowable values are: `Upgrade`, `Patch`, `UpgradePatch`. + +## 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 backup_recovery_manager_update_cluster_upgrades. + + +## Import +Not Supported diff --git a/website/docs/r/backup_recovery_source_registration.html.markdown b/website/docs/r/backup_recovery_source_registration.html.markdown index 132579ce41..9c1bd3fe05 100644 --- a/website/docs/r/backup_recovery_source_registration.html.markdown +++ b/website/docs/r/backup_recovery_source_registration.html.markdown @@ -18,12 +18,9 @@ resource "ibm_backup_recovery_source_registration" "backup_recovery_source_regis key = "key" value = "value" } - connections { - connection_id = 1 - entity_id = 1 - connector_group_id = 1 - data_source_connection_id = "data_source_connection_id" - } + + connection_id = 1 + environment = "kPhysical" kubernetes_params { auto_protect_config {